From 30a2ad98246c3c9a2be90a65170b8fb66712d4ab Mon Sep 17 00:00:00 2001 From: 18392181980 Date: Thu, 21 Oct 2021 15:57:05 +0800 Subject: [PATCH 1/2] usb_service_commit_1021 --- LICENSE | 177 ++ hdi/BUILD.gn | 21 + hdi/api/include/usbd_api.h | 240 ++ hdi/client/BUILD.gn | 49 + hdi/client/include/readme.md | 27 + hdi/client/include/usbd_client.h | 99 + hdi/client/include/usbd_subscriber.h | 41 + hdi/client/src/usbd_client.cpp | 615 +++++ hdi/client/src/usbd_subscriber.cpp | 110 + hdi/service/BUILD.gn | 84 + hdi/service/include/usbd.h | 99 + hdi/service/include/usbd_dispatcher.h | 22 + hdi/service/include/usbd_function.h | 23 + hdi/service/include/usbd_parser.h | 37 + hdi/service/include/usbd_port.h | 24 + hdi/service/include/usbd_publisher.h | 36 + hdi/service/src/usbd.c | 326 +++ hdi/service/src/usbd_dispatcher.c | 2087 +++++++++++++++++ hdi/service/src/usbd_function.c | 206 ++ hdi/service/src/usbd_port.c | 149 ++ hdi/service/src/usbd_publisher.c | 91 + hdi/test/BUILD.gn | 22 + hdi/test/unittest/common/BUILD.gn | 294 +++ .../common/include/usbd_config_test.h | 27 + .../common/include/usbd_descriptor_test.h | 27 + .../common/include/usbd_device_test.h | 27 + .../common/include/usbd_function_test.h | 27 + .../common/include/usbd_interface_test.h | 27 + .../unittest/common/include/usbd_port_test.h | 27 + .../common/include/usbd_request_test.h | 27 + .../common/include/usbd_transfer_test.h | 27 + .../unittest/common/src/usbd_config_test.cpp | 308 +++ .../common/src/usbd_descriptor_test.cpp | 680 ++++++ .../unittest/common/src/usbd_device_test.cpp | 230 ++ .../common/src/usbd_function_test.cpp | 227 ++ .../common/src/usbd_interface_test.cpp | 643 +++++ .../unittest/common/src/usbd_port_test.cpp | 188 ++ .../unittest/common/src/usbd_request_test.cpp | 1091 +++++++++ .../common/src/usbd_transfer_test.cpp | 824 +++++++ interfaces/innerkits/BUILD.gn | 55 + .../innerkits/native/include/iusb_srv.h | 125 + .../innerkits/native/include/usb_config.h | 150 ++ .../innerkits/native/include/usb_device.h | 289 +++ .../native/include/usb_device_pipe.h | 57 + .../innerkits/native/include/usb_endpoint.h | 130 + .../innerkits/native/include/usb_info.h | 87 + .../innerkits/native/include/usb_interface.h | 153 ++ .../innerkits/native/include/usb_port.h | 76 + .../native/include/usb_port_status.h | 53 + .../innerkits/native/include/usb_request.h | 102 + .../innerkits/native/include/usb_srv_client.h | 111 + .../innerkits/native/src/usb_device.cpp | 22 + .../innerkits/native/src/usb_device_pipe.cpp | 103 + .../innerkits/native/src/usb_request.cpp | 51 + .../innerkits/native/src/usb_srv_client.cpp | 401 ++++ interfaces/kits/java/BUILD.gn | 54 + .../ohos/usb/IUSBDevicePipeController.java | 42 + .../java/ohos/usb/IUSBRequestController.java | 28 + .../java/ohos/usb/IUsbCoreController.java | 43 + interfaces/kits/java/ohos/usb/USBConfig.java | 143 ++ interfaces/kits/java/ohos/usb/USBCore.java | 191 ++ interfaces/kits/java/ohos/usb/USBDevice.java | 290 +++ .../kits/java/ohos/usb/USBDevicePipe.java | 263 +++ .../ohos/usb/USBDevicePipeController.java | 142 ++ .../kits/java/ohos/usb/USBEndpoint.java | 151 ++ .../kits/java/ohos/usb/USBInterface.java | 172 ++ .../kits/java/ohos/usb/USBLoggerFactory.java | 46 + interfaces/kits/java/ohos/usb/USBPort.java | 4 + interfaces/kits/java/ohos/usb/USBRequest.java | 131 ++ .../kits/java/ohos/usb/UsbCoreController.java | 142 ++ .../java/ohos/usb/UsbCoreControllerProxy.java | 414 ++++ .../usb/UsbDevicePipeControllerProxy.java | 173 ++ .../kits/java/ohos/usb/UsbKitsUtils.java | 7 + .../kits/java/ohos/usb/UsbPortStatus.java | 4 + .../java/ohos/usb/UsbRequestController.java | 142 ++ .../ohos/usb/UsbRequestControllerProxy.java | 134 ++ .../kits/java/ohos/usb/package-info.java | 24 + interfaces/kits/js/@ohos.usb.d.ts | 789 +++++++ interfaces/kits/js/napi/BUILD.gn | 48 + interfaces/kits/js/napi/usb_async_context.h | 75 + interfaces/kits/js/napi/usb_info.cpp | 1459 ++++++++++++ interfaces/kits/js/test/CheckEmptyUtils.js | 68 + interfaces/kits/js/test/DateAndTimeUtil.js | 114 + interfaces/kits/js/test/EventConstants.js | 66 + interfaces/kits/js/test/ListUsb.test.js | 25 + interfaces/kits/js/test/UsbCoreJsunit.test.js | 254 ++ .../kits/js/test/UsbDevicePipeJsunit.test.js | 358 +++ .../kits/js/test/UsbFunctionsJsunit.test.js | 218 ++ interfaces/kits/js/test/UsbPortJsunit.test.js | 141 ++ interfaces/kits/js/test/usb_unit.test.js | 495 ++++ ohos.build | 32 + sa_profile/4201.xml | 24 + sa_profile/BUILD.gn | 19 + services/BUILD.gn | 69 + .../native/include/usb_descriptor_parser.h | 37 + .../native/include/usb_function_manager.h | 55 + services/native/include/usb_host_manager.h | 45 + services/native/include/usb_port_manager.h | 51 + services/native/include/usb_right_manager.h | 43 + services/native/include/usb_serial_reader.h | 41 + .../native/include/usb_server_event_handler.h | 40 + services/native/include/usb_service.h | 148 ++ .../native/include/usb_service_subscriber.h | 36 + services/native/src/usb_descriptor_parser.cpp | 247 ++ services/native/src/usb_function_manager.cpp | 114 + services/native/src/usb_host_manager.cpp | 75 + services/native/src/usb_port_manager.cpp | 134 ++ services/native/src/usb_right_manager.cpp | 83 + services/native/src/usb_serial_reader.cpp | 32 + .../native/src/usb_server_event_handler.cpp | 35 + services/native/src/usb_service.cpp | 556 +++++ .../native/src/usb_service_subscriber.cpp | 119 + services/native/test/BUILD.gn | 22 + services/native/test/unittest/common/BUILD.gn | 166 ++ .../unittest/common/include/usb_core_test.h | 28 + .../common/include/usb_device_pipe_test.h | 29 + .../common/include/usb_request_test.h | 28 + .../unittest/common/src/usb_core_test.cpp | 381 +++ .../common/src/usb_device_pipe_test.cpp | 1778 ++++++++++++++ .../common/src/usb_port_service_test.cpp | 200 ++ .../unittest/common/src/usb_request_test.cpp | 712 ++++++ services/zidl/include/usb_server_proxy.h | 110 + services/zidl/include/usb_server_stub.h | 85 + services/zidl/iusb_server.zidl | 19 + services/zidl/src/usb_srv_proxy.cpp | 887 +++++++ services/zidl/src/usb_srv_stub.cpp | 663 ++++++ test/native/BUILD.gn | 20 + test/native/unittest/BUILD.gn | 72 + .../unittest/include/usb_service_test.h | 26 + test/native/unittest/src/usb_service_test.cpp | 224 ++ usbmgr.gni | 18 + utils/BUILD.gn | 21 + utils/native/include/delayed_sp_singleton.h | 62 + utils/native/include/hilog_wrapper.h | 108 + utils/native/include/usb_common.h | 143 ++ utils/native/include/usb_errors.h | 48 + 136 files changed, 25986 insertions(+) create mode 100644 LICENSE create mode 100644 hdi/BUILD.gn create mode 100644 hdi/api/include/usbd_api.h create mode 100644 hdi/client/BUILD.gn create mode 100644 hdi/client/include/readme.md create mode 100644 hdi/client/include/usbd_client.h create mode 100644 hdi/client/include/usbd_subscriber.h create mode 100644 hdi/client/src/usbd_client.cpp create mode 100644 hdi/client/src/usbd_subscriber.cpp create mode 100644 hdi/service/BUILD.gn create mode 100644 hdi/service/include/usbd.h create mode 100644 hdi/service/include/usbd_dispatcher.h create mode 100644 hdi/service/include/usbd_function.h create mode 100644 hdi/service/include/usbd_parser.h create mode 100644 hdi/service/include/usbd_port.h create mode 100644 hdi/service/include/usbd_publisher.h create mode 100644 hdi/service/src/usbd.c create mode 100644 hdi/service/src/usbd_dispatcher.c create mode 100644 hdi/service/src/usbd_function.c create mode 100644 hdi/service/src/usbd_port.c create mode 100644 hdi/service/src/usbd_publisher.c create mode 100644 hdi/test/BUILD.gn create mode 100644 hdi/test/unittest/common/BUILD.gn create mode 100644 hdi/test/unittest/common/include/usbd_config_test.h create mode 100644 hdi/test/unittest/common/include/usbd_descriptor_test.h create mode 100644 hdi/test/unittest/common/include/usbd_device_test.h create mode 100644 hdi/test/unittest/common/include/usbd_function_test.h create mode 100644 hdi/test/unittest/common/include/usbd_interface_test.h create mode 100644 hdi/test/unittest/common/include/usbd_port_test.h create mode 100644 hdi/test/unittest/common/include/usbd_request_test.h create mode 100644 hdi/test/unittest/common/include/usbd_transfer_test.h create mode 100644 hdi/test/unittest/common/src/usbd_config_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_descriptor_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_device_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_function_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_interface_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_port_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_request_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_transfer_test.cpp create mode 100644 interfaces/innerkits/BUILD.gn create mode 100644 interfaces/innerkits/native/include/iusb_srv.h create mode 100644 interfaces/innerkits/native/include/usb_config.h create mode 100644 interfaces/innerkits/native/include/usb_device.h create mode 100644 interfaces/innerkits/native/include/usb_device_pipe.h create mode 100644 interfaces/innerkits/native/include/usb_endpoint.h create mode 100644 interfaces/innerkits/native/include/usb_info.h create mode 100644 interfaces/innerkits/native/include/usb_interface.h create mode 100644 interfaces/innerkits/native/include/usb_port.h create mode 100644 interfaces/innerkits/native/include/usb_port_status.h create mode 100644 interfaces/innerkits/native/include/usb_request.h create mode 100644 interfaces/innerkits/native/include/usb_srv_client.h create mode 100644 interfaces/innerkits/native/src/usb_device.cpp create mode 100644 interfaces/innerkits/native/src/usb_device_pipe.cpp create mode 100644 interfaces/innerkits/native/src/usb_request.cpp create mode 100644 interfaces/innerkits/native/src/usb_srv_client.cpp create mode 100644 interfaces/kits/java/BUILD.gn create mode 100644 interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java create mode 100644 interfaces/kits/java/ohos/usb/IUSBRequestController.java create mode 100644 interfaces/kits/java/ohos/usb/IUsbCoreController.java create mode 100644 interfaces/kits/java/ohos/usb/USBConfig.java create mode 100644 interfaces/kits/java/ohos/usb/USBCore.java create mode 100644 interfaces/kits/java/ohos/usb/USBDevice.java create mode 100644 interfaces/kits/java/ohos/usb/USBDevicePipe.java create mode 100644 interfaces/kits/java/ohos/usb/USBDevicePipeController.java create mode 100644 interfaces/kits/java/ohos/usb/USBEndpoint.java create mode 100644 interfaces/kits/java/ohos/usb/USBInterface.java create mode 100644 interfaces/kits/java/ohos/usb/USBLoggerFactory.java create mode 100644 interfaces/kits/java/ohos/usb/USBPort.java create mode 100644 interfaces/kits/java/ohos/usb/USBRequest.java create mode 100644 interfaces/kits/java/ohos/usb/UsbCoreController.java create mode 100644 interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java create mode 100644 interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java create mode 100644 interfaces/kits/java/ohos/usb/UsbKitsUtils.java create mode 100644 interfaces/kits/java/ohos/usb/UsbPortStatus.java create mode 100644 interfaces/kits/java/ohos/usb/UsbRequestController.java create mode 100644 interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java create mode 100644 interfaces/kits/java/ohos/usb/package-info.java create mode 100644 interfaces/kits/js/@ohos.usb.d.ts create mode 100644 interfaces/kits/js/napi/BUILD.gn create mode 100644 interfaces/kits/js/napi/usb_async_context.h create mode 100644 interfaces/kits/js/napi/usb_info.cpp create mode 100644 interfaces/kits/js/test/CheckEmptyUtils.js create mode 100644 interfaces/kits/js/test/DateAndTimeUtil.js create mode 100644 interfaces/kits/js/test/EventConstants.js create mode 100644 interfaces/kits/js/test/ListUsb.test.js create mode 100644 interfaces/kits/js/test/UsbCoreJsunit.test.js create mode 100644 interfaces/kits/js/test/UsbDevicePipeJsunit.test.js create mode 100644 interfaces/kits/js/test/UsbFunctionsJsunit.test.js create mode 100644 interfaces/kits/js/test/UsbPortJsunit.test.js create mode 100644 interfaces/kits/js/test/usb_unit.test.js create mode 100644 ohos.build create mode 100644 sa_profile/4201.xml create mode 100644 sa_profile/BUILD.gn create mode 100644 services/BUILD.gn create mode 100644 services/native/include/usb_descriptor_parser.h create mode 100644 services/native/include/usb_function_manager.h create mode 100644 services/native/include/usb_host_manager.h create mode 100644 services/native/include/usb_port_manager.h create mode 100644 services/native/include/usb_right_manager.h create mode 100644 services/native/include/usb_serial_reader.h create mode 100644 services/native/include/usb_server_event_handler.h create mode 100644 services/native/include/usb_service.h create mode 100644 services/native/include/usb_service_subscriber.h create mode 100644 services/native/src/usb_descriptor_parser.cpp create mode 100644 services/native/src/usb_function_manager.cpp create mode 100644 services/native/src/usb_host_manager.cpp create mode 100644 services/native/src/usb_port_manager.cpp create mode 100644 services/native/src/usb_right_manager.cpp create mode 100644 services/native/src/usb_serial_reader.cpp create mode 100644 services/native/src/usb_server_event_handler.cpp create mode 100644 services/native/src/usb_service.cpp create mode 100644 services/native/src/usb_service_subscriber.cpp create mode 100644 services/native/test/BUILD.gn create mode 100644 services/native/test/unittest/common/BUILD.gn create mode 100644 services/native/test/unittest/common/include/usb_core_test.h create mode 100644 services/native/test/unittest/common/include/usb_device_pipe_test.h create mode 100644 services/native/test/unittest/common/include/usb_request_test.h create mode 100644 services/native/test/unittest/common/src/usb_core_test.cpp create mode 100644 services/native/test/unittest/common/src/usb_device_pipe_test.cpp create mode 100644 services/native/test/unittest/common/src/usb_port_service_test.cpp create mode 100644 services/native/test/unittest/common/src/usb_request_test.cpp create mode 100644 services/zidl/include/usb_server_proxy.h create mode 100644 services/zidl/include/usb_server_stub.h create mode 100644 services/zidl/iusb_server.zidl create mode 100644 services/zidl/src/usb_srv_proxy.cpp create mode 100644 services/zidl/src/usb_srv_stub.cpp create mode 100644 test/native/BUILD.gn create mode 100644 test/native/unittest/BUILD.gn create mode 100644 test/native/unittest/include/usb_service_test.h create mode 100644 test/native/unittest/src/usb_service_test.cpp create mode 100644 usbmgr.gni create mode 100644 utils/BUILD.gn create mode 100644 utils/native/include/delayed_sp_singleton.h create mode 100644 utils/native/include/hilog_wrapper.h create mode 100644 utils/native/include/usb_common.h create mode 100644 utils/native/include/usb_errors.h diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..4947287f --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/hdi/BUILD.gn b/hdi/BUILD.gn new file mode 100644 index 00000000..e2b675c4 --- /dev/null +++ b/hdi/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("hdi_group") { + deps = [ + "client:usbd_client", + "service:usbd" + ] +} diff --git a/hdi/api/include/usbd_api.h b/hdi/api/include/usbd_api.h new file mode 100644 index 00000000..541b5bca --- /dev/null +++ b/hdi/api/include/usbd_api.h @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_API_H +#define USBD_API_H + +#include +#include + +#define USB_MAX_INTERFACES 32 +typedef void (*UsbdRequestCallback)(void *requestArg); + +enum UsbdDeviceAction { + ACT_DEVUP = 0, + ACT_DEVDOWN, + ACT_UPDEVICE, + ACT_DOWNDEVICE, +}; + +enum UsbdCmd { + CMD_BIND_USB_SUBSCRIBER = 0, + CMD_UNBIND_USB_SUBSCRIBER, + CMD_NOTIFY_DEVICE_DOWN, + CMD_NOTIFY_DEVICE_FOUND, + CMD_NOTIFY_PORT_CHANGED, + CMD_CLASS_CTRL_SYNC, + CMD_FUN_ADD_FUNCTION, + CMD_FUN_ADD_INTERFACE, + CMD_FUN_CLAIM_INTERFACE, + CMD_FUN_CLOSE_DEVICE, + CMD_FUN_CONNECT_DEVICE, + CMD_FUN_DELETE_INTERFACE, + CMD_FUN_GET_CONFIG, + CMD_FUN_GET_CURRENT_FUNCTIONS, + CMD_FUN_GET_DESCRIPTOR, + CMD_FUN_GET_DEVICE_DESCRIPTOR, + CMD_FUN_GET_CONFIG_DESCRIPTOR, + CMD_FUN_GET_STRING_DESCRIPTOR, + CMD_FUN_GET_INTERFACE_DESCRIPTOR, + CMD_FUN_GET_ENDPOINT_DESCRIPTOR, + CMD_FUN_HANDLE_REQUEST, + CMD_FUN_OPEN_DEVICE, + CMD_FUN_RELEASE_INTERFACE, + CMD_FUN_REMOVE_FUNCTION, + CMD_FUN_REMOVE_INTERFACE, + CMD_FUN_SEND_BULK_READ_ASYNC, + CMD_FUN_SEND_BULK_READ_SYNC, + CMD_FUN_SEND_BULK_WRITE_ASYNC, + CMD_FUN_SEND_BULK_WRITE_SYNC, + CMD_FUN_SEND_CTRL_READ_ASYNC, + CMD_FUN_SEND_CTRL_READ_SYNC, + CMD_FUN_SEND_CTRL_REQUEST_ASYNC, + CMD_FUN_SEND_CTRL_REQUEST_SYNC, + CMD_FUN_SEND_CTRL_WRITE_ASYNC, + CMD_FUN_SEND_CTRL_WRITE_SYNC, + CMD_FUN_SEND_INTERRUPT_READ_ASYNC, + CMD_FUN_SEND_INTERRUPT_READ_SYNC, + CMD_FUN_SEND_INTERRUPT_WRITE_ASYNC, + CMD_FUN_SEND_INTERRUPT_WRITE_SYNC, + CMD_FUN_SEND_ISO_READ_ASYNC, + CMD_FUN_SEND_ISO_READ_SYNC, + CMD_FUN_SEND_ISO_WRITE_ASYNC, + CMD_FUN_SEND_ISO_WRITE_SYNC, + CMD_FUN_SET_CONFIG, + CMD_FUN_SET_CURRENT_FUNCTIONS, + CMD_FUN_SET_INTERFACE, + CMD_ADD_INTERFACE, + CMD_REMOVE_INTERFACE, + CMD_GET_CHARGE_STATE, + CMD_GET_DEVICES, + CMD_HAS_RIGHT, + CMD_READ_DATA_SYNC, + CMD_READ_PARM, + CMD_SET_BAUDRATE, + CMD_SET_ROLE, + CMD_QUERY_PORT, + CMD_STD_CTRL_GET_CONFIGURATION, + CMD_STD_CTRL_GET_DESCRIPTOR_ASYNC, + CMD_STD_CTRL_GET_DESCRIPTOR_CMD, + CMD_STD_CTRL_GET_INTERFACE, + CMD_STD_CTRL_GET_STATUS_CMD, + CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT, + CMD_FUN_REQUEST_QUEUE, + CMD_FUN_REQUEST_WAIT, + CMD_FUN_REQUEST_CANCEL +}; + +struct UsbdDevice { + uint8_t busNum; + uint8_t devAddr; + uint8_t interface; + uint8_t endPoint; +}; +struct UsbdPeripheral { + uint8_t busNum; + uint8_t devAddr; + uint8_t iSerialNumber; +}; +struct UsbdPort { + uint8_t modes; + uint8_t roles; +}; +struct UsbdRequestDataSync { + uint8_t endPoint; + int32_t *requested; + uint8_t *data; + int32_t length; + uint32_t timeout; +}; +struct UsbdRequestDataAsync { + unsigned char endPoint; + unsigned char *buffer; + int length; + int numIsoPackets; + UsbdRequestCallback callback; + void *userData; + unsigned int timeout; +}; +struct UsbdControlRequestSetupData { + uint8_t requestType; + uint8_t requestCmd; + uint16_t value; + uint16_t index; + uint8_t *data; + uint16_t length; + uint32_t timeout; +}; +struct UsbdDescriptorParam { + uint8_t descType; + uint8_t descIndex; + int length; +}; +struct UsbdDescriptorHeader { + uint8_t bLength; + uint8_t bDescriptorType; +} __attribute__((packed)); + +struct UsbdDeviceDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} __attribute__((packed)); + +struct UsbdConfigDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t bMaxPower; +} __attribute__((packed)); + +struct UsbdInterfaceDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; + uint8_t bInterfaceSubClass; + uint8_t bInterfaceProtocol; + uint8_t iInterface; +} __attribute__((packed)); + +struct UsbdEndpointDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint16_t wMaxPacketSize; + uint8_t bInterval; +} __attribute__((packed)); + +struct UsbNotifyServiceInfo { + uint32_t length; + + int32_t devNum; + int32_t busNum; + + int32_t interfaceLength; + uint8_t interfaceNumber[USB_MAX_INTERFACES]; +} __attribute__((packed)); + +enum PortRoleType { DATA_ROLE, POWER_ROLE, MODE }; + +enum PortPowerRole { SOURCE, SINK }; + +enum PortMode { HOST, DEVICE, OTG }; + +struct PortInfo { + int32_t portId; + int32_t powerRole; + int32_t dataRole; + int32_t mode; +}; + +// Keep it same as the inner kit usb_info.h +struct UsbdInfo { + int32_t capacity_; + int32_t voltage_; + int32_t temperature_; + int32_t healthState_; + int32_t pluggedType_; + int32_t pluggedMaxCurrent_; + int32_t pluggedMaxVoltage_; + int32_t chargeState_; + int32_t chargeCounter_; + int8_t present_; + const char *technology_; +}; + +struct UsbdRequest { +}; + +#endif // USBD_API_H diff --git a/hdi/client/BUILD.gn b/hdi/client/BUILD.gn new file mode 100644 index 00000000..382e5657 --- /dev/null +++ b/hdi/client/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") + +config("usbd_client_public_config") { + include_dirs = [ + "include", + "${usb_manager_path}/hdi/api/include", + "${usb_manager_path}/interfaces/innerkits/native/include", + ] +} + +ohos_shared_library("usbd_client") { + sources = [ + "src/usbd_client.cpp", + "src/usbd_subscriber.cpp", + ] + + configs = [ "${utils_path}:utils_config" ] + + public_configs = [ ":usbd_client_public_config" ] + + deps = [ + "${hdf_uhdf_path}/hdi:libhdi", + "${hdf_uhdf_path}/host:libhdf_host", + "${hdf_uhdf_path}/osal:libhdf_utils", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + part_name = "usb_manager_native" +} diff --git a/hdi/client/include/readme.md b/hdi/client/include/readme.md new file mode 100644 index 00000000..1d811a1e --- /dev/null +++ b/hdi/client/include/readme.md @@ -0,0 +1,27 @@ +**USB HDI API 接口** + +| C++接口申明 | C++接口描述 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| int32_t OpenDevice(uint8_t busNum, uint8_t devAddr); | 打开设备,建立连接 | +| int32_t CloseDevice(uint8_t busNum, uint8_t devAddr); | 关闭设备,释放与设备相关的所有系统资源 | +| int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length); | 获取设备描述符 | +| int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); | 获取设备的配置描述符 | +| int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); | 获取设备的字符串描述符 | +| int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex); | 设置设备当前使用的配置,通过配置值进行指定 | +| int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex); | 获取当前生效的配置值 | +| int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface); | 打开接口,并申明独占接口,必须在数据传输前执行 | +| int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface); | 关闭接口,释放接口的占用,在停止数据传输后执行 | +| int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface, uint8_t altIndex); | 设置指定接口的备选设置,用于在具有相同ID但不同备用设置的两个接口之间进行选择 | +| int32_t BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行批量数据读取, 返回读取的数据和长度,端点方向必须为数据读取 | +| int32_t BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行批量数据写入, 返回读取的数据和长度,端点方向必须为数据写入 | +| int32_t ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams ¶ms); | 对此设备执行端点零的控制事务,传输方向由请求类型决定。 如果requestType& USB_ENDPOINT_DIR_MASK是USB_DIR_OUT ,则传输是写入,如果是USB_DIR_IN ,则传输是读取。 | +| int32_t InterruptTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行中断数据读取, 返回读取的数据和长度,端点方向必须为数据读取 | +| int32_t InterruptTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行中断数据写入, 返回读取的数据和长度,端点方向必须为数据写入 | +| int32_t IsoTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行等时数据读取, 返回读取的数据和长度,端点方向必须为数据读取 | +| int32_t IsoTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行等时数据写入, 返回读取的数据和长度,端点方向必须为数据写入 | +| int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct RequestParams ¶ms); | 将指定的端点进行异步数据发送或者接收请求,数据传输方向由端点方向决定 | +| int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); | 等待RequestQueue异步请求的操作结果 | +| int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interface, uint8_t endpoint); | 取消待处理的数据请求 | +| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | 设置端口工作模式(从设备) | +| int32_t GetCurrentFunctions(uint8_t busNum, uint8_t devAddr, int32_t *funcs) | 获取从设备支持的功能列表(按位域表示)(从设备) | +| int32_t SetCurrentFunctions(uint8_t busNum, uint8_t devAddr, int32_t funcs) | 设置从设备支持的功能列表(按位域表示)(从设备) | \ No newline at end of file diff --git a/hdi/client/include/usbd_client.h b/hdi/client/include/usbd_client.h new file mode 100644 index 00000000..d4a2320c --- /dev/null +++ b/hdi/client/include/usbd_client.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_CLIENT_H +#define USBD_CLIENT_H + +#include "usbd_subscriber.h" + +namespace OHOS { +namespace USB { +struct DescriptorParams { + uint8_t DescId; + uint8_t *buffer; + uint32_t &length; +}; + +struct TransferParams { + uint8_t interfaceid; + uint8_t endpointid; + uint8_t *buffer; + uint32_t &length; + int32_t timeout; +}; + +struct CtrlTransferParamsParams { + int32_t requestType; + int32_t request; + int32_t value; + int32_t index; + uint8_t *buffer; + uint32_t &length; + int32_t timeout; +}; + +struct RequestParams { + void *clientData; + uint32_t &clientLength; + uint8_t *buffer; + uint32_t &length; +}; + +class UsbdClient { +public: + /* usb主设备接口 */ + static int32_t OpenDevice(uint8_t busNum, uint8_t devAddr); + static int32_t CloseDevice(uint8_t busNum, uint8_t devAddr); + static int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length); + static int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length); + static int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex); + static int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex); + static int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid); + static int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid); + static int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex); + static int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + static int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + static int32_t BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams ¶ms); + static int32_t InterruptTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t InterruptTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t IsoTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t IsoTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t + RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct RequestParams ¶ms); + static int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + static int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid); + + /* usb从设备接口 */ + static int32_t GetCurrentFunctions(int32_t &funcs); + static int32_t SetCurrentFunctions(int32_t funcs); + static int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); + static int32_t QueryPort(int32_t &portId, int32_t &powerRole, int32_t &dataRole, int32_t &mode); + + static ErrCode BindUsbdSubscriber(const sptr &subscriber); + static ErrCode UnbindUsbdSubscriber(); + +private: + static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); + static int32_t SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr); + static int32_t SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length); + static int32_t GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length); + static sptr GetUsbdService(); + static ErrCode DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply); +}; +} // namespace USB +} // namespace OHOS +#endif // USBD_CLIENT_H diff --git a/hdi/client/include/usbd_subscriber.h b/hdi/client/include/usbd_subscriber.h new file mode 100644 index 00000000..eab1e2b9 --- /dev/null +++ b/hdi/client/include/usbd_subscriber.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 USBD_SUBSCRIBER_H +#define USBD_SUBSCRIBER_H + +#include "ipc_object_stub.h" +#include "usb_info.h" +#include "usbd_api.h" + +namespace OHOS { +namespace USB { +class UsbdSubscriber : public IPCObjectStub { +public: + explicit UsbdSubscriber() : IPCObjectStub(u"ohos.usb.IUsbManagerSubscriber"){}; + virtual ~UsbdSubscriber() = default; + virtual int32_t DeviceEvent(const UsbInfo &info) = 0; + virtual int32_t PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) = 0; + virtual int32_t Update(const UsbInfo &info) = 0; + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + static FoundDevice &ParserFoundDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option); + static int32_t ParserUsbInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, UsbInfo &info); + static int32_t ParserPortInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, PortInfo &info); +}; +} // namespace USB +} // namespace OHOS +#endif // USBD_SUBSCRIBER_H diff --git a/hdi/client/src/usbd_client.cpp b/hdi/client/src/usbd_client.cpp new file mode 100644 index 00000000..94d08c1d --- /dev/null +++ b/hdi/client/src/usbd_client.cpp @@ -0,0 +1,615 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_client.h" +#include +#include "hilog_wrapper.h" +#include "iservmgr_hdi.h" +#include "message_parcel.h" +#include "securec.h" +#include "usb_common.h" +#include "usbd_api.h" + +namespace OHOS { +namespace USB { +using OHOS::HDI::ServiceManager::V1_0::IServiceManager; + +namespace { +const std::string USBD_SERVICE = "usbd"; +} + +void UsbdClient::PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << 二进制数据流[" << length << "字节] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_SERVICE, "%{public}s", oss.str().c_str()); +} + +sptr UsbdClient::GetUsbdService() +{ + auto serviceManager = IServiceManager::Get(); + if (serviceManager == nullptr) { + USB_HILOGW(MODULE_USBD, "service manager is nullptr"); + return nullptr; + } + auto UsbdService = serviceManager->GetService(USBD_SERVICE.c_str()); + if (UsbdService == nullptr) { + USB_HILOGW(MODULE_USBD, "Usbd service is nullptr"); + return nullptr; + } + return UsbdService; +} + +ErrCode UsbdClient::BindUsbdSubscriber(const sptr &subscriber) +{ + USB_HILOGD(MODULE_USBD, "BindUsbdSubscriber enter"); + if (subscriber == nullptr) { + USB_HILOGW(MODULE_USBD, "subscriber is nullptr"); + return ERR_INVALID_VALUE; + } + + MessageParcel data; + MessageParcel reply; + data.WriteRemoteObject(subscriber); + return DoDispatch(CMD_BIND_USB_SUBSCRIBER, data, reply); +} + +ErrCode UsbdClient::UnbindUsbdSubscriber() +{ + USB_HILOGD(MODULE_USBD, "UnbindUsbdSubscriber enter"); + MessageParcel data; + MessageParcel reply; + return DoDispatch(CMD_UNBIND_USB_SUBSCRIBER, data, reply); +} + +int32_t UsbdClient::OpenDevice(uint8_t busNum, uint8_t devAddr) +{ + MessageParcel data; + MessageParcel reply; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d OpenDevice bus:%{public}d dev:%{public}d", __func__, __LINE__, + busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + ErrCode ret = DoDispatch(CMD_FUN_OPEN_DEVICE, data, reply); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d OpenDevice ret:%{public}d bus:%{public}d dev:%{public}d", __func__, + __LINE__, ret, busNum, devAddr); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d CMD_FUN_OPEN_DEVICE failed, return %{public}d", __func__, + __LINE__, ret); + return ERR_INVALID_VALUE; + } + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d OpenDevice bus:%{public}d dev:%{public}d ", __func__, __LINE__, + busNum, devAddr); + return ERR_OK; +} + +int32_t UsbdClient::GetCurrentFunctions(int32_t &funcs) +{ + USB_HILOGD(MODULE_USBD, "GetCurrentFunctions enter"); + MessageParcel data; + MessageParcel reply; + ErrCode ret = DoDispatch(CMD_FUN_GET_CURRENT_FUNCTIONS, data, reply); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_FUN_GET_CURRENT_FUNCTIONS failed, return INVALID_USB_INT_VALUE"); + return ret; + } + READ_PARCEL_WITH_RET(reply, Int32, funcs, E_READ_PARCEL_ERROR); + USB_HILOGD(MODULE_USBD, "GetCurrentFunctions funcs %{public}d", funcs); + return ERR_OK; +} + +int32_t UsbdClient::SetCurrentFunctions(int32_t funcs) +{ + USB_HILOGD(MODULE_USBD, "SetCurrentFunctions enter"); + MessageParcel data; + MessageParcel reply; + WRITE_PARCEL_WITH_RET(data, Int32, funcs, E_WRITE_PARCEL_ERROR); + USB_HILOGD(MODULE_USBD, "SetCurrentFunctions funcs %{public}d", funcs); + ErrCode ret = DoDispatch(CMD_FUN_SET_CURRENT_FUNCTIONS, data, reply); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_FUN_SET_CURRENT_FUNCTIONS failed"); + return ret; + } + return ERR_OK; +} + +int32_t UsbdClient::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + USB_HILOGD(MODULE_USBD, "UsbdClient::SetPortRole enter"); + MessageParcel data; + MessageParcel reply; + + WRITE_PARCEL_WITH_RET(data, Int32, portId, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, powerRole, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, dataRole, E_WRITE_PARCEL_ERROR); + + ErrCode ret = DoDispatch(CMD_SET_ROLE, data, reply); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_SET_ROLE failed, return INVALID_STRING_VALUE"); + return ret; + } + return ERR_OK; +} + +int32_t UsbdClient::QueryPort(int32_t &portId, int32_t &powerRole, int32_t &dataRole, int32_t &mode) +{ + USB_HILOGD(MODULE_USBD, "UsbdClient::queryPort enter"); + MessageParcel data; + MessageParcel reply; + ErrCode ret = DoDispatch(CMD_QUERY_PORT, data, reply); + READ_PARCEL_WITH_RET(reply, Int32, portId, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(reply, Int32, powerRole, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(reply, Int32, dataRole, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(reply, Int32, mode, E_READ_PARCEL_ERROR); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_QUERY_PORT failed, return INVALID_STRING_VALUE"); + return ret; + } + USB_HILOGE(MODULE_USBD, "portId:%{public}d powerRole:%{public}d dataRole:%{public}d mode:%{public}d ", portId, + powerRole, dataRole, mode); + return ERR_OK; +} + +ErrCode UsbdClient::DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply) +{ + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d cmd:%{public}d", __func__, __LINE__, cmd); + auto Usbd = GetUsbdService(); + if (Usbd == nullptr) { + USB_HILOGE(MODULE_USBD, "fumang get usbd service failed."); + return ERR_NO_INIT; + } + MessageOption option; + auto ret = Usbd->SendRequest(cmd, data, reply, option); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d SendRequest end cmd:%{public}d ", __func__, __LINE__, cmd); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USBD, "failed to send request, cmd: %{public}d, ret: %{public}d", cmd, ret); + return ret; + } + USB_HILOGD(MODULE_USBD, "fumang success to dispatch cmd: %{public}d", cmd); + return ERR_OK; +} + +int32_t UsbdClient::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) +{ + int32_t ret = ERR_OK; + if (desc == NULL || length == 0) { + return ERR_INVALID_VALUE; + } + MessageParcel data; + MessageParcel reply; + if ((!desc) || (length < 1)) { + return ERR_INVALID_VALUE; + } + UsbdClient::SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_CONFIG_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + uint32_t descLength = 0; + reply.ReadUint32(descLength); + if (descLength > length) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ERR_OVERFLOW; + } + const uint8_t *readData = reply.ReadBuffer(descLength); + memcpy_s(desc, length, readData, descLength); + return ret; +} + +int32_t UsbdClient::GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + if ((!buffer) || (length < 1)) { + return ERR_INVALID_VALUE; + } + UsbdClient::SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_DEVICE_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + GetBufferMessage(reply, buffer, length); + struct UsbdDeviceDescriptor *devDesc = (struct UsbdDeviceDescriptor *)buffer; + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang bLength=%{public}d, \ + bDescriptorType=%{public}d, \ + bcdUSB=%{public}d, \ + bDeviceClass=%{public}d, \ + bDeviceSubClass=%{public}d, \ + bDeviceProtocol=%{public}d, \ + bMaxPacketSize0=%{public}d, \ + idVendor=%{public}d, \ + idProduct=%{public}d, \ + bcdDevice=%{public}d, \ + iManufacturer=%{public}d, \ + iProduct=%{public}d, \ + iSerialNumber=%{public}d, \ + bNumConfigurations=%{public}d len:%{public}d", + __func__, devDesc->bLength, devDesc->bDescriptorType, devDesc->bcdUSB, devDesc->bDeviceClass, + devDesc->bDeviceSubClass, devDesc->bDeviceProtocol, devDesc->bMaxPacketSize0, devDesc->idVendor, + devDesc->idProduct, devDesc->bcdDevice, devDesc->iManufacturer, devDesc->iProduct, + devDesc->iSerialNumber, devDesc->bNumConfigurations, length); + + return ret; +} + +int32_t UsbdClient::GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d cfgId:%{public}d length:%{public}d ", __func__, __LINE__, + params.DescId, params.length); + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.DescId, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_STRING_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + GetBufferMessage(reply, params.buffer, params.length); + PrintBuffer("UsbdClient::GetStringDescriptor", params.buffer, params.length); + return ret; +} + +int32_t UsbdClient::GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d cfgId:%{public}d length:%{public}d ", __func__, __LINE__, + params.DescId, params.length); + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.DescId, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_CONFIG_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + GetBufferMessage(reply, params.buffer, params.length); + PrintBuffer("UsbdClient::GetConfigDescriptor", params.buffer, params.length); + return ret; +} + +int32_t UsbdClient::SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, configIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SET_CONFIG, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_CONFIG, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + READ_PARCEL_WITH_RET(data, Uint8, configIndex, E_READ_PARCEL_ERROR); + return ret; +} + +int32_t UsbdClient::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_CLAIM_INTERFACE, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_RELEASE_INTERFACE, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceIndex, uint8_t altIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceIndex, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, altIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SET_INTERFACE, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + return ERR_OK; +} + +int32_t UsbdClient::BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_BULK_READ_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + return GetBufferMessage(reply, params.buffer, params.length); +} + +int32_t UsbdClient::BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.buffer, params.length); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_BULK_WRITE_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, params.requestType, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.request, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.value, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.index, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + bool bWrite = (params.requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT; + if (bWrite) { + SetBufferMessage(data, params.buffer, params.length); + } + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_CTRL_REQUEST_SYNC, data, reply); + if (ret != ERR_OK) { + return ret; + } + if (!bWrite) { + GetBufferMessage(reply, params.buffer, params.length); + PrintBuffer("UsbdClient::ControlTransfer", (const uint8_t *)params.buffer, params.length); + } + return ret; +} + +int32_t UsbdClient::InterruptTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_INTERRUPT_READ_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + return GetBufferMessage(reply, params.buffer, params.length); +} + +int32_t UsbdClient::InterruptTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.buffer, params.length); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_INTERRUPT_WRITE_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::IsoTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_ISO_READ_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + return GetBufferMessage(reply, params.buffer, params.length); +} + +int32_t UsbdClient::IsoTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.buffer, params.length); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_ISO_WRITE_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::CloseDevice(uint8_t busNum, uint8_t devAddr) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_CLOSE_DEVICE, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpoint, + struct RequestParams ¶ms) +{ + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, ifId, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.clientData, params.clientLength); + SetBufferMessage(data, params.buffer, params.length); + return UsbdClient::DoDispatch(CMD_FUN_REQUEST_QUEUE, data, reply); +} + +int32_t UsbdClient::RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms) +{ + int32_t ret; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_REQUEST_WAIT, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d failed ret:%{public}d", __func__, __LINE__, ret); + return ret; + } + GetBufferMessage(reply, params.clientData, params.clientLength); + GetBufferMessage(reply, params.buffer, params.length); + return ERR_OK; +} + +int32_t UsbdClient::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) +{ + int32_t ret; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpointid, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_REQUEST_CANCEL, data, reply); + if (ret != ERR_OK) { + return ret; + } + + return ERR_OK; +} + +int32_t UsbdClient::SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length) +{ + if (!data.WriteUint32(length)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && !data.WriteBuffer(buffer, length)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbdClient::GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length) +{ + uint32_t dataSize; + if (!data.ReadUint32(dataSize)) { + return ERR_INVALID_VALUE; + } + if (dataSize == 0) { + length = 0; + return ERR_OK; + } + if (!buffer) { + length = 0; + return ERR_INVALID_VALUE; + } + if (length < dataSize) { + USB_HILOGW(MODULE_USBD, "%{public}s failed buffer overflow", __func__); + return ERR_NO_MEMORY; + } + const uint8_t *readData = data.ReadBuffer(dataSize); // +1 避免0大小的空buffer + if (readData == nullptr) { + return ERR_INVALID_VALUE; + } + memcpy_s(buffer, length, readData, dataSize); + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d, dataSize = %{public}d", __func__, + length, dataSize); + length = dataSize; + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d", __func__, length); + return ERR_OK; +} + +int32_t UsbdClient::SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr) +{ + WRITE_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} +} // namespace USB +} // namespace OHOS diff --git a/hdi/client/src/usbd_subscriber.cpp b/hdi/client/src/usbd_subscriber.cpp new file mode 100644 index 00000000..8cd448c8 --- /dev/null +++ b/hdi/client/src/usbd_subscriber.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_subscriber.h" +#include "usb_common.h" + +namespace OHOS { +namespace USB { +FoundDevice &UsbdSubscriber::ParserFoundDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + static FoundDevice t; + return t; +} +int UsbdSubscriber::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t ret = ERR_OK; + UsbInfo info; + PortInfo pinfo; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT entry code:%{public}d", __func__, + __LINE__, code); + switch (code) { + case CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT: + USB_HILOGW(MODULE_USBD, "%{public}s CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT entry", __func__); + ParserUsbInfo(data, reply, option, info); + USB_HILOGD(MODULE_USBD, + "%{public}s CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT Read devInfo " + "status=%{public}d,busNum=%{public}d,devAddr=%{public}d", + __func__, info.getDevInfoStatus(), info.getDevInfoBusNum(), info.getDevInfoDevNum()); + ret = DeviceEvent(info); + break; + case CMD_NOTIFY_PORT_CHANGED: + USB_HILOGW(MODULE_USBD, "%{public}s CMD_NOTIFY_PORT_CHANGED entry", __func__); + ParserPortInfo(data, reply, option, pinfo); + ret = PortChangedEvent(pinfo.portId, pinfo.powerRole, pinfo.dataRole, pinfo.mode); + break; + default: + USB_HILOGW(MODULE_USBD, "no specific cmd for code: %{public}d", code); + ret = ERR_INVALID_OPERATION; + break; + } + return ret; +} + +int32_t UsbdSubscriber::ParserUsbInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, UsbInfo &info) +{ + int32_t status; + int32_t busNum; + int32_t devNum; + + if (!data.ReadInt32(status)) { + USB_HILOGW(MODULE_USBD, "Read devInfo status error"); + } + if (!data.ReadInt32(busNum)) { + USB_HILOGW(MODULE_USBD, "Read devInfo busNum error"); + } + if (!data.ReadInt32(devNum)) { + USB_HILOGW(MODULE_USBD, "Read devInfo devNum error"); + } + info.setDevInfoStatus(status); + info.setDevInfoBusNum(busNum); + info.setDevInfoDevNum(devNum); + + USB_HILOGD(MODULE_USBD, "%{public}s Read devInfo status=%{public}d,busNum=%{public}d,devAddr=%{public}d", __func__, + status, busNum, devNum); + return 1; +} + +int32_t UsbdSubscriber::ParserPortInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, PortInfo &info) +{ + int32_t portId; + int32_t powerRole; + int32_t dataRole; + int32_t mode; + + if (!data.ReadInt32(portId)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo id error"); + return 0; + } + if (!data.ReadInt32(powerRole)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo powerRole error"); + return 0; + } + if (!data.ReadInt32(dataRole)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo dataRole error"); + return 0; + } + if (!data.ReadInt32(mode)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo mode error"); + return 0; + } + info.portId = portId; + info.powerRole = powerRole; + info.dataRole = dataRole; + info.mode = mode; + return 1; +} +} // namespace USB +} // namespace OHOS diff --git a/hdi/service/BUILD.gn b/hdi/service/BUILD.gn new file mode 100644 index 00000000..80ed6424 --- /dev/null +++ b/hdi/service/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") + +config("usbd_private_config") { + include_dirs = [ + ] +} + +config("usbd_public_config") { + include_dirs = [ + "include", + "${usb_manager_path}/hdi/api/include", + "//drivers/adapter/uhdf2/include/hdi", + "//drivers/framework/include/utils", + "//drivers/adapter/uhdf2/shared/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//drivers/framework/include/core", + "//drivers/peripheral/usb/ddk/common/include", + "//drivers/peripheral/usb/ddk/host/include", + "//drivers/peripheral/usb/interfaces/ddk/common", + "//drivers/peripheral/usb/interfaces/ddk/host", + "//drivers/peripheral/usb/interfaces/ddk/device", + "//drivers/peripheral/usb/gadget/function/include", + "//drivers/framework/core/shared/include", + "//drivers/framework/core/adapter/syscall/include", + "//drivers/framework/model/usb/include", + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/log", + ] +} + +ohos_shared_library("usbd") { + sources = [ + "src/usbd.c", + "src/usbd_dispatcher.c", + "src/usbd_publisher.c", + "src/usbd_function.c", + "src/usbd_port.c" + ] + + configs = [ + "${utils_path}:utils_config", + ":usbd_private_config", + ] + + public_configs = [ ":usbd_public_config" ] + + deps = [ + "${hdf_uhdf_path}/host:libhdf_host", + "${hdf_uhdf_path}/ipc:libhdf_ipc_adapter", + "${hdf_uhdf_path}/osal:libhdf_utils", + "//utils/native/base:utils", + "${hdf_uhdf_path}/hdi:libhdi", + "//drivers/peripheral/usb:libusb_ddk", + "//drivers/adapter/uhdf2/config:uhdf_hcs_pkg", + "//drivers/adapter/uhdf2/host:libhdf_host", + "//drivers/peripheral/usb/ddk:libusb_core", + "//base/startup/init_lite/services/param:param_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + part_name = "usb_manager_native" + + subsystem_name = "hdf" +} diff --git a/hdi/service/include/usbd.h b/hdi/service/include/usbd.h new file mode 100644 index 00000000..bb2e7af3 --- /dev/null +++ b/hdi/service/include/usbd.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_H +#define USBD_H + +#include "data_fifo.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_atomic.h" +#include "osal_sem.h" +#include "usb_ddk.h" +#include "usb_interface.h" +#include "usb_session.h" +#include "usbd_api.h" +#include "usbd_publisher.h" + +#define USB_MAX_INTERFACES 32 +#define DIRECTION_MASK 0x1 +#define USB_CTRL_SET_TIMEOUT 5000 +#define USB_PIPE_DIR_OFFSET 7 + +struct UsbdService; +struct HostDevice { + struct HdfSListNode node; + struct UsbdService *service; + struct DataFifo readFifo; + struct HdfSList requestQueue; + struct OsalMutex requestLock; + uint8_t interfaceIndex[USB_MAX_INTERFACES]; + uint8_t interfaceCnt; + struct UsbInterface *iface[USB_MAX_INTERFACES]; + UsbInterfaceHandle *ctrDevHandle; + UsbInterfaceHandle *devHandle[USB_MAX_INTERFACES]; + struct OsalMutex writeLock; + struct OsalMutex readLock; + struct OsalMutex lock; + struct UsbRequest *ctrlReq; + struct UsbInterface *ctrIface; + struct UsbPipeInfo *ctrPipe; + uint8_t busNum; + uint8_t devAddr; + bool initFlag; +}; + +struct RequestMsg { + struct HdfSListNode node; + struct UsbRequest *request; + void *clientData; + uint32_t clientLength; +}; + +struct UsbControlParams { + uint8_t request; + UsbRequestTargetType target; + UsbControlRequestType reqType; + UsbRequestDirection directon; + uint16_t value; + uint16_t index; + void *data; + uint16_t size; +}; + +struct UsbDescriptorParams { + UsbInterfaceHandle *devHandle; + struct UsbRequest *request; + uint8_t type; + uint8_t index; + void *buf; + uint16_t size; +}; + +struct UsbdService { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct UsbdSubscriber *subscriber; + struct UsbSession *session; + // struct HostDevice *port; + struct HdfSList devList; + struct OsalMutex lock; +}; + +struct UsbdSubscriber; +int32_t BindUsbSubscriber(struct UsbdService *service, struct UsbdSubscriber *subscriber); +int32_t UnbindUsbSubscriber(struct UsbdService *service); + +#endif // USBD_H diff --git a/hdi/service/include/usbd_dispatcher.h b/hdi/service/include/usbd_dispatcher.h new file mode 100644 index 00000000..bb5e7afa --- /dev/null +++ b/hdi/service/include/usbd_dispatcher.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_DISPATCHER_H +#define USBD_DISPATCHER_H + +#include "core/hdf_device_desc.h" + +int32_t UsbdServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply); +#endif // USBD_DISPATCHER_H diff --git a/hdi/service/include/usbd_function.h b/hdi/service/include/usbd_function.h new file mode 100644 index 00000000..e571df50 --- /dev/null +++ b/hdi/service/include/usbd_function.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBD_FUNCTION_H +#define USBD_FUNCTION_H +#include "usbd.h" + +int32_t UsbdSetFunction(int funcs); +int32_t UsbdGetFunction(); + +#endif diff --git a/hdi/service/include/usbd_parser.h b/hdi/service/include/usbd_parser.h new file mode 100644 index 00000000..06e29c92 --- /dev/null +++ b/hdi/service/include/usbd_parser.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 USBD_PARSER_H +#define USBD_PARSER_H + +#include "usbd_api.h" + +int32_t InitUsbdSysfs(void); +int32_t ParseCapacity(int32_t *capacity); +int32_t ParseVoltage(int32_t *voltage); +int32_t ParseTemperature(int32_t *temperature); +int32_t ParseHealthState(int32_t *healthState); +int32_t ParsePluggedType(int32_t *pluggedType); +int32_t ParseChargeState(int32_t *chargeState); +int32_t ParsePresent(int8_t *present); +int32_t ParseTechnology(char *technology, size_t size); +void ParseUeventToUsbdInfo(const char *msg, struct UsbdInfo *info); +int32_t SwitchRole(int32_t portId, int32_t powerRole, int32_t dataRole); +int changeRole(const char *portName, enum PortRoleType type, int32_t role); +int32_t readFile(const char *filename, char contents); +char *appendRoleNodeHelper(const char *portName, enum PortRoleType type); +char *convertRoletoString(enum PortRoleType type, int32_t role); + +#endif // USBD_PARSER_H diff --git a/hdi/service/include/usbd_port.h b/hdi/service/include/usbd_port.h new file mode 100644 index 00000000..f26da3ae --- /dev/null +++ b/hdi/service/include/usbd_port.h @@ -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. + */ + +#ifndef USBD_PORT_H +#define USBD_PORT_H + +#include "usbd.h" + +int SetPort(int portId, int powerRole, int dataRole, struct UsbdService *service); +int QueryPort(int *portId, int *powerRole, int *dataRole, int *mode, struct UsbdService *service); + +#endif diff --git a/hdi/service/include/usbd_publisher.h b/hdi/service/include/usbd_publisher.h new file mode 100644 index 00000000..b35cada8 --- /dev/null +++ b/hdi/service/include/usbd_publisher.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 USBD_PUBLISHER_H +#define USBD_PUBLISHER_H + +#include "usbd.h" +#include "usbd_api.h" + +struct UsbdSubscriber { + struct HdfRemoteService *remoteService; +}; + +void NotifyUsbPortSubscriber(const struct UsbdSubscriber *subscriber, + int32_t portId, + int32_t powerRole, + int32_t dataRole, + int32_t mode); +void NotifySubscriberDevice(const struct UsbdSubscriber *subscriber, + enum UsbdDeviceAction act, + int32_t busNum, + int32_t devNum); + +#endif // USBD_PUBLISHER_H diff --git a/hdi/service/src/usbd.c b/hdi/service/src/usbd.c new file mode 100644 index 00000000..c5dfe1c6 --- /dev/null +++ b/hdi/service/src/usbd.c @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd.h" +#include +#include "devmgr_service_if.h" +#include "hdf_base.h" +#include "hdf_io_service_if.h" +#include "hdf_log.h" +#include "hdf_syscall_adapter.h" +#include "hdf_usb_pnp_manage.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "securec.h" +#include "usb_ddk_pnp_loader.h" +#include "usbd_dispatcher.h" +#include "usbd_function.h" +#include "usbd_parser.h" +#include "usbd_publisher.h" + +int32_t HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener); + +static int32_t UsbdDriverBind(struct HdfDeviceObject *device); +static int32_t UsbdDriverInit(struct HdfDeviceObject *device); +static void UsbdDriverRelease(struct HdfDeviceObject *device); +int32_t UsbdRealseDevices(struct UsbdService *service); +int32_t HostDeviceCreate(struct HostDevice **port); + +static int UsbdEventHandle(struct UsbdService *inst); + +/* HdfDriverEntry implementations */ +static int32_t UsbdDriverBind(struct HdfDeviceObject *device) +{ + struct UsbdService *dev = NULL; + struct UsbPnpNotifyServiceInfo *info = NULL; + int32_t ret; + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + if (device == NULL) { + HDF_LOGE("%{public}s:%{public}d device is null", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + dev = (struct UsbdService *)OsalMemCalloc(sizeof(struct UsbdService)); + if (dev == NULL) { + HDF_LOGE("%{public}s: Alloc dev device failed", __func__); + return HDF_FAILURE; + } + memset(dev, 0, sizeof(struct UsbdService)); + if (OsalMutexInit(&dev->lock) != HDF_SUCCESS) { + HDF_LOGE(" init lock fail!"); + return HDF_FAILURE; + } + info = (struct UsbPnpNotifyServiceInfo *)device->priv; + if (info) { + struct HostDevice *port = NULL; + ret = HostDeviceCreate(&port); + if (ret == HDF_SUCCESS) { + port->busNum = info->busNum; + port->devAddr = info->busNum; + port->service = dev; + OsalMutexLock(&dev->lock); + HdfSListAdd(&dev->devList, &port->node); + OsalMutexUnlock(&dev->lock); + } + } + HDF_LOGE("%{public}s: fumang exit", __func__); + device->service = &(dev->service); + device->service->Dispatch = UsbdServiceDispatch; + dev->device = device; + UsbdEventHandle(dev); + return HDF_SUCCESS; +} + +static int32_t UsbdDriverInit(struct HdfDeviceObject *device) +{ + int32_t ret = HDF_SUCCESS; + HDF_LOGE("%{public}s:%{public}d fumang exit", __func__, __LINE__); + if (device == NULL) { + HDF_LOGE("%{public}s:%{public}d device is null", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + + HDF_LOGD("%{public}s:%{public}d init ok!", __func__, __LINE__); + return ret; +} + +static void UsbdDriverRelease(struct HdfDeviceObject *device) +{ + struct UsbdService *dev = NULL; + HDF_LOGE("%{public}s:%{public}d fumang exit", __func__, __LINE__); + if (device == NULL) { + HDF_LOGE("%{public}s: device is NULL", __func__); + return; + } + dev = (struct UsbdService *)device->service; + UsbdRealseDevices(dev); + HDF_LOGD("%{public}s:%{public}d exit", __func__, __LINE__); +} + +struct HdfDriverEntry g_usbdDriverEntry = { + .moduleVersion = 1, + .moduleName = "usbd", + .Bind = UsbdDriverBind, + .Init = UsbdDriverInit, + .Release = UsbdDriverRelease, +}; +HDF_INIT(g_usbdDriverEntry); + +static int UsbdAddDevicesOnStart(struct UsbdService *service); + +int32_t BindUsbSubscriber(struct UsbdService *service, struct UsbdSubscriber *subscriber) +{ + HDF_LOGE("%{public}s: fumang entry", __func__); + HDF_LOGE("%{public}s:%{public}d fumang entry service:%{public}p subscriber:%{public}p", __func__, __LINE__, service, + subscriber); + if (service == NULL) { + HDF_LOGW("%{public}s fumang service is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + service->subscriber = subscriber; + UsbdAddDevicesOnStart(service); + return HDF_SUCCESS; +} + +int32_t UnbindUsbSubscriber(struct UsbdService *service) +{ + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + if (service == NULL) { + HDF_LOGW("%{public}s service is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (service->subscriber != NULL) { + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + OsalMemFree(service->subscriber); + service->subscriber = NULL; + } + return HDF_SUCCESS; +} + +static int UsbdPnpLoaderEventReceived(void *priv, uint32_t id, struct HdfSBuf *data) +{ + int ret = HDF_SUCCESS; + bool flag = false; + uint32_t infoSize; + struct UsbPnpNotifyMatchInfoTable *infoTable = NULL; + struct UsbdService *super = (struct UsbdService *)priv; + + HDF_LOGI("%{public}s:%{public}d id:%{public}d service:%{public}s subscriber:%{public}s ", __func__, __LINE__, id, + super ? "OK" : "NULL", super ? (super->subscriber ? "OK" : "NULL") : "NULL"); + if (!super) { + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGI("%{public}s:%{public}d id:%{public}d service:%{public}p subscriber:%{public}p ", __func__, __LINE__, id, + super, super->subscriber); + if (USB_PNP_DRIVER_GADGET_ADD == id) { + NotifySubscriberDevice(super->subscriber, ACT_UPDEVICE, 0, 0); + return HDF_SUCCESS; + } else if (USB_PNP_DRIVER_GADGET_REMOVE == id) { + NotifySubscriberDevice(super->subscriber, ACT_DOWNDEVICE, 0, 0); + return HDF_SUCCESS; + } + flag = HdfSbufReadBuffer(data, (const void **)(&infoTable), &infoSize); + if ((flag == false) || (infoTable == NULL)) { + ret = HDF_ERR_INVALID_PARAM; + HDF_LOGE("%{public}s: fail to read infoTable in event data, flag=%{public}d, infoTable=%{public}p", __func__, + flag, infoTable); + return ret; + } + + HDF_LOGI( + "%{public}s:%{public}d id=%{public}d infoSize=%{public}d, usbDevAddr=0x%{public}x, devNum=%{public}d, \ + busNum=%{public}d, class:%{public}d infoTable=0x%{public}x-0x%{public}x success", + __func__, __LINE__, id, infoSize, infoTable->usbDevAddr, infoTable->devNum, infoTable->busNum, + infoTable->deviceInfo.deviceClass, infoTable->deviceInfo.vendorId, infoTable->deviceInfo.productId); + + if (0x09 == infoTable->deviceInfo.deviceClass) { + HDF_LOGI("%{public}s:%{public}d hub device ret:%{public}d", __func__, __LINE__, ret); + return ret; + } + switch (id) { + case USB_PNP_NOTIFY_ADD_DEVICE: + ret = HDF_SUCCESS; + if (0x09 != infoTable->deviceInfo.deviceClass) + NotifySubscriberDevice(super->subscriber, ACT_DEVUP, infoTable->busNum, infoTable->devNum); + break; + case USB_PNP_NOTIFY_REMOVE_DEVICE: + ret = HDF_SUCCESS; + if (0x09 != infoTable->deviceInfo.deviceClass) + NotifySubscriberDevice(super->subscriber, ACT_DEVDOWN, infoTable->busNum, infoTable->devNum); + break; + default: + ret = HDF_SUCCESS; + break; + } + + HDF_LOGI("%{public}s:%{public}d ret=%{public}d DONE", __func__, __LINE__, ret); + + return ret; +} + +static int UsbdEventHandle(struct UsbdService *inst) +{ + int status; + struct HdfIoService *usbPnpServ = HdfIoServiceBind(USB_PNP_NOTIFY_SERVICE_NAME); + static struct HdfDevEventlistener usbPnpListener = { + .callBack = UsbdPnpLoaderEventReceived, + }; + usbPnpListener.priv = (void *)(inst); + + if (usbPnpServ == NULL) { + HDF_LOGE("%{public}s: HdfIoServiceBind faile.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + status = HdfDeviceRegisterEventListener(usbPnpServ, &usbPnpListener); + if (status != HDF_SUCCESS) { + HDF_LOGE("HdfDeviceRegisterEventListener faile status=%{public}d", status); + return status; + } + + return HDF_SUCCESS; +} + +static int UsbdAddDevicesOnStart(struct UsbdService *service) +{ + int32_t ret = HDF_SUCCESS; + struct HdfIoService *usbPnpServ = HdfIoServiceBind(USB_PNP_NOTIFY_SERVICE_NAME); + struct HdfSBuf *data; + struct HdfSBuf *reply; + int32_t count = 0, size = 0; + + if (service == NULL) { + HDF_LOGE("%{public}s:%{public}d service is NULL.", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + + if (usbPnpServ == NULL) { + HDF_LOGE("%{public}s: HdfIoServiceBind faile serv:%{public}s.", __func__, USB_PNP_NOTIFY_SERVICE_NAME); + return HDF_ERR_INVALID_OBJECT; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + ret = HDF_DEV_ERR_NO_MEMORY; + HDF_LOGE("%{public}s: fail to obtain sbuf data", __func__); + return ret; + } + reply = HdfSBufObtainDefaultSize(); + if (reply == NULL) { + ret = HDF_DEV_ERR_NO_MEMORY; + HDF_LOGE("%{public}s: fail to obtain sbuf reply", __func__); + goto out; + } + + ret = usbPnpServ->dispatcher->Dispatch(&usbPnpServ->object, USB_PNP_DRIVER_GETDEVICES, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: fail to send serivice call, ret=%{public}d", __func__, ret); + goto out; + } + + while (1) { + int32_t busNum; + int32_t devNum; + uint8_t devClass; + uint8_t subClass; + uint8_t protocol; + uint8_t status; + if (!HdfSbufReadInt32(reply, &busNum)) { + HDF_LOGE("%{public}s: fail to get service call reply", __func__); + break; + } + if (!HdfSbufReadInt32(reply, &devNum)) { + HDF_LOGE("%{public}s: fail to get service call reply", __func__); + break; + } + if (!HdfSbufReadUint8(reply, &devClass)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + if (!HdfSbufReadUint8(reply, &subClass)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + if (!HdfSbufReadUint8(reply, &protocol)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + if (!HdfSbufReadUint8(reply, &status)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + HDF_LOGI( + "%{public}s:%{public}d OnStart get device[%{public}d]:%{public}d:%{public}d status:%{pubic}d " + "class:%{public}d subClass:%{public}d protocol:%{pubic}d", + __func__, __LINE__, count, busNum, devNum, status, devClass, subClass, protocol); + if (devClass != 0x09) { + NotifySubscriberDevice(service->subscriber, ACT_DEVUP, busNum, devNum); + ++size; + } + ++count; + } + + HDF_LOGI("%{public}s:%{public}d onStart add devices:%{public}d size:%{public}d success", __func__, __LINE__, count, + size); + +out: + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + HdfIoServiceRecycle(usbPnpServ); + return ret; +} diff --git a/hdi/service/src/usbd_dispatcher.c b/hdi/service/src/usbd_dispatcher.c new file mode 100644 index 00000000..bccd59f8 --- /dev/null +++ b/hdi/service/src/usbd_dispatcher.c @@ -0,0 +1,2087 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_dispatcher.h" +#include +#include +#include "hdf_base.h" +#include "hdf_log.h" +#include "hdf_usb_pnp_manage.h" +#include "osal_mem.h" +#include "osal_sem.h" +#include "osal_time.h" +#include "securec.h" +#include "usb_interface_pool.h" +#include "usbd.h" +#include "usbd_function.h" +#include "usbd_parser.h" +#include "usbd_port.h" +#include "usbd_publisher.h" + +#define HDF_LOG_TAG usbd_dispatcher + +#define MAX_BUFF_SIZE 16384 +#define MAX_CONTROL_BUFF_SIZE 1024 +#define READ_BUF_SIZE 8192 + +#define USB_CTRL_SET_TIMEOUT 5000 +#define USB_PIPE_DIR_OFFSET 7 +#define CHARFORMAT 8 +#define USB_REUQEST_SLEEP_TIME 100 +#define USB_MAX_DESCRIPTOR_SIZE 256 + +#define OPEN_SLEPP_TIME 1000 +#define SUBMIT_SLEEP_TIME 500 + +static int32_t DispatchBindUsbSubscriber(struct UsbdService *service, struct HdfSBuf *data); +static int32_t DispatchUnbindUsbSubscriber(struct UsbdService *service); +static int32_t GetPipe(const struct HostDevice *dev, uint8_t interfaceId, uint8_t pipeId, struct UsbPipeInfo *pipe); +static int32_t UsbControlTransfer(struct HostDevice *dev, + int32_t requestCmd, + int32_t cmdType, + int32_t target, + int32_t direction, + int32_t value, + int32_t index, + int32_t timeout, + uint8_t *buffer, + uint32_t *length); + +int32_t HostDeviceCreate(struct HostDevice **port); +int32_t UsbdRealseDevices(struct UsbdService *service); +static struct HostDevice *FindDevFromService(struct UsbdService *service, uint8_t busNum, uint8_t devAddr); +static int32_t RemoveDevFromService(struct UsbdService *service, struct HostDevice *port); + +static int32_t UsbdInit(struct HostDevice *dev); +static void UsbdRelease(struct HostDevice *dev); + +void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + if (title == NULL || buffer == NULL || length == 0) { + return; + } + uint32_t logLength = strlen(title) + length * 3 + 50; + char *logBuffer = (char *)OsalMemAlloc(logLength); + if (logBuffer == NULL) { + return; + } + memset(logBuffer, 0, logLength); + sprintf_s(logBuffer, logLength, " %s << 二进制数据流,%u字节 >> :", title, length); + uint32_t pos = strlen(logBuffer); + for (uint32_t i = 0; i < length; ++i) { + sprintf_s(logBuffer + pos, logLength - pos, " %02x", buffer[i]); + pos += 3; + } + sprintf_s(logBuffer + pos, logLength - pos, " --> %s \n", buffer); + HDF_LOGE("%{public}s", logBuffer); + OsalMemFree(logBuffer); +} + +static int32_t ParseDeviceBuf(struct HdfSBuf *data, uint8_t *busNum, uint8_t *devAddr) +{ + if (data == NULL || busNum == NULL || devAddr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + HdfSbufReadUint8(data, busNum); + HdfSbufReadUint8(data, devAddr); + return HDF_SUCCESS; +} + +static int32_t UsbdAllocFifo(struct DataFifo *fifo, uint32_t size) +{ + if (!DataFifoIsInitialized(fifo)) { + void *data = OsalMemAlloc(size); + if (data == NULL) { + HDF_LOGE("%{public}s:%{public}d allocate failed", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + DataFifoInit(fifo, size, data); + } + return HDF_SUCCESS; +} + +static void UsbdFreeFifo(struct DataFifo *fifo) +{ + if (fifo == NULL) { + HDF_LOGE("%{public}s:%{public}d fifo is NULL", __func__, __LINE__); + return; + } + + if (fifo->data != NULL) { + OsalMemFree(fifo->data); + fifo->data = NULL; + } + + DataFifoInit(fifo, 0, NULL); +} + +static struct RequestMsg *UsbdAllocRequestMsg(UsbInterfaceHandle *interfaceHandle, int32_t isoPackets, int32_t length) +{ + struct RequestMsg *reqMsg = NULL; + reqMsg = (struct RequestMsg *)OsalMemAlloc(sizeof(struct RequestMsg)); + if (reqMsg == NULL) { + HDF_LOGE("HDF_ERR_MALLOC_FAIL faild\n"); + return NULL; + } + memset(reqMsg, 0, sizeof(*reqMsg)); + reqMsg->request = UsbAllocRequest(interfaceHandle, 0, length); + if (reqMsg->request == NULL) { + HDF_LOGE("HDF_ERR_MALLOC_FAIL faild\n"); + OsalMemFree(reqMsg); + return NULL; + } + reqMsg->clientData = NULL; + reqMsg->clientLength = 0; + return reqMsg; +} + +static int32_t UsbdFreeRequestMsg(struct RequestMsg *reqMsg) +{ + if (reqMsg == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (reqMsg->request != NULL) { + UsbFreeRequest(reqMsg->request); + } + if (reqMsg->clientData) { + OsalMemFree(reqMsg->clientData); + } + reqMsg->clientData = NULL; + reqMsg->clientLength = 0; + OsalMemFree(reqMsg); + reqMsg = NULL; + + return HDF_SUCCESS; +} + +static void UsbdReadCallback(struct UsbRequest *req) +{ + uint8_t *data = NULL; + uint32_t dataSize = 0, readSize = 0; + struct UsbIfRequest *reqObj = (struct UsbIfRequest *)req; + HDF_LOGE("%{public}s:%{pulib}d entry", __func__, __LINE__); + if (req == NULL) { + HDF_LOGE("%{public}s:%{pulib}d req is NULL!", __func__, __LINE__); + return; + } + int status = req->compInfo.status; + dataSize = req->compInfo.actualLength; + struct HostDevice *dev = (struct HostDevice *)req->compInfo.userData; + if (dev == NULL) { + HDF_LOGE("%{public}s:%{pulib}d dev is NULL!", __func__, __LINE__); + goto exit; + } + + switch (status) { + case 0: + HDF_LOGD("Bulk status: %{public}d+size:%{public}u\n", status, dataSize); + if (dataSize > 0) { + data = req->compInfo.buffer; + OsalMutexLock(&dev->readLock); + if (DataFifoIsFull(&dev->readFifo)) { + HDF_LOGD("%{public}s:%{public}d", __func__, __LINE__); + DataFifoSkip(&dev->readFifo, dataSize); + } + readSize = DataFifoWrite(&dev->readFifo, data, dataSize); + if (readSize != dataSize) { + HDF_LOGW("%{public}s: write %{public}u less than expected %{public}zu", __func__, dataSize, + readSize); + } + + OsalMutexUnlock(&dev->readLock); + } + break; + default: + HDF_LOGE("%{public}s:%{public}d status=%{public}d", __func__, __LINE__, status); + break; + } + +exit: + OsalSemPost(&reqObj->hostRequest->sem); +} + +static void UsbdWriteCallback(struct UsbRequest *req) +{ + HDF_LOGE("%{public}s:%{pulib}d entry", __func__, __LINE__); + if (req == NULL) { + HDF_LOGE("%{public}s:%{pulib}d req is NULL!", __func__, __LINE__); + return; + } + struct HostDevice *dev = (struct HostDevice *)req->compInfo.userData; + if ((dev == NULL) || (dev == NULL)) { + HDF_LOGE("%{public}s:%{pulib}d dev or dev->port is NULL!", __func__, __LINE__); + return; + } + int status = req->compInfo.status; + HDF_LOGE("%{public}s:%{pulib}d statue is %d!", __func__, __LINE__, status); + switch (status) { + case 0: + break; + case -ECONNRESET: + case -ENOENT: + case -ESHUTDOWN: + break; + default: + break; + } + + return; +} + +static UsbInterfaceHandle *InterfaceIdToHandle(const struct HostDevice *dev, uint8_t id) +{ + UsbInterfaceHandle *devHandle = NULL; + + if (id == 0xFF) { + devHandle = dev->ctrDevHandle; + } else if (id < USB_MAX_INTERFACES) { + return dev->devHandle[id]; + } + return devHandle; +} + +static int32_t UsbControlSetUp(struct UsbControlParams *controlParams, struct UsbControlRequest *controlReq) +{ + if (controlParams == NULL || controlReq == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + controlReq->target = controlParams->target; + controlReq->reqType = controlParams->reqType; + controlReq->directon = controlParams->directon; + controlReq->request = controlParams->request; + controlReq->value = CpuToLe16(controlParams->value); + controlReq->index = CpuToLe16(controlParams->index); + controlReq->buffer = controlParams->data; + controlReq->length = CpuToLe16(controlParams->size); + return HDF_SUCCESS; +} + +static struct UsbInterface *GetUsbInterfaceById(const struct HostDevice *dev, uint8_t interfaceIndex) +{ + struct UsbInterface *tmpIf = NULL; + + if (!dev || (dev->service == NULL)) { + HDF_LOGE("%{public}s:%{public}d idx:%{public}d service is null", __func__, __LINE__, interfaceIndex); + return NULL; + } + HDF_LOGE( + "%{public}s:%{public}d UsbClaimInterface start session:%{public}s bus:%{public}d dev:%{public}d " + "idex:%{public}d", + __func__, __LINE__, dev->service->session ? "OK" : "NULL", dev->busNum, dev->devAddr, interfaceIndex); + tmpIf = (struct UsbInterface *)UsbClaimInterface(dev->service->session, dev->busNum, dev->devAddr, interfaceIndex); + HDF_LOGE( + "%{public}s:%{public}d UsbClaimInterface end session:%{public}s bus:%{public}d dev:%{public}d idex:%{public}d", + __func__, __LINE__, dev->service->session ? "OK" : "NULL", dev->busNum, dev->devAddr, interfaceIndex); + if (tmpIf == NULL) { + HDF_LOGE("%{public}s:%{public}d failed busNum=%{public}d, devAddr=%{public}d, interface=%{public}d", __func__, + __LINE__, dev->busNum, dev->devAddr, interfaceIndex); + } + return tmpIf; +} + +static int32_t GetInterfacePipe(const struct HostDevice *dev, + struct UsbInterface *interface, + uint8_t pipeAddr, + struct UsbPipeInfo *pipe) +{ + int32_t ret = HDF_FAILURE; + struct UsbInterfaceInfo *info = NULL; + UsbInterfaceHandle *interfaceHandle = NULL; + struct UsbPipeInfo pipeTmp; + memset(&pipeTmp, 0, sizeof(pipeTmp)); + if (dev == NULL || interface == NULL || pipe == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid parmas", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + info = &interface->info; + if (info == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid interface", __func__, __LINE__); + return HDF_FAILURE; + } + + interfaceHandle = InterfaceIdToHandle(dev, info->interfaceIndex); + if (interfaceHandle == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid interface handle", __func__, __LINE__); + return HDF_FAILURE; + } + + for (uint8_t i = 1; i <= info->pipeNum; ++i) { + ret = UsbGetPipeInfo(interfaceHandle, info->curAltSetting, i, &pipeTmp); + HDF_LOGE( + "%{public}s:%{public}d UsbGetPipeInfo [%{public}d/%{public}d] ret:%{public}d Addr:0x%{public}02x " + "pipeAddr:0x%{public}02x id:%{public}d type:%{public}d direction:%{public}d ifcId:%{public}d", + __func__, __LINE__, i, info->pipeNum, ret, pipeAddr, pipeTmp.pipeAddress, pipeTmp.pipeId, pipeTmp.pipeType, + pipeTmp.pipeDirection, pipeTmp.interfaceId); + if ((ret == HDF_SUCCESS) && ((pipeTmp.pipeAddress | (uint8_t)pipeTmp.pipeDirection) == pipeAddr)) { + if (pipe) + *pipe = pipeTmp; + return HDF_SUCCESS; + } + } + return HDF_FAILURE; +} + +static int32_t GetPipe(const struct HostDevice *dev, uint8_t interfaceId, uint8_t pipeId, struct UsbPipeInfo *pipe) +{ + int32_t ret = HDF_SUCCESS; + struct UsbInterface *interface = NULL; + + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid parmas", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (interfaceId > USB_MAX_INTERFACES) { + HDF_LOGE("%{public}s:%{public}d invalid parmas", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + interface = dev->iface[interfaceId]; + if (interface == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid interface", __func__, __LINE__); + return HDF_FAILURE; + } + + ret = GetInterfacePipe(dev, interface, pipeId, pipe); + return ret; +} + +static void UsbdFreeCtrlPipe(struct HostDevice *dev) +{ + if (dev == NULL) { + return; + } + if (dev->ctrPipe) { + OsalMemFree(dev->ctrPipe); + dev->ctrPipe = NULL; + } +} + +static int32_t UsbdGetCtrlPipe(struct HostDevice *dev) +{ + int32_t ret; + struct UsbPipeInfo *pipe = NULL; + pipe = (struct UsbPipeInfo *)OsalMemAlloc(sizeof(struct UsbPipeInfo)); + if (pipe == NULL) { + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc failed", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + + memset(pipe, 0, sizeof(struct UsbPipeInfo)); + HDF_LOGE( + "%{public}s: constrol interface info : %{public}d, %{public}d, %{public}d, \ + %{public}d, %{public}d, %{public}d, %{public}d,", + __func__, dev->ctrIface->info.interfaceIndex, dev->ctrIface->info.altSettings, + dev->ctrIface->info.curAltSetting, dev->ctrIface->info.pipeNum, dev->ctrIface->info.interfaceClass, + dev->ctrIface->info.interfaceSubClass, dev->ctrIface->info.interfaceProtocol); + ret = UsbGetPipeInfo(dev->ctrDevHandle, dev->ctrIface->info.curAltSetting, 0, pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d get pipe failed ret = %{public}d", __func__, __LINE__, ret); + OsalMemFree(pipe); + return HDF_FAILURE; + } + dev->ctrPipe = pipe; + + return HDF_SUCCESS; +} + +static int32_t FunBulkReadSync(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + struct UsbPipeInfo pipe; + struct UsbRequest *request = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + + memset(&parmas, 0, sizeof(parmas)); + memset(&pipe, 0, sizeof(pipe)); + + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d read interfaceId error", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s:%{public}d read pipeId error", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d read timeout error", __func__, __LINE__); + return HDF_ERR_IO; + } + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d get pipe info failed interfaceId=%{public}d, pipeId=%{public}d", __func__, + __LINE__, interfaceId, pipeId); + return HDF_FAILURE; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (!interfaceHandle) { + HDF_LOGE("%{public}s:%{public}d InterfaceIdToHandle failed interfaceId=%{public}d, pipeId=%{public}d", __func__, + __LINE__, interfaceId, pipeId); + return HDF_FAILURE; + } + request = UsbAllocRequest(interfaceHandle, 0, pipe.maxPacketSize); + if (!request) { + HDF_LOGE("%{public}s:%{public}d readReq request faild", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + + HDF_LOGD("%{public}s:%{public}d request:%{public}p ", __func__, __LINE__, request); + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.interfaceId = pipe.interfaceId; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_DIR_OFFSET) & 0x1; + parmas.dataReq.length = pipe.maxPacketSize; + ret = UsbFillRequest(request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto out; + } + + ret = UsbSubmitRequestSync(request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestSync faile, ret=%{public}d \n", ret); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto out; + } + + HDF_LOGD("%{public}s:%{public}d fumang buffer:%{public}p-%{public}p-actualLength:%{public}d", __func__, __LINE__, + request->compInfo.buffer, (uint8_t *)request->compInfo.buffer, request->compInfo.actualLength); + struct UsbIfRequest *reqObj = (struct UsbIfRequest *)request; + OsalMutexLock(&reqObj->hostRequest->lock); + if (!HdfSbufWriteBuffer(reply, (const void *)request->compInfo.buffer, request->compInfo.actualLength)) { + HDF_LOGE("%{public}s: sbuf write buffer failed", __func__); + ret = HDF_ERR_IO; + } + OsalMutexUnlock(&reqObj->hostRequest->lock); + +out: + UsbFreeRequest(request); + return ret; +} + +static int32_t FunBulkWriteSync(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + uint32_t length = 0; + UsbInterfaceHandle *interfaceHandle = NULL; + struct UsbPipeInfo pipe; + struct UsbRequest *request = NULL; + struct UsbRequestParams parmas = {}; + + memset(&parmas, 0, sizeof(parmas)); + memset(&pipe, 0, sizeof(pipe)); + + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed interfaceId=%{public}d, pipeId=%{public}d", __func__, interfaceId, + pipeId); + return HDF_FAILURE; + } + + interfaceHandle = InterfaceIdToHandle(port, interfaceId); + if (interfaceHandle == NULL) { + HDF_LOGE("%{public}s: get interface handle faild \n", __func__); + return HDF_ERR_INVALID_PARAM; + } + request = UsbAllocRequest(interfaceHandle, 0, pipe.maxPacketSize); + if (!request) { + HDF_LOGE("%{public}s: alloc request faild\n", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + HDF_LOGD("%{public}s:%{public}d fumang debug buffer:%{public}s, length:%{public}d, maxPacketSize:%{public}d \n", + __func__, __LINE__, buffer, length, pipe.maxPacketSize); + parmas.interfaceId = pipe.interfaceId; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.userData = port; + parmas.dataReq.length = length; + parmas.dataReq.buffer = buffer; + ret = UsbFillRequest(request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto out; + } + HDF_LOGD("%{public}s:%{public}d fumang debug buffer:%{public}s, length:%{public}d, maxPacketSize:%{public}d \n", + __func__, __LINE__, buffer, length, pipe.maxPacketSize); + ret = UsbSubmitRequestSync(request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestSync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMSleep(SUBMIT_SLEEP_TIME); + } + +out: + UsbFreeRequest(request); + return ret; +} + +static int32_t UsbControlTransfer(struct HostDevice *dev, + int32_t requestCmd, + int32_t cmdType, + int32_t target, + int32_t direction, + int32_t value, + int32_t index, + int32_t timeout, + uint8_t *buffer, + uint32_t *length) +{ + int ret = 0; + struct UsbRequest *request = NULL; + struct UsbControlParams controlParams = {}; + struct UsbRequestParams parmas = {}; + + memset(&controlParams, 0, sizeof(controlParams)); + memset(&parmas, 0, sizeof(parmas)); + + if (NULL == dev || NULL == buffer || length == NULL) { + HDF_LOGE("%{public}s:%{public}d null pointer faild", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + request = UsbAllocRequest(dev->ctrDevHandle, 0, MAX_CONTROL_BUFF_SIZE); + if (!request) { + HDF_LOGE("%{public}s:%{public}d UsbAllocRequest alloc request faild\n", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + + controlParams.request = (uint8_t)requestCmd; + controlParams.target = (UsbRequestTargetType)target; + controlParams.reqType = (UsbControlRequestType)cmdType; + controlParams.directon = (UsbRequestDirection)direction; + controlParams.value = value; + controlParams.index = index; + controlParams.data = (void *)buffer; + controlParams.size = *length; + parmas.interfaceId = USB_CTRL_INTERFACE_ID; + parmas.pipeAddress = 0; + parmas.pipeId = 0; + parmas.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; + parmas.timeout = timeout; + UsbControlSetUp(&controlParams, &parmas.ctrlReq); + + ret = UsbFillRequest(request, dev->ctrDevHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d UsbFillRequest faile, ret=%{public}d ", __func__, __LINE__, ret); + goto out; + } + + ret = UsbSubmitRequestSync(request); + HDF_LOGD("%{public}s:%{public}d UsbSubmitRequestSync ret=%{public}d ", __func__, __LINE__, ret); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d UsbSubmitRequestSync faile, ret=%{public}d ", __func__, __LINE__, ret); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto out; + } + + if (USB_REQUEST_DIR_FROM_DEVICE == direction) { + HDF_LOGD("%{public}s: fumang debug length=%{public}d, actualLength=%{public}d rlen:=%{public}d", __func__, + request->compInfo.length, request->compInfo.actualLength, *length); + memcpy_s(buffer, *length, request->compInfo.buffer, request->compInfo.actualLength); + if (*length > request->compInfo.actualLength) + *length = request->compInfo.actualLength; + PrintBuffer("UsbControlTransfer", buffer, *length); + } + +out: + UsbFreeRequest(request); + return ret; +} + +static int32_t FunControlTransfer(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + int32_t requestCmd = 0, requestType = 0, value = 0, index = 0, timeout = 0; + int32_t target = 0, direction = 0, cmdType = 0; + + HDF_LOGE("%{public}s:%{public}d mangf FunControlTransfer entry", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (port->ctrDevHandle == NULL) { + HDF_LOGE("%{public}s:%{public}d interface handle is null \n", __func__, __LINE__); + ret = HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadInt32(data, &requestType)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &requestCmd)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &value)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &index)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + + target = requestType & 0x1F; + direction = (requestType >> 7) & 0x1; + cmdType = (requestType >> 5) & 0x3; + HDF_LOGE("%{public}s:%{public}d direction:%{public}d target:%{public}d cmdType::%{public}d\n", __func__, __LINE__, + direction, target, cmdType); + if (direction == USB_REQUEST_DIR_TO_DEVICE) { + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s:%{public}d mangf hdf sbuf Read failed", __func__, __LINE__); + return HDF_FAILURE; + } + HDF_LOGE("%{public}s:%{public}d HdfSbufReadBuffer length = %{public}d", __func__, __LINE__, length); + } else { + length = MAX_CONTROL_BUFF_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (buffer == NULL) { + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc faild length = %{public}d", __func__, __LINE__, length); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc length = %{public}d", __func__, __LINE__, length); + } + ret = UsbControlTransfer(port, requestCmd, cmdType, target, direction, value, index, timeout, buffer, &length); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d UsbControlTransfer faild ret:%{public}d\n", __func__, __LINE__, ret); + } + HDF_LOGE("%{public}s:%{public}d UsbControlTransfer ok length = %{public}d", __func__, __LINE__, length); + if (direction == USB_REQUEST_DIR_FROM_DEVICE) { + PrintBuffer("FunControlTransfer 738", buffer, length); + if ((HDF_SUCCESS == ret) && (!HdfSbufWriteBuffer(reply, buffer, length))) { + HDF_LOGE("%{public}s:%{public}d sbuf write buffer failed", __func__, __LINE__); + } + if (buffer) + OsalMemFree(buffer); + } + return ret; +} + +static int32_t UsbdReleaseInterface(struct HostDevice *dev, uint8_t interfaceId) +{ + int32_t ret = HDF_FAILURE; + HDF_LOGE("%{public}s:%{public}d interfaceId:%{public}d dev:%{public}s", __func__, __LINE__, interfaceId, + dev ? "OK" : "NULL"); + if (interfaceId >= USB_MAX_INTERFACES) { + HDF_LOGE("%{public}s:%{public}d interfaceId:%{public}d fail", __func__, __LINE__, interfaceId); + return HDF_ERR_INVALID_PARAM; + } + if (!dev) { + HDF_LOGE("%{public}s:%{public}d dev is null", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (dev->devHandle[interfaceId] != NULL) { + ret = UsbCloseInterface(dev->devHandle[interfaceId]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbCloseInterface failed id = %{public}d ret:%{public}d", __func__, interfaceId, ret); + return ret; + } + dev->devHandle[interfaceId] = NULL; + } + + if (dev->iface[interfaceId] != NULL) { + ret = UsbReleaseInterface(dev->iface[interfaceId]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbReleaseInterface failed id = %{public}d ret:%{public}d", __func__, interfaceId, + ret); + return ret; + } + dev->iface[interfaceId] = NULL; + } + + return HDF_SUCCESS; +} + +static void UsbdReleaseInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return; + } + + for (int i = 0; i < USB_MAX_INTERFACES; ++i) { + if (dev->iface[i]) { + UsbReleaseInterface(dev->iface[i]); + dev->iface[i] = NULL; + } + } + if (dev->ctrIface) { + UsbReleaseInterface(dev->ctrIface); + dev->ctrIface = NULL; + } +} + +static int32_t UsbdClaimInterface(struct HostDevice *dev, uint8_t interfaceId) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (interfaceId >= USB_MAX_INTERFACES) { + return HDF_ERR_INVALID_PARAM; + } + + if (dev->iface[interfaceId] == NULL) { + dev->iface[interfaceId] = GetUsbInterfaceById((const struct HostDevice *)dev, interfaceId); + if (dev->iface[interfaceId] == NULL) { + HDF_LOGE( + "%{public}s:%{public}d UsbClaimInterface failed id = %{public}d, busNum=%{public}d, devAddr=%{public}d", + __func__, __LINE__, interfaceId, (int32_t)dev->busNum, (int32_t)dev->devAddr); + return HDF_FAILURE; + } + } + + if (dev->devHandle[interfaceId] == NULL) { + dev->devHandle[interfaceId] = UsbOpenInterface(dev->iface[interfaceId]); + if (dev->devHandle[interfaceId] == NULL) { + HDF_LOGE("%{public}s:%{public}d UsbOpenInterface failed id = %{public}d", __func__, __LINE__, interfaceId); + return HDF_FAILURE; + } + } + + return HDF_SUCCESS; +} + +static int32_t UsbdClaimInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + memset(dev->iface, 0, sizeof(struct UsbInterface *) * USB_MAX_INTERFACES); + + dev->ctrIface = GetUsbInterfaceById((const struct HostDevice *)dev, USB_CTRL_INTERFACE_ID); + if (dev->ctrIface == NULL) { + HDF_LOGE("%{public}s:%{public}d GetUsbInterfaceById null", __func__, __LINE__); + goto error; + } + + return HDF_SUCCESS; + +error: + UsbdReleaseInterfaces(dev); + return HDF_FAILURE; +} + +static void UsbdCloseInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return; + } + + for (int i = 0; i < USB_MAX_INTERFACES; ++i) { + if (dev->devHandle[i]) { + UsbCloseInterface(dev->devHandle[i]); + dev->devHandle[i] = NULL; + } + } + if (dev->ctrDevHandle) { + UsbCloseInterface(dev->ctrDevHandle); + dev->ctrDevHandle = NULL; + } +} + +static int32_t FunClaimInterface(struct HostDevice *port, struct HdfSBuf *data) +{ + if ((port == NULL) || (data == NULL)) { + HDF_LOGE("%{public}s:%{public}d invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + uint8_t interfaceId; + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d sbuf read interfaceNum failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + return UsbdClaimInterface(port, interfaceId); +} + +static int32_t FunReleaseInterface(struct HostDevice *port, struct HdfSBuf *data) +{ + if ((port == NULL) || (data == NULL)) { + HDF_LOGE("%{public}s:%{public}d invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + uint8_t interfaceId; + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d sbuf read interfaceNum failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s:%{public}d interfaceId:%{public}d", __func__, __LINE__, interfaceId); + return UsbdReleaseInterface(port, interfaceId); +} + +static int32_t UsbdOpenInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + memset(dev->devHandle, 0, sizeof(UsbInterfaceHandle *) * USB_MAX_INTERFACES); + + HDF_LOGE("%{public}s:%{public}d UsbOpenInterface start", __func__, __LINE__); + dev->ctrDevHandle = UsbOpenInterface(dev->ctrIface); + HDF_LOGE("%{public}s:%{public}d UsbOpenInterface end", __func__, __LINE__); + if (dev->ctrDevHandle == NULL) { + HDF_LOGE("%{public}s:%{public}d ctrDevHandle UsbOpenInterface null", __func__, __LINE__); + goto error; + } + return HDF_SUCCESS; + +error: + UsbdCloseInterfaces(dev); + return HDF_FAILURE; +} +static int32_t FunGetDeviceDescriptor(struct HostDevice *port, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + length = USB_MAX_DESCRIPTOR_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (!buffer) { + HDF_LOGE("%{public}s:%{public}d malloc fail ", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_DESCRIPTOR, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, (int32_t)USB_DDK_DT_DEVICE << 8, 0, USB_CTRL_SET_TIMEOUT, + buffer, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed ret:%{public}d", __func__, __LINE__, ret); + goto out; + } + PrintBuffer("FunGetDeviceDescriptor", buffer, length); + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + } + +out: + if (buffer) + OsalMemFree(buffer); + return ret; +} + +static int32_t FunGetConfigDescriptor(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + uint8_t configId = 0; + + if ((port == NULL) || (reply == NULL) || (data == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &configId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + length = USB_MAX_DESCRIPTOR_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (!buffer) { + HDF_LOGE("%{public}s:%{public}d malloc fail ", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_DESCRIPTOR, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, ((int32_t)USB_DDK_DT_CONFIG << 8) + configId, 0, + USB_CTRL_SET_TIMEOUT, buffer, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + goto out; + } + PrintBuffer("FunGetConfigDescriptor", buffer, length); + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + } + +out: + if (buffer) + OsalMemFree(buffer); + return ret; +} + +static int32_t FunGetStringDescriptor(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + uint8_t stringId = 0; + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &stringId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + length = USB_MAX_DESCRIPTOR_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (!buffer) { + HDF_LOGE("%{public}s:%{public}d malloc fail ", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_DESCRIPTOR, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, ((int32_t)USB_DDK_DT_STRING << 8) + stringId, 0, + USB_CTRL_SET_TIMEOUT, buffer, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + goto out; + } + PrintBuffer("FunGetStringDescriptor", buffer, length); + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + } + +out: + if (buffer) + OsalMemFree(buffer); + return ret; +} + +static int32_t FunGetActiveConfig(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t configId = 0; + uint32_t length = 1; + + HDF_LOGE("%{public}s: mangf FunControlTransfer entry", __func__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, 0, 0, USB_CTRL_SET_TIMEOUT, &configId, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufWriteUint8(reply, configId)) { + ret = HDF_ERR_IO; + } + return ret; +} +static int32_t FunSetActiveConfig(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t configId = 0, configIdOld = 0, configIdNew = 0; + uint32_t length = 1; + + HDF_LOGE("%{public}s: mangf FunControlTransfer entry", __func__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &configId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + length = 1; + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, 0, 0, USB_CTRL_SET_TIMEOUT, &configIdOld, &length); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d config:%{public}d leng:%{public}d", __func__, __LINE__, ret, + configIdOld, length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d getConfiguration failed ret:%{public}d", __func__, __LINE__, ret); + return HDF_ERR_INVALID_PARAM; + } + if (configId == configIdOld) { + HDF_LOGE("%{public}s:%{public}d setConfiguration success configId:%{public}d old:%{public}d", __func__, + __LINE__, configId, configIdOld); + return HDF_SUCCESS; + } + length = 0; + ret = UsbControlTransfer(port, USB_DDK_REQ_SET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_TO_DEVICE, (int32_t)0 + configId, 0, USB_CTRL_SET_TIMEOUT, &configId, + &length); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d configId:%{public}d id2:%{public}d length:%{public}d", __func__, + __LINE__, ret, configId, configIdOld, length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d setConfiguration failed ret:%{public}d", __func__, __LINE__, ret); + return HDF_ERR_IO; + } + length = 1; + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, 0, 0, USB_CTRL_SET_TIMEOUT, &configIdNew, &length); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d config:%{public}d leng:%{public}d", __func__, __LINE__, ret, + configIdNew, length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d getConfiguration failed ret:%{public}d", __func__, __LINE__, ret); + return HDF_ERR_IO; + } + if (configId != configIdNew) { + HDF_LOGE("%{public}s:%{public}d setConfiguration success configId:%{public}d new:%{public}d", __func__, + __LINE__, configId, configIdNew); + return HDF_ERR_NOT_SUPPORT; + } + if (configId != 0) { + uint8_t busNum = port->busNum; + uint8_t devAddr = port->devAddr; + UsbdRelease(port); + port->busNum = busNum; + port->devAddr = devAddr; + ret = UsbdInit(port); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbInit failed ret:%{public}d", __func__, __LINE__, ret); + UsbdRelease(port); + RemoveDevFromService(port->service, port); + OsalMemFree(port); + port = NULL; + return ret; + } + DataFifoReset(&port->readFifo); + + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen success", __func__, __LINE__); + OsalMSleep(OPEN_SLEPP_TIME); + } + return ret; +} + +static int32_t FunSetInterface(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, altIndex = 0; + uint32_t length = 0; + UsbInterfaceHandle *interfaceHandle = NULL; + + HDF_LOGE("%{public}s:%{public}d mangf FunControlTransfer entry", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &altIndex)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + interfaceHandle = InterfaceIdToHandle(port, interfaceId); + if (interfaceHandle == NULL) { + HDF_LOGE( + "%{public}s:%{public}d InterfaceIdToHandle failed bus:%{public}d devAddr:%{public}d interfaceId:%{public}d", + __func__, __LINE__, port->busNum, port->devAddr, interfaceId); + return HDF_FAILURE; + } + + ret = UsbSelectInterfaceSetting(interfaceHandle, altIndex, &port->iface[interfaceId]); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d ifId:%{public}d altIdx:%{public}d length:%{public}d", __func__, + __LINE__, ret, interfaceId, altIndex, length); + return ret; +} + +static int32_t FunBulkRead(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + struct UsbPipeInfo pipe; + struct RequestMsg *reqMsg = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + memset(&pipe, 0, sizeof(pipe)); + memset(&parmas, 0, sizeof(parmas)); + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed", __func__); + return HDF_FAILURE; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (interfaceHandle == NULL) { + HDF_LOGE( + "%{public}s:%{public}d InterfaceIdToHandle failed bus:%{public}d devAddr:%{public}d interfaceId:%{public}d", + __func__, __LINE__, port->busNum, port->devAddr, pipe.interfaceId); + return HDF_FAILURE; + } + reqMsg = UsbdAllocRequestMsg(interfaceHandle, 0, pipe.maxPacketSize); + if (reqMsg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + parmas.userData = (void *)port; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.interfaceId = pipe.interfaceId; + parmas.callback = UsbdReadCallback; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + parmas.dataReq.length = pipe.maxPacketSize; + ret = UsbFillRequest(reqMsg->request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto error; + } + + OsalMutexLock(&port->requestLock); + struct UsbIfRequest *ifReq = (struct UsbIfRequest *)reqMsg->request; + struct UsbHostRequest *hostReq = (struct UsbHostRequest *)ifReq->hostRequest; + OsalSemInit(&hostReq->sem, 0); + ret = UsbSubmitRequestAsync(reqMsg->request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestAsync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMutexUnlock(&port->requestLock); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto error; + } + HdfSListAdd(&port->requestQueue, &reqMsg->node); + OsalMutexUnlock(&port->requestLock); + +error: + UsbdFreeRequestMsg(reqMsg); + return ret; +} + +static int32_t FunBulkWrite(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + uint32_t length = 0; + uint8_t *buffer = NULL; + struct UsbPipeInfo pipe; + struct RequestMsg *reqMsg = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + memset(&pipe, 0, sizeof(pipe)); + memset(&parmas, 0, sizeof(parmas)); + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed", __func__); + return HDF_FAILURE; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (interfaceHandle == NULL) { + return HDF_FAILURE; + } + reqMsg = UsbdAllocRequestMsg(interfaceHandle, 0, pipe.maxPacketSize); + if (reqMsg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + parmas.userData = (void *)port; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.interfaceId = pipe.interfaceId; + parmas.callback = UsbdWriteCallback; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + parmas.dataReq.length = length; + parmas.dataReq.buffer = buffer; + ret = UsbFillRequest(reqMsg->request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto error; + } + + OsalMutexLock(&port->requestLock); + struct UsbIfRequest *ifReq = (struct UsbIfRequest *)reqMsg->request; + struct UsbHostRequest *hostReq = (struct UsbHostRequest *)ifReq->hostRequest; + OsalSemInit(&hostReq->sem, 0); + ret = UsbSubmitRequestAsync(reqMsg->request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestAsync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMutexUnlock(&port->requestLock); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto error; + } + HdfSListAdd(&port->requestQueue, &reqMsg->node); + OsalMutexUnlock(&port->requestLock); + +error: + UsbdFreeRequestMsg(reqMsg); + return HDF_SUCCESS; +} + +static int32_t FunRequestQueue(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = 0; + struct UsbPipeInfo pipe; + struct RequestMsg *reqMsg = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + uint8_t interfaceId = 0, pipeId = 0; + uint8_t *clientData = NULL, *buffer = NULL, *tclientData = NULL; + uint32_t clientLength = 0, length = 0; + bool bWrite = false; + int32_t requestCount = 0; + memset(&pipe, 0, sizeof(pipe)); + memset(&parmas, 0, sizeof(parmas)); + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadBuffer(data, (const void **)&tclientData, &clientLength)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + clientData = (uint8_t *)OsalMemAlloc(clientLength); + if (!clientData) { + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc fail size:%{public}d", __func__, __LINE__, clientLength); + return HDF_ERR_MALLOC_FAIL; + } + memcpy(clientData, tclientData, clientLength); + + PrintBuffer("clientData", clientData, clientLength); + PrintBuffer("buffer", buffer, length); + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed, interfaceId=%{public}d,pipeId=%{public}d pipeAddr:%{public}d", + __func__, interfaceId, pipeId, pipe.pipeAddress); + ret = HDF_FAILURE; + goto error1; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (interfaceHandle == NULL) { + ret = HDF_FAILURE; + goto error1; + } + reqMsg = UsbdAllocRequestMsg(interfaceHandle, 0, pipe.maxPacketSize); + if (reqMsg == NULL) { + ret = HDF_ERR_MALLOC_FAIL; + goto error1; + } + reqMsg->clientData = clientData; + reqMsg->clientLength = clientLength; + reqMsg->request->compInfo.status = -1; + bWrite = (pipe.pipeDirection == USB_PIPE_DIRECTION_OUT); + parmas.interfaceId = pipe.interfaceId; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = USB_CTRL_SET_TIMEOUT; + parmas.dataReq.numIsoPackets = 0; + parmas.userData = (void *)port; + parmas.dataReq.length = length; + HDF_LOGE( + "%{public}s: interfaceId=%{public}d,pipeId=%{public}d bwrite:%{public}d pipDriect:%{public}d " + "pipeAddr:%{public}d Addr:%{public}d", + __func__, interfaceId, pipeId, bWrite, pipe.pipeDirection, pipe.pipeAddress, parmas.pipeAddress); + if (bWrite) { + parmas.callback = UsbdWriteCallback; + parmas.dataReq.buffer = buffer; + } else { + parmas.callback = UsbdReadCallback; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + } + ret = UsbFillRequest(reqMsg->request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: fumang UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto error; + } + HDF_LOGE( + "%{public}s: interfaceId=%{public}d,pipeId=%{public}d bwrite:%{public}d pipDriect:%{public}d pmdir:%{public}d ", + __func__, interfaceId, pipeId, bWrite, pipe.pipeDirection, parmas.dataReq.directon); + OsalMutexLock(&port->requestLock); + struct UsbIfRequest *ifReq = (struct UsbIfRequest *)reqMsg->request; + struct UsbHostRequest *hostReq = (struct UsbHostRequest *)ifReq->hostRequest; + OsalSemInit(&hostReq->sem, 0); + ret = UsbSubmitRequestAsync(reqMsg->request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("fumang UsbSubmitRequestAsync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMutexUnlock(&port->requestLock); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto error; + } + HdfSListAddTail(&port->requestQueue, &reqMsg->node); + requestCount = HdfSListCount(&port->requestQueue); + OsalMutexUnlock(&port->requestLock); + HDF_LOGE("%{public}s:%{public}d fumang send request %{public}p ok, count = %{public}d", __func__, __LINE__, reqMsg, + requestCount); + return HDF_SUCCESS; +error: + UsbdFreeRequestMsg(reqMsg); + return ret; +error1: + if (clientData) { + OsalMemFree(clientData); + clientData = NULL; + } + return ret; +} +static int32_t FunRequestWait(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_SUCCESS; + struct RequestMsg *reqMsg = NULL; + struct HdfSListNode *requestNode = NULL; + uint8_t *buffer = NULL; + uint32_t length = 0; + int32_t timeout = 0; + int32_t requestCount = 0; + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s:%{public}d request wait entry ok timeout = %{public}d", __func__, __LINE__, timeout); + + OsalMutexLock(&port->requestLock); + if (!HdfSListIsEmpty(&port->requestQueue)) { + requestNode = HdfSListPop(&port->requestQueue); + requestCount = HdfSListCount(&port->requestQueue); + } + OsalMutexUnlock(&port->requestLock); + if (requestNode == NULL) { + HDF_LOGE("%{public}s:%{public}d fumang request node is null", __func__, __LINE__); + return HDF_FAILURE; + } + reqMsg = HDF_SLIST_CONTAINER_OF(struct HdfSListNode, requestNode, struct RequestMsg, node); + if (reqMsg == NULL) { + HDF_LOGE("%{public}s:%{public}d fumang request msg is null", __func__, __LINE__); + return HDF_FAILURE; + } + + HDF_LOGE("%{public}s:%{public}d fumang get request %{public}p ok, count=%{public}d status:%{public}d", __func__, + __LINE__, reqMsg, requestCount, reqMsg->request->compInfo.status); + + if ((int32_t)(reqMsg->request->compInfo.status) == -1) { + HDF_LOGE("%{public}s:%{public}d fumang request waitting... timeout:%{public}d", __func__, __LINE__, timeout); + ret = OsalSemWait(&((struct UsbIfRequest *)reqMsg->request)->hostRequest->sem, timeout); + HDF_LOGE("%{public}s:%{public}d wait over ret:%{public}d timeout:%{public}d status:%{public}d", __func__, + __LINE__, ret, timeout, reqMsg->request->compInfo.status); + ret = (int32_t)(reqMsg->request->compInfo.status); + if ((ret == USB_REQUEST_COMPLETED) || (USB_REQUEST_COMPLETED_SHORT == ret)) { + ret = HDF_SUCCESS; + } + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d fumang request wait failed ret = %{public}d", __func__, __LINE__, ret); + goto error; + } + } + + OsalMutexLock(&port->readLock); + length = DataFifoLen(&port->readFifo); + HDF_LOGE("%{public}s:%{public}d len:%{public}d", __func__, __LINE__, length); + if (length > 0) { + buffer = (uint8_t *)OsalMemCalloc(length + 1); + if (buffer == NULL) { + HDF_LOGE("%{public}s:%{public}d OsalMemCalloc error", __func__, __LINE__); + ret = HDF_ERR_MALLOC_FAIL; + OsalMutexUnlock(&port->readLock); + goto error; + } + memset(buffer, 0, length + 1); + length = DataFifoRead(&port->readFifo, buffer, length); + HDF_LOGE("%{public}s:%{public}d len:%{public}d", __func__, __LINE__, length); + } + OsalMutexUnlock(&port->readLock); + if (!HdfSbufWriteBuffer(reply, reqMsg->clientData, reqMsg->clientLength)) { + ret = HDF_ERR_IO; + HDF_LOGE("%{public}s:%{public}d fumang HdfSbufWriteBuffer failed", __func__, __LINE__); + goto out; + } + if (length > 0) { + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + HDF_LOGE("%{public}s:%{public}d fumang HdfSbufWriteBuffer failed", __func__, __LINE__); + goto out; + } + PrintBuffer("fumang request wait get data:", buffer, length); + } else { + if (!HdfSbufWriteUint32(reply, length)) { + ret = HDF_ERR_IO; + HDF_LOGE("%{public}s:%{public}d fumang HdfSbufWriteBuffer failed", __func__, __LINE__); + goto out; + } + } + HDF_LOGE("%{public}s:%{public}d fumang request wait success, buffer=%{public}p, length=%{public}d", __func__, + __LINE__, buffer, length); +out: + if (buffer) + OsalMemFree(buffer); +error: + UsbdFreeRequestMsg(reqMsg); + return ret; +} + +static int32_t FunRequestCancel(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_SUCCESS; + struct RequestMsg *reqMsg = NULL; + struct HdfSListNode *requestNode = NULL; + uint8_t interfaceId = 0, endpointId = 0; + + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &endpointId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + OsalMutexLock(&port->requestLock); + if (!HdfSListIsEmpty(&port->requestQueue)) { + requestNode = HdfSListPop(&port->requestQueue); + } + OsalMutexUnlock(&port->requestLock); + if (requestNode == NULL) { + HDF_LOGE("%{public}s:%{public}d request node is null", __func__, __LINE__); + return HDF_SUCCESS; + } + reqMsg = HDF_SLIST_CONTAINER_OF(struct HdfSListNode, requestNode, struct RequestMsg, node); + if (reqMsg == NULL) { + HDF_LOGE("%{public}s:%{public}d request msg is null", __func__, __LINE__); + return HDF_FAILURE; + } + ret = UsbCancelRequest(reqMsg->request); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d request cancel failed = %{public}d", __func__, __LINE__, ret); + } + OsalMSleep(SUBMIT_SLEEP_TIME); + UsbdFreeRequestMsg(reqMsg); + return ret; +} + +static int32_t UsbdInit(struct HostDevice *dev) +{ + int32_t ret = HDF_FAILURE; + struct UsbSession *session = NULL; + HDF_LOGE("%{public}s:%{public}d mangf UsbdInit", __func__, __LINE__); + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s:%{public}d mangf UsbdInit", __func__, __LINE__); + if (dev->initFlag == true) { + HDF_LOGE("%{public}s:%{public}d: mangf initFlag is true", __func__, __LINE__); + return HDF_SUCCESS; + } + HDF_LOGE("%{public}s:%{public}d mangf UsbdInit", __func__, __LINE__); + ret = UsbInitHostSdk(NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbInitHostSdk faild", __func__, __LINE__); + return HDF_ERR_IO; + } + if (dev->service) + dev->service->session = session; + + HDF_LOGE("%{public}s:%{public}d UsbdClaimInterfaces start", __func__, __LINE__); + ret = UsbdClaimInterfaces(dev); + HDF_LOGE("%{public}s:%{public}d UsbdClaimInterfaces end ret:%{public}d", __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbdClaimInterfaces faild ret:%{public}d", __func__, __LINE__, ret); + goto error_claim_interfaces; + } + + HDF_LOGE("%{public}s:%{public}d UsbdOpenInterfaces start", __func__, __LINE__); + ret = UsbdOpenInterfaces(dev); + HDF_LOGE("%{public}s:%{public}d UsbdOpenInterfaces end ret:%{public}d", __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbdOpenInterfaces faild ret:%{public}d", __func__, __LINE__, ret); + goto error_open_interfaces; + } + + HDF_LOGE("%{public}s:%{public}d UsbdClaimInterfaces start", __func__, __LINE__); + ret = UsbdGetCtrlPipe(dev); + HDF_LOGE("%{public}s:%{public}d UsbdGetCtrlPipe end ret:%{public}d", __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbdGetPipes failed ret:%{public}d", __func__, __LINE__, ret); + goto error_get_pipes; + } + + dev->initFlag = true; + HDF_LOGD("%{public}s:%{public}d========OK busNum:%{public}d devAddr:%{public}d", __func__, __LINE__, dev->busNum, + dev->devAddr); + return HDF_SUCCESS; + +error_get_pipes: + UsbdCloseInterfaces(dev); +error_open_interfaces: + UsbdReleaseInterfaces(dev); +error_claim_interfaces: + UsbExitHostSdk(dev->service->session); + HDF_LOGD("%{public}s:%{public}d UsbExitHostSdk session:%{public}s ", __func__, __LINE__, + dev->service->session ? "OK" : "NULL"); + dev->service->session = NULL; + return ret; +} + +static void UsbdRelease(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return; + } + + if (dev->initFlag == false) { + HDF_LOGE("%{public}s:%{public}d: initFlag is false", __func__, __LINE__); + return; + } + + UsbdFreeCtrlPipe(dev); + UsbdCloseInterfaces(dev); + UsbdReleaseInterfaces(dev); + UsbExitHostSdk(dev->service->session); + HDF_LOGD("%{public}s:%{public}d UsbExitHostSdk session:%{public}s ", __func__, __LINE__, + dev->service->session ? "OK" : "NULL"); + dev->service->session = NULL; + OsalMutexDestroy(&dev->writeLock); + OsalMutexDestroy(&dev->readLock); + OsalMutexDestroy(&dev->lock); + OsalMutexDestroy(&dev->requestLock); + dev->busNum = 0; + dev->devAddr = 0; + dev->initFlag = false; +} + +static int32_t FunOpenDevice(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int ret; + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (port->initFlag) { + HDF_LOGE("%{public}s:%{public}d device is already on flag:%{public}d bus:%{public}d dev:%{public}d", __func__, + __LINE__, port->initFlag, port->busNum, port->devAddr); + return HDF_SUCCESS; + } + ret = UsbdInit(port); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbInit failed ret:%{public}d", __func__, __LINE__, ret); + goto err_init; + } + ret = UsbdAllocFifo(&port->readFifo, READ_BUF_SIZE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbAllocFifo failed ret:%{public}d", __func__, __LINE__, ret); + ret = HDF_ERR_INVALID_PARAM; + goto err_fifo; + } + + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen success", __func__, __LINE__); + OsalMSleep(OPEN_SLEPP_TIME); + return HDF_SUCCESS; + +err_fifo: + UsbdFreeFifo(&port->readFifo); +err_init: + UsbdRelease(port); + RemoveDevFromService(port->service, port); + OsalMemFree(port); + port = NULL; + return ret; +} + +static int32_t FunCloseDevice(struct HostDevice *port, struct HdfSBuf *data) +{ + if (port == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!port->initFlag) { + HDF_LOGE("%{public}s:%{public}d device already close", __func__, __LINE__); + return HDF_SUCCESS; + } + UsbdFreeFifo(&port->readFifo); + UsbdRelease(port); + RemoveDevFromService(port->service, port); + OsalMemFree(port); + port = NULL; + return HDF_SUCCESS; +} + +static int32_t FunSetRole(struct HdfSBuf *data, struct HdfSBuf *reply, struct UsbdService *service) +{ + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + if (!HdfSbufReadInt32(data, &portId)) { + HDF_LOGE("%{public}s:%{public}d mangf Read data faild", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &powerRole)) { + HDF_LOGE("%{public}s:%{public}d mangf Read data faild", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &dataRole)) { + HDF_LOGE("%{public}s:%{public}d mangf Read data faild", __func__, __LINE__); + return HDF_ERR_IO; + } + + HDF_LOGE("%{public}s:%{public}d FunSetRole %{public}d %{public}d %{public}d", __func__, __LINE__, portId, powerRole, + dataRole); + int32_t ret = SetPort(portId, powerRole, dataRole, service); + if (ret) { + HDF_LOGE("%{public}s:%{public}d FunSetRole fasle", __func__, __LINE__); + return HDF_ERR_IO; + } + if (reply) + HdfSbufWriteInt32(reply, ret); + return HDF_SUCCESS; +} + +static int32_t FunQueryPort(struct HdfSBuf *data, struct HdfSBuf *reply, struct UsbdService *service) +{ + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + int32_t mode = 0; + int32_t ret = QueryPort(&portId, &powerRole, &dataRole, &mode, service); + if (ret) { + HDF_LOGE("%{public}s:%{public}d FunQueryPort fasle", __func__, __LINE__); + return HDF_ERR_IO; + } + if (reply) { + HdfSbufWriteInt32(reply, portId); + HdfSbufWriteInt32(reply, powerRole); + HdfSbufWriteInt32(reply, dataRole); + HdfSbufWriteInt32(reply, mode); + } + return HDF_SUCCESS; +} + +static int32_t FunGetCurrentFunctions(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t funcs = UsbdGetFunction(); + HDF_LOGE("%{public}s:%{public}d FunSetCurrentFunctions funcs: %{public}d", __func__, __LINE__, funcs); + if (reply) + HdfSbufWriteInt32(reply, funcs); + return HDF_SUCCESS; +} + +static int32_t FunSetCurrentFunctions(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t funcs = 0; + HdfSbufReadInt32(data, &funcs); + HDF_LOGE("%{public}s:%{public}d FunSetCurrentFunctions funcs: %{public}d", __func__, __LINE__, funcs); + int ret = UsbdSetFunction(funcs); + if (ret) { + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t DispatchBindUsbSubscriber(struct UsbdService *service, struct HdfSBuf *data) +{ + struct UsbdSubscriber *subscriber = NULL; + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + if (service == NULL || data == NULL) { + HDF_LOGW("%{public}s:%{public}d param is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + struct HdfRemoteService *remoteService = HdfSBufReadRemoteService(data); + if (remoteService == NULL) { + HDF_LOGW("%{public}s: remoteService is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + + subscriber = (struct UsbdSubscriber *)OsalMemCalloc(sizeof(struct UsbdSubscriber)); + if (subscriber == NULL) { + HDF_LOGE("%{public}s: calloc subscriber error", __func__); + return HDF_ERR_MALLOC_FAIL; + } + memset(subscriber, 0, sizeof(struct UsbdSubscriber)); + subscriber->remoteService = remoteService; + return BindUsbSubscriber(service, subscriber); +} + +static int32_t DispatchUnbindUsbSubscriber(struct UsbdService *service) +{ + if (service == NULL) { + HDF_LOGW("%{public}s:%{public}d param is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + return UnbindUsbSubscriber(service); +} + +int32_t UsbdServiceDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + struct UsbdService *service = NULL; + struct HostDevice *port = NULL; + + if (client == NULL) { + HDF_LOGE("%{public}s:%{public}d client is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + if (client->device == NULL) { + HDF_LOGE("%{public}s:%{public}d client->device is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + if (client->device->service == NULL) { + HDF_LOGE("%{public}s:%{public}d client->device->service is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + + HDF_LOGE("%{public}s:%{public}d usbd dispatch cmd = %{public}d", __func__, __LINE__, cmd); + service = (struct UsbdService *)client->device->service; + if (cmd != CMD_FUN_GET_CURRENT_FUNCTIONS && cmd != CMD_FUN_SET_CURRENT_FUNCTIONS && cmd != CMD_SET_ROLE && + cmd != CMD_QUERY_PORT && CMD_BIND_USB_SUBSCRIBER != cmd && CMD_UNBIND_USB_SUBSCRIBER != cmd) { + uint8_t busNum = 0; + uint8_t devAddr = 0; + int32_t ret = 0; + ret = ParseDeviceBuf(data, &busNum, &devAddr); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d cmd = %{public}d ParseDeviceBuf error:%{public}d", __func__, __LINE__, cmd, + ret); + return ret; + } + port = FindDevFromService(service, busNum, devAddr); + switch (cmd) { + case CMD_FUN_OPEN_DEVICE: + if (!port) { + ret = HostDeviceCreate(&port); + HDF_LOGE( + "%{public}s:%{public}d OpenDevice create ret:%{public}d busNum:%{public}d devAddr:%{public}d " + "port:%{public}p", + __func__, __LINE__, ret, busNum, devAddr, port); + if ((HDF_SUCCESS == ret) && (port)) { + port->service = service; + port->busNum = busNum; + port->devAddr = devAddr; + OsalMutexLock(&service->lock); + HdfSListAdd(&service->devList, &port->node); + OsalMutexUnlock(&service->lock); + } else { + return ret; + } + } + break; + default: + if (!port) { + HDF_LOGE("%{public}s:%{public}d cmd = %{public}d busNum:%{public}d devAddr:%{public}d no device", + __func__, __LINE__, cmd, busNum, devAddr); + return HDF_DEV_ERR_NO_DEVICE; + } + break; + } + } + HDF_LOGE("%{public}s:%{public}d cmd = %{public}d port:%{public}p", __func__, __LINE__, cmd, port); + switch (cmd) { + case CMD_BIND_USB_SUBSCRIBER: + return DispatchBindUsbSubscriber(service, data); + case CMD_UNBIND_USB_SUBSCRIBER: + return DispatchUnbindUsbSubscriber(service); + case CMD_FUN_OPEN_DEVICE: + return FunOpenDevice(port, data, reply); + case CMD_FUN_CLOSE_DEVICE: + return FunCloseDevice(port, data); + case CMD_FUN_SEND_BULK_READ_ASYNC: + return FunBulkRead(port, data, reply); + case CMD_FUN_SEND_BULK_WRITE_ASYNC: + return FunBulkWrite(port, data, reply); + case CMD_FUN_SEND_BULK_READ_SYNC: + case CMD_FUN_SEND_INTERRUPT_READ_SYNC: + case CMD_FUN_SEND_ISO_READ_SYNC: + return FunBulkReadSync(port, data, reply); + case CMD_FUN_SEND_BULK_WRITE_SYNC: + case CMD_FUN_SEND_INTERRUPT_WRITE_SYNC: + case CMD_FUN_SEND_ISO_WRITE_SYNC: + return FunBulkWriteSync(port, data, reply); + case CMD_FUN_SEND_CTRL_REQUEST_SYNC: + return FunControlTransfer(port, data, reply); + case CMD_FUN_GET_DEVICE_DESCRIPTOR: + return FunGetDeviceDescriptor(port, reply); + case CMD_FUN_GET_CONFIG_DESCRIPTOR: + return FunGetConfigDescriptor(port, data, reply); + case CMD_FUN_GET_STRING_DESCRIPTOR: + return FunGetStringDescriptor(port, data, reply); + case CMD_FUN_REQUEST_QUEUE: + return FunRequestQueue(port, data, reply); + case CMD_FUN_REQUEST_WAIT: + return FunRequestWait(port, data, reply); + case CMD_FUN_REQUEST_CANCEL: + return FunRequestCancel(port, data, reply); + case CMD_FUN_CLAIM_INTERFACE: + return FunClaimInterface(port, data); + case CMD_FUN_RELEASE_INTERFACE: + return FunReleaseInterface(port, data); + case CMD_FUN_SET_CONFIG: + return FunSetActiveConfig(port, data, reply); + case CMD_FUN_GET_CONFIG: + return FunGetActiveConfig(port, data, reply); + case CMD_FUN_SET_INTERFACE: + return FunSetInterface(port, data, reply); + case CMD_SET_ROLE: + return FunSetRole(data, reply, service); + case CMD_QUERY_PORT: + return FunQueryPort(data, reply, service); + case CMD_FUN_GET_CURRENT_FUNCTIONS: + return FunGetCurrentFunctions(data, reply); + case CMD_FUN_SET_CURRENT_FUNCTIONS: + return FunSetCurrentFunctions(data, reply); + default: + return HDF_ERR_NOT_SUPPORT; + } + return HDF_SUCCESS; +} + +static int32_t HostDeviceInit(struct HostDevice *port) +{ + if (!port) { + HDF_LOGE("%{public}s:%{public}d param failed", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + port->busNum = 0; + port->devAddr = 0; + port->initFlag = false; + port->interfaceCnt = 0; + + if (OsalMutexInit(&port->lock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + if (OsalMutexInit(&port->requestLock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + if (OsalMutexInit(&port->writeLock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + if (OsalMutexInit(&port->readLock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + HdfSListInit(&port->requestQueue); + return HDF_SUCCESS; +} + +int32_t HostDeviceCreate(struct HostDevice **port) +{ + int32_t ret = HDF_SUCCESS; + struct HostDevice *tmp = NULL; + if (!port) { + return HDF_FAILURE; + } + tmp = (struct HostDevice *)OsalMemCalloc(sizeof(struct HostDevice)); + if (!tmp) { + HDF_LOGE("%{public}s:%{public}d Alloc usb host device failed", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(tmp, 0, sizeof(struct HostDevice)); + + ret = HostDeviceInit(tmp); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d HostDeviceInit fail!", __func__, __LINE__); + goto out; + } + + tmp->initFlag = false; + *port = tmp; + return HDF_SUCCESS; +out: + OsalMemFree(tmp); + return ret; +} + +int32_t UsbdRealseDevices(struct UsbdService *service) +{ + if (!service) { + return HDF_ERR_INVALID_PARAM; + } + OsalMutexLock(&service->lock); + while (!HdfSListIsEmpty(&service->devList)) { + struct HostDevice *port = (struct HostDevice *)HdfSListPop(&service->devList); + if (port) { + UsbdRelease(port); + OsalMemFree(port); + } + } + OsalMutexUnlock(&service->lock); + return HDF_SUCCESS; +} + +static struct HostDevice *FindDevFromService(struct UsbdService *service, uint8_t busNum, uint8_t devAddr) +{ + struct HdfSListIterator it; + struct HostDevice *port = NULL; + bool flag = false; + if (!service) { + return NULL; + } + + OsalMutexLock(&service->lock); + HdfSListIteratorInit(&it, &service->devList); + while (HdfSListIteratorHasNext(&it)) { + port = (struct HostDevice *)HdfSListIteratorNext(&it); + if (!port) { + continue; + } + if ((port->busNum == busNum) && (port->devAddr == devAddr)) { + flag = true; + break; + } + } + OsalMutexUnlock(&service->lock); + if (!flag) { + return NULL; + } + return port; +} + +static int32_t RemoveDevFromService(struct UsbdService *service, struct HostDevice *port) +{ + struct HdfSListIterator it; + struct HostDevice *tport = NULL; + if (!service || !port) { + return HDF_SUCCESS; + } + + OsalMutexLock(&service->lock); + HdfSListIteratorInit(&it, &service->devList); + while (HdfSListIteratorHasNext(&it)) { + tport = (struct HostDevice *)HdfSListIteratorNext(&it); + if (!tport) { + continue; + } + if ((tport->busNum == port->busNum) && (tport->devAddr == port->devAddr)) { + HdfSListIteratorRemove(&it); + break; + } + } + OsalMutexUnlock(&service->lock); + + return HDF_SUCCESS; +} diff --git a/hdi/service/src/usbd_function.c b/hdi/service/src/usbd_function.c new file mode 100644 index 00000000..0797af91 --- /dev/null +++ b/hdi/service/src/usbd_function.c @@ -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. + */ +#include "usbd_function.h" + +#include +#include +#include +#include +#include +#include +#include "devmgr_hdi.h" +#include "hdf_log.h" +#include "hdf_remote_service.h" +#include "osal_time.h" +#include "securec.h" +#include "sys_param.h" + +#define DEV_SERVICE_NAME "usbfn_master" +#define ACM_SERVICE_NAME "usbfn_cdcacm" +#define ECM_SERVICE_NAME "usbfn_cdcecm" + +#define SYS_USB_FFS_READY "sys.usb.ffs.ready" +#define SYS_USB_CONFIGFS "sys.usb.configfs" +#define SYS_USB_CONFIG "sys.usb.config" +#define HDC_CONFIG_OFF "none" +#define HDC_CONFIG_ON "hdc" +#define HDC_CONFIGFS_OFF "0" +#define HDC_CONFIGFS_ON "1" + +#define FUNCTION_ADD 1 +#define FUNCTION_DEL 2 + +#define USB_INIT 100 +#define USB_RELEASE 101 +#define USB_ACM_OPEN 0 +#define USB_ACM_CLOSE 1 + +#define USB_FUNCTION_ACM 1 +#define USB_FUNCTION_ECM 2 +#define USB_FUNCTION_ACM_ECM 3 +#define USB_FUNCTION_HDC 4 +#define FUNCTIONS_MAX 7 + +static uint8_t currentFuncs = USB_FUNCTION_HDC; +static uint8_t pre_acm_ecm; + +static int send_cmd_to_service(const char *name, int cmd, unsigned char funcMask) +{ + int status; + struct HdfRemoteService *service; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + struct HDIServiceManager *servmgr = HDIServiceManagerGet(); + if (servmgr == NULL) { + printf("HDIServiceManagerGet err\n"); + return HDF_FAILURE; + } + service = servmgr->GetService(servmgr, name); + HDIServiceManagerRelease(servmgr); + if (service == NULL) { + printf("GetService err\n"); + return HDF_FAILURE; + } + + data = HdfSBufTypedObtain(SBUF_IPC); + reply = HdfSBufTypedObtain(SBUF_IPC); + if (data == NULL || reply == NULL) { + printf("data or reply err\n"); + status = HDF_FAILURE; + goto error; + } + if (!HdfSbufWriteInt8(data, funcMask)) { + printf("UsbEcmRead HdfSbufWriteInt8 error"); + status = HDF_FAILURE; + goto error_sbuf; + } + status = service->dispatcher->Dispatch(service, cmd, data, reply); + if (status) { + printf("serice %s dispatch cmd : %d error\n", name, cmd); + } +error_sbuf: + HdfSBufRecycle(data); + HdfSBufRecycle(reply); +error: + HdfRemoteServiceRecycle(service); + return status; +} + +// 1. 先卸载(acm/ecm, hdc) 2.再加载 +int UsbdSetFunction(int funcs) +{ + uint8_t _acm_ecm = funcs & USB_FUNCTION_ACM_ECM; + uint8_t status; + if (funcs < 0 || funcs > FUNCTIONS_MAX) { + HDF_LOGI("%{public}s:%{public}d funcs invalid \n", __func__, __LINE__); + goto err; + } + // HDC + if ((currentFuncs & USB_FUNCTION_HDC) || (funcs == 0)) { + if (!(funcs & USB_FUNCTION_HDC)) { + if (currentFuncs != funcs) { + HDF_LOGI("%{public}s:%{public}d remove hdc\n", __func__, __LINE__); + status = SystemSetParameter(SYS_USB_CONFIG, HDC_CONFIG_OFF); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove hdc config error = %{public}d\n", __func__, __LINE__, + status); + goto err; + } + status = SystemSetParameter(SYS_USB_CONFIGFS, HDC_CONFIGFS_OFF); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove hdc configs error = %{public}d\n", __func__, __LINE__, + status); + goto err; + } + } + } + } else { + if (funcs & USB_FUNCTION_HDC) { + HDF_LOGI("%{public}s:%{public}d add hdc\n", __func__, __LINE__); + status = SystemSetParameter(SYS_USB_CONFIGFS, HDC_CONFIGFS_ON); + if (status) { + HDF_LOGE("%{public}s:%{public}d add hdc configfs error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + status = SystemSetParameter(SYS_USB_CONFIG, HDC_CONFIG_ON); + if (status) { + HDF_LOGE("%{public}s:%{public}d add hdc config error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + } + + // acm_ecm + if (pre_acm_ecm != _acm_ecm) { + if ((pre_acm_ecm > 0) || (funcs == 0)) { + HDF_LOGI("%{public}s:%{public}d remove pre_acm_ecm = %{public}d \n", __func__, __LINE__, pre_acm_ecm); + if (pre_acm_ecm & USB_FUNCTION_ACM) { + status = send_cmd_to_service(ACM_SERVICE_NAME, USB_RELEASE, pre_acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d release acm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + if (pre_acm_ecm & USB_FUNCTION_ECM) { + status = send_cmd_to_service(ECM_SERVICE_NAME, USB_RELEASE, pre_acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d release ecm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + status = send_cmd_to_service(DEV_SERVICE_NAME, FUNCTION_DEL, pre_acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove device error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + if (_acm_ecm > 0) { + HDF_LOGI("%{public}s:%{public}d add _acm_ecm = %{public}d\n", __func__, __LINE__, _acm_ecm); + status = send_cmd_to_service(DEV_SERVICE_NAME, FUNCTION_ADD, _acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d add device _acm_ecm:%{public}d error = %{public}d\n", __func__, + __LINE__, _acm_ecm, status); + goto err; + } + if (_acm_ecm & USB_FUNCTION_ACM) { + status = send_cmd_to_service(ACM_SERVICE_NAME, USB_INIT, _acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove acm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + if (_acm_ecm & USB_FUNCTION_ECM) { + status = send_cmd_to_service(ECM_SERVICE_NAME, USB_INIT, _acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove ecm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + } + } + + currentFuncs = funcs; + pre_acm_ecm = _acm_ecm; + return HDF_SUCCESS; + +err: + return HDF_FAILURE; +} + +int32_t UsbdGetFunction() +{ + HDF_LOGI("%{public}s:%{public}d currentFuncs:%{public}d\n", __func__, __LINE__, currentFuncs); + return currentFuncs; +} diff --git a/hdi/service/src/usbd_port.c b/hdi/service/src/usbd_port.c new file mode 100644 index 00000000..1122c345 --- /dev/null +++ b/hdi/service/src/usbd_port.c @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_port.h" +#include "usbd_function.h" +#include "usbd_publisher.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hdf_log.h" +#include "osal_time.h" +#include "securec.h" +#include "sys_param.h" + +#define PORT_MODE_NONE_STR "none" +#define PORT_MODE_HOST_STR "host" +#define PORT_MODE_DEVICE_STR "device" +#define PORT_MODE_OTG_STR "otg" + +#define DEFAULT_PORT_ID 1 + +#define POWER_ROLE_NONE 0 +#define POWER_ROLE_SOURCE 1 +#define POWER_ROLE_SINK 2 + +#define DATA_ROLE_NONE 0 +#define DATA_ROLE_HOST 1 +#define DATA_ROLE_DEVICE 2 + +#define PORT_MODE_NONE 0 +#define PORT_MODE_HOST 1 +#define PORT_MODE_DEVICE 2 + +#define SYS_USB_PORT "sys.usb.port" +#define SYS_USB_FFS_READY "sys.usb.ffs.ready" +#define SYS_USB_CONFIGFS "sys.usb.configfs" +#define SYS_USB_CONFIG "sys.usb.config" +#define HDC_CONFIG_OFF "none" +#define HDC_CONFIG_ON "hdc" + +static int32_t currentPortId = 1; +static int32_t currentPowerRole = 1; +static int32_t currentDataRole = 1; +static int32_t currentMode = 1; + +int SetPort(int portId, int powerRole, int dataRole, struct UsbdService *service) +{ + HDF_LOGE("%{public}s: portId:%{public}d,powerRole:%{public}d,dataRole:%{public}d start", __func__, portId, + powerRole, dataRole); + int ret = 0; + char *fn = "/sys/kernel/debug/usb/100e0000.hidwc3_0/mode"; + int fd = -1; + int len = 0; + int mode = 0; + char *mode_str = NULL; + if (portId != DEFAULT_PORT_ID) { + return -1; + } + if (powerRole < 1 || powerRole >= 3) { + return -1; + } + if (dataRole < 1 || dataRole >= 3) { + return -1; + } + if (powerRole == POWER_ROLE_SOURCE && dataRole == DATA_ROLE_HOST) { + mode = PORT_MODE_HOST; + } + if (powerRole == POWER_ROLE_SINK && dataRole == DATA_ROLE_DEVICE) { + mode = PORT_MODE_DEVICE; + } + if (mode == PORT_MODE_HOST || mode == PORT_MODE_DEVICE) { + switch (mode) { + case PORT_MODE_HOST: + mode_str = PORT_MODE_HOST_STR; + break; + case PORT_MODE_DEVICE: + mode_str = PORT_MODE_DEVICE_STR; + break; + default: + mode_str = PORT_MODE_NONE; + break; + } + } + HDF_LOGE("%{public}s: mode = %{public}d, start", __func__, mode); + if (!mode_str) { + return -1; + } + len = strlen(mode_str); + fd = open(fn, O_WRONLY | O_TRUNC); + if (fd < 0) { + HDF_LOGE("%{public}s: file open error fd= %{public}d", __func__, fd); + return -1; + } + // otg host device + ret = write(fd, mode_str, len); + HDF_LOGE("%{public}s: set mode=%{public}d result:%{public}d len:%{pulibic}d", __func__, mode, ret, len); + if (ret == len) { + ret = 0; + currentPortId = portId; + currentPowerRole = powerRole; + currentDataRole = dataRole; + currentMode = mode; + NotifyUsbPortSubscriber(service->subscriber, currentPortId, currentPowerRole, currentDataRole, currentMode); + } else { + ret = -1; + } + close(fd); + HDF_LOGE("%{public}s: set mode end", __func__); + return 0; +} +static int SetDefaultPort(struct UsbdService *service) +{ + return SetPort(DEFAULT_PORT_ID, POWER_ROLE_SINK, DATA_ROLE_DEVICE, service); +} + +int QueryPort(int *portId, int *powerRole, int *dataRole, int *mode, struct UsbdService *service) +{ + int ret = SetDefaultPort(service); + if (ret) { + return -1; + } + sleep(1); + *portId = currentPortId; + *powerRole = currentPowerRole; + *dataRole = currentDataRole; + *mode = currentMode; + return 0; +} diff --git a/hdi/service/src/usbd_publisher.c b/hdi/service/src/usbd_publisher.c new file mode 100644 index 00000000..a5e589d0 --- /dev/null +++ b/hdi/service/src/usbd_publisher.c @@ -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 "usbd_publisher.h" + +#include "hdf_remote_service.h" +#include "utils/hdf_log.h" + +#define HDF_LOG_TAG usbd_publisher + +void NotifySubscriberDevice(const struct UsbdSubscriber *subscriber, + enum UsbdDeviceAction act, + int32_t busNum, + int32_t devNum) +{ + HDF_LOGD("%{public}s: enter subscriber:%{public}s act:%{public}d bus:%{public}d dev:%{public}d", __func__, + subscriber ? "OK" : "NULL", act, busNum, devNum); + if (subscriber == NULL) { + HDF_LOGD("%{public}s: subscriber is NULL", __func__); + return; + } + int ret; + struct HdfRemoteService *service = subscriber->remoteService; + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC); + struct HdfSBuf *reply = HdfSBufTypedObtain(SBUF_IPC); + if (data == NULL || reply == NULL) { + HDF_LOGE("%{public}s failed to obtain hdf sbuf", __func__); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return; + } + HdfSbufWriteInt32(data, act); + HdfSbufWriteInt32(data, busNum); + HdfSbufWriteInt32(data, devNum); + ret = service->dispatcher->Dispatch(service, CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s failed to notify subscriber, ret: %{public}d", __func__, ret); + } else { + HDF_LOGD("%{public}s: succeed to notify subscriber", __func__); + } + HdfSBufRecycle(data); + HdfSBufRecycle(reply); +} + +void NotifyUsbPortSubscriber(const struct UsbdSubscriber *subscriber, + int32_t portId, + int32_t powerRole, + int32_t dataRole, + int32_t mode) +{ + HDF_LOGD("%{public}s: enter", __func__); + if (subscriber == NULL) { + HDF_LOGD("%{public}s: subscriber is NULL", __func__); + return; + } + int ret; + struct HdfRemoteService *service = subscriber->remoteService; + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC); + struct HdfSBuf *reply = HdfSBufTypedObtain(SBUF_IPC); + if (data == NULL || reply == NULL) { + HDF_LOGE("%{public}s failed to obtain hdf sbuf", __func__); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return; + } + HdfSbufWriteInt32(data, portId); + HdfSbufWriteInt32(data, powerRole); + HdfSbufWriteInt32(data, dataRole); + HdfSbufWriteInt32(data, mode); + + ret = service->dispatcher->Dispatch(service, CMD_NOTIFY_PORT_CHANGED, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s failed to notify subscriber, ret: %{public}d", __func__, ret); + } else { + HDF_LOGD("%{public}s: succeed to notify subscriber", __func__); + } + HdfSBufRecycle(data); + HdfSBufRecycle(reply); +} diff --git a/hdi/test/BUILD.gn b/hdi/test/BUILD.gn new file mode 100644 index 00000000..e3c24a7b --- /dev/null +++ b/hdi/test/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +#################################group######################################### +group("usbd_client_unittest") { + testonly = true + deps = [ "unittest/common:unittest", ] + +} +############################################################################### \ No newline at end of file diff --git a/hdi/test/unittest/common/BUILD.gn b/hdi/test/unittest/common/BUILD.gn new file mode 100644 index 00000000..41444c24 --- /dev/null +++ b/hdi/test/unittest/common/BUILD.gn @@ -0,0 +1,294 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +module_output_path = "usb_manager_native/usbd_client_test" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//base/usb/usb_manager/hdi/client/include", + ] +} + +##############################unittest##########################################= + +ohos_unittest("test_config") { + module_out_path = module_output_path + sources = [ + "src/usbd_config_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_transfer") { + module_out_path = module_output_path + sources = [ + "src/usbd_transfer_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_descriptor") { + module_out_path = module_output_path + sources = [ + "src/usbd_descriptor_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_device") { + module_out_path = module_output_path + sources = [ + "src/usbd_device_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_function") { + module_out_path = module_output_path + sources = [ + "src/usbd_function_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_interface") { + module_out_path = module_output_path + sources = [ + "src/usbd_interface_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_port") { + module_out_path = module_output_path + sources = [ + "src/usbd_port_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_request") { + module_out_path = module_output_path + sources = [ + "src/usbd_request_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +############################################################################### +group("unittest") { + testonly = true + deps = [ + ":test_config", + ":test_descriptor", + ":test_device", + ":test_function", + ":test_interface", + ":test_port", + ":test_request", + ":test_transfer", + ] +} +############################################################################### \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_config_test.h b/hdi/test/unittest/common/include/usbd_config_test.h new file mode 100644 index 00000000..08e8a996 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_config_test.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 USBD_CONFIG_TEST_H +#define USBD_CONFIG_TEST_H + +#include + +class UsbdConfigTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_CONFIG_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_descriptor_test.h b/hdi/test/unittest/common/include/usbd_descriptor_test.h new file mode 100644 index 00000000..55a0e59e --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_descriptor_test.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 USBD_DESCRIPTOR_TEST_H +#define USBD_DESCRIPTOR_TEST_H + +#include + +class UsbdDescriptorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_DESCRIPTOR_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_device_test.h b/hdi/test/unittest/common/include/usbd_device_test.h new file mode 100644 index 00000000..3418d0d8 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_device_test.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 USBD_DEVICE_TEST_H +#define USBD_DEVICE_TEST_H + +#include + +class UsbdDeviceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_DEVICE_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_function_test.h b/hdi/test/unittest/common/include/usbd_function_test.h new file mode 100644 index 00000000..97e460b8 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_function_test.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 USBD_FUNCTION_TEST_H +#define USBD_FUNCTION_TEST_H + +#include + +class UsbdFunctionTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_FUNCTION_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_interface_test.h b/hdi/test/unittest/common/include/usbd_interface_test.h new file mode 100644 index 00000000..e0fbd8ff --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_interface_test.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 USBD_INTERFACE_TEST_H +#define USBD_INTERFACE_TEST_H + +#include + +class UsbdInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_INTERFACE_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_port_test.h b/hdi/test/unittest/common/include/usbd_port_test.h new file mode 100644 index 00000000..9ac29dfc --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_port_test.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 USBD_PORT_TEST_H +#define USBD_PORT_TEST_H + +#include + +class UsbdPortTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_PORT_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_request_test.h b/hdi/test/unittest/common/include/usbd_request_test.h new file mode 100644 index 00000000..f20324c6 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_request_test.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 USBD_REQUEST_TEST_H +#define USBD_REQUEST_TEST_H + +#include + +class UsbdRequestTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_REQUEST_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_transfer_test.h b/hdi/test/unittest/common/include/usbd_transfer_test.h new file mode 100644 index 00000000..3947520f --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_transfer_test.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 USBD_TRANSFER_TEST_H +#define USBD_TRANSFER_TEST_H + +#include + +class UsbdTransferTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_TRANSFER_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_config_test.cpp b/hdi/test/unittest/common/src/usbd_config_test.cpp new file mode 100644 index 00000000..795fba6b --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_config_test.cpp @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_config_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +UsbDevice device; +void UsbdConfigTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdConfigTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d GetDevices=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d GetBusNum=%{public}d GetDevAddr=%{public}d", __LINE__, + device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + USBDevicePipe pipe; + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d GetBusNum=%{public}d GetDevAddr=%{public}d", __LINE__, + pipe.GetBusNum(), pipe.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdConfigTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdConfigTest-----------"); +} + +void UsbdConfigTest::SetUp(void) {} + +void UsbdConfigTest::TearDown(void) {} + +/** + * @tc.name: UsbdConfig001 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig001 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdConfigTest::UsbdSetConfigConfig001 %{public}d GetBusNum=%{public}d GetDevAddr=%{public}d", __LINE__, + device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfigConfig001 %{public}d config.GetId=%{public}d", + __LINE__, configIndex); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfigConfig001 %{public}d SetConfig=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig001 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig002 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetConfig002 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig002 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig002 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig003 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig003 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig003 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig003 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig004 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig004 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig004 %{public}d SetConfig=%{public}d", __LINE__, ret); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig004 %{public}d configIndex=%{public}d", __LINE__, + configIndex); + ASSERT_TRUE(ret == ERR_OK); + configIndex = device.GetConfigs().front().GetId(); + ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig004 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig005 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig005 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig005 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig005 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig006 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig006 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig006 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig006 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig007 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:devAddr、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig007 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig007 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig007 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig008 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:busNum、devAddr、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig008 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig008 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig008 : SetConfig-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdConfig011 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig001 : GetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig001 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig001 : GetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig012 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig002 : GetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig002 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig002 : GetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig013 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig003 : GetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig003 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig003 : GetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig014 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig004 : GetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig004 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig004 : GetConfig-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_descriptor_test.cpp b/hdi/test/unittest/common/src/usbd_descriptor_test.cpp new file mode 100644 index 00000000..1b6c3676 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_descriptor_test.cpp @@ -0,0 +1,680 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_descriptor_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +UsbDevice device; +void UsbdDescriptorTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdDescriptorTest-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "device list NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + USBDevicePipe pipe; + device = deviceList.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdDescriptorTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdDescriptorTest-----------"); +} + +void UsbdDescriptorTest::SetUp(void) {} + +void UsbdDescriptorTest::TearDown(void) {} + +/** + * @tc.name: UsbdDescriptor001 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor001 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor001 %{public}d ret=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor001 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("设备描述符", buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor001 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor002 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor002 : GetDeviceDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor002 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor002 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor003 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor003 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 233; + uint8_t buffer[255] = {}; + uint32_t length = 255; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor003 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor003 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor004 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor004 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor004 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("设备描述符", buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor004 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor005 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor005 : GetDeviceDescriptor-----------"); + uint8_t busNum = 99; + uint8_t devAddr = 99; + uint8_t buffer[255] = {}; + uint32_t length = 255; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor005 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor005 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor006 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,busNum、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor006 : GetDeviceDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor006 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor006 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor007 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor007 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t buffer[] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor007 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor007 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor008 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:busNum、devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor008 : GetDeviceDescriptor-----------"); + uint8_t busNum = 233; + uint8_t devAddr = 234; + uint8_t buffer[] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor008 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor008 : GetDeviceDescriptor-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdDescriptor001 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor001 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 0; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor001 %{public}d ret=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor001 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor001 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor002 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor002 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor002 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor002 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor003 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor003 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 222; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor003 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor003 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor004 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor004 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor004 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor004 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor005 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor005 : GetStringDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor005 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor005 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor006 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor006 : GetStringDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 0; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor006 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor006 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor007 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor007 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t stringId = 233; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor007 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor007 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor008 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:busNum、devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor008 : GetStringDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t stringId = 222; + uint8_t buffer[10] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor008 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor008 : GetStringDescriptor-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdDescriptor001 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor001 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = 0; + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor001 %{public}d ret=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor001 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("配置描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor001 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor002 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor002 : GetConfigDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor002 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor002 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor003 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor003 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor003 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor003 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor004 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,configId + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor004 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = 1; + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor004 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("配置描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor004 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor005 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor005 : GetConfigDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor005 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor005 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor006 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor006 : GetConfigDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor006 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor006 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor007 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor007 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 1; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor007 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor007 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor008 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:busNum、devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor008 : GetConfigDescriptor-----------"); + uint8_t busNum = 255; + uint8_t devAddr = 222; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[] = {0}; + uint32_t length = 0; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor008 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor008 : GetConfigDescriptor-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_device_test.cpp b/hdi/test/unittest/common/src/usbd_device_test.cpp new file mode 100644 index 00000000..5040699f --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_device_test.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_device_test.h" +#include +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "delayed_sp_singleton.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +vector deviceList; + +UsbDevice device; + +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +void UsbdDeviceTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdDeviceTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Get DeviceList OK, result = %{public}d", __LINE__, + ret); + ASSERT_TRUE(!(deviceList.empty())) << "DeviceList NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d DeviceList size=%{public}d", __LINE__, + deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); +} + +void UsbdDeviceTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdDeviceTest-----------"); +} + +void UsbdDeviceTest::SetUp(void) {} + +void UsbdDeviceTest::TearDown(void) {} + +/** + * @tc.name: UsbdDevice001 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice001 : OpenDevice-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDeviceTest:: Line:%{public}d OpenDevice GetBusNum =%{public}d GetDevAddr =%{public}d", __LINE__, + device.GetBusNum(), device.GetDevAddr()); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result =%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice001 : OpenDevice-----------"); +} + +/** + * @tc.name: UsbdDevice002 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice002 : OpenDevice-----------"); + uint8_t busNum = 255; + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice002 : OpenDevice-----------"); +} + +/** + * @tc.name: UsbdDevice003 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice003 : OpenDevice-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 255; + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice003 : OpenDevice-----------"); +} + +/** + * @tc.name: UsbdDevice004 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice004 : OpenDevice-----------"); + uint8_t busNum = 255; + uint8_t devAddr = 255; + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice004 : OpenDevice-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdDevice011 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice001 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice001 : Close-----------"); +} + +/** + * @tc.name: UsbdDevice012 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice002 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice002 : Close-----------"); +} + +/** + * @tc.name: UsbdDevice013 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice003 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 255; + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice003 : Close-----------"); +} + +/** + * @tc.name: UsbdDevice014 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice004 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + devAddr = 255; + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice004 : Close-----------"); +} \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_function_test.cpp b/hdi/test/unittest/common/src/usbd_function_test.cpp new file mode 100644 index 00000000..fc9abbbc --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_function_test.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_function_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +void UsbdFunctionTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdFunctionTest-----------"); +} + +void UsbdFunctionTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdFunctionTest-----------"); +} + +void UsbdFunctionTest::SetUp(void) {} + +void UsbdFunctionTest::TearDown(void) {} + +/** + * @tc.name: UsbdGetCurrentFunctions001 + * @tc.desc: Test functions to GetCurrentFunctions + * @tc.desc: int32_t GetCurrentFunctions() + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdGetCurrentFunctions001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction001 : GetCurrentFunctions-----------"); + int32_t funcs = 0; + auto ret = UsbdClient::GetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdGetCurrentFunctions001 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction001 : GetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdGetCurrentFunctions002 + * @tc.desc: Test functions to GetCurrentFunctions + * @tc.desc: int32_t GetCurrentFunctions() + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdGetCurrentFunctions002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction002 : GetCurrentFunctions-----------"); + auto ret = UsbdClient::SetCurrentFunctions(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction011 %{public}d SetCurrentFunctions=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + int32_t funcs = 255; + ret = UsbdClient::GetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction002 : GetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions001 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction001 : SetCurrentFunctions-----------"); + int32_t funcs = 1; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdFunctionTest::UsbdSetCurrentFunctions001 %{public}d SetCurrentFunctions=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction001 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions002 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 反向测试:参数异常,funcs错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction002 : SetCurrentFunctions-----------"); + int32_t funcs = -1; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction012 %{public}d ret=%{public}d", __LINE__, ret); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction012 %{public}d funcs=%{public}d", __LINE__, funcs); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction002 : SetCurrentFunctions-----------"); +} +/** + * @tc.name: UsbdSetCurrentFunctions003 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction003 : SetCurrentFunctions-----------"); + int32_t funcs = 2; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction003 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions004 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction004 : SetCurrentFunctions-----------"); + int32_t funcs = 3; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction004 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions005 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction005 : SetCurrentFunctions-----------"); + int32_t funcs = 4; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction005 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions006 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction006 : SetCurrentFunctions-----------"); + int32_t funcs = 5; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction006 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions007 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction007 : SetCurrentFunctions-----------"); + int32_t funcs = 6; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction007 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions008 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 反向测试:参数异常,funcs错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction008 : SetCurrentFunctions-----------"); + int32_t funcs = 8; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction008 : SetCurrentFunctions-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_interface_test.cpp b/hdi/test/unittest/common/src/usbd_interface_test.cpp new file mode 100644 index 00000000..0018c805 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_interface_test.cpp @@ -0,0 +1,643 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_interface_test.h" +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "delayed_sp_singleton.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); +UsbDevice device; +UsbInterface interface; + +void UsbdInterfaceTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdDeviceTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + USBDevicePipe pipe; + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); +} + +void UsbdInterfaceTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdInterfaceTest-----------"); +} + +void UsbdInterfaceTest::SetUp(void) {} + +void UsbdInterfaceTest::TearDown(void) {} + +/** + * @tc.name: UsbdClaimInterface001 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface001 : ClaimInterface-----------"); + + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface001 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface002 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface002 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 20; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface002 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface003 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface003 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface003 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface004 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface004 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface004 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface005 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface005 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + devAddr = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface005 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface006 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface006 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface006 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface007 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface007 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 255; + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface007 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface008 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface008 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + devAddr = 255; + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface008 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface001 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface001 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface001 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface001 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface002 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface002 : ReleaseInterface-----------"); + uint8_t busNum = 25; + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface002 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface003 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface003 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 25; + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface003 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface004 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface004 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface004 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface005 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface005 : ReleaseInterface-----------"); + uint8_t busNum = 25; + uint8_t devAddr = 25; + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface005 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface006 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface006 : ReleaseInterface-----------"); + uint8_t busNum = 255; + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface006 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface007 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface007 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 255; + int32_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface007 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface008 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface008 : ReleaseInterface-----------"); + uint8_t busNum = 255; + uint8_t devAddr = 255; + int32_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface008 : ReleaseInterface-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdSetInterface001 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface001 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface001 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface001 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface002 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface002 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + ; + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface002 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 222; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface002 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface003 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface003 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface003 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + devAddr = 222; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface003 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface004 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface004 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = 222; + uint8_t altIndex = 222; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface004 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface004 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface005 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface005 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface005 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 233; + devAddr = 233; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface005 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface006 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface006 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 224; + uint8_t altIndex = 1; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface006 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 224; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface006 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface007 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface007 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 225; + uint8_t altIndex = 225; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface007 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + devAddr = 225; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface007 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface008 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface008 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 225; + uint8_t altIndex = 225; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface008 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 225; + devAddr = 225; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface008 : SetInterface-----------"); +} \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_port_test.cpp b/hdi/test/unittest/common/src/usbd_port_test.cpp new file mode 100644 index 00000000..1bed0fc3 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_port_test.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_port_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_port.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +void UsbdPortTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdPortTest-----------"); +} + +void UsbdPortTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdPortTest-----------"); +} + +void UsbdPortTest::SetUp(void) {} + +void UsbdPortTest::TearDown(void) {} + +/** + * @tc.name: UsbdSetPortRole001 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole001 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole001 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole002 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,portId错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole002 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(2, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole002 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole003 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,powerRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole003 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 4, 2); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole003 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole004 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole004 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 1, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole004 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole005 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,portId、powerRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole005 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 5, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole005 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole006 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,portId、dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole006 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(5, 1, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole006 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole007 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:powerRole、dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole007 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 5, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole007 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole008 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:portId、powerRole、dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole008 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(2, 5, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole008 : SetPortRole-----------"); +} + +/** + * @tc.name: SetPortRole09 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, SetPortRole09, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole009 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 2, 2); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::SetPortRole09 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole009 : SetPortRole-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_request_test.cpp b/hdi/test/unittest/common/src/usbd_request_test.cpp new file mode 100644 index 00000000..b997377a --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_request_test.cpp @@ -0,0 +1,1091 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_request_test.h" +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "delayed_sp_singleton.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_request.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +UsbDevice device; + +void UsbdRequestTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdRequestTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d GetDevices=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + USBDevicePipe pipe; + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdRequestTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdRequestTest-----------"); +} + +void UsbdRequestTest::SetUp(void) {} + +void UsbdRequestTest::TearDown(void) {} + +/** + * @tc.name: UsbdRequest001 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest001 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue001 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest001 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest002 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + devAddr = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue002 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue002 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest003 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest003 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint8_t pointid = point.GetAddress(); + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + devAddr = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue003 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue003 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest003 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest004 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest004 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t length = 255; + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + interfaceid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue004 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue004 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest004 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest005 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest005 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + devAddr = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue005 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest005 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest006 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、interfaceId错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest006 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + interfaceid = 222; + pointid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue006 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest006 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest007 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 正向测试 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest007 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request 007"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue007 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue007 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue007 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqparams.clientData, reqparams.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqparams.buffer, reqparams.length); + + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest007 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest008 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:interfaceId错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest008 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "reuquest008"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue008 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue008 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + interfaceid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue008 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest008 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest009 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:interfaceId、poinid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest009 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request 009"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue009 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue009 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue009 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + interfaceid = 222; + pointid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue009 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest009 : RequestQueue-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdRequest001 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest001 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest001 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest002 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 222; + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest002 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest003 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest003 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 222; + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest003 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest004 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:timeout错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest004 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, -500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest004 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest005 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest005 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + length = 0; + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest005 : RequestWait-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdRequest001 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest001 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request001"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest001 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest002 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request002"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest002 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest003 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest003 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request003"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest003 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest004 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,interfaceid错误 结果正常??? + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest004 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request004"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + interfaceid = 222; + pointid = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest004 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest005 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 正向测试 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest005 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request005"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest005 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest006 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest006 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request006"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestCancel006 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 224; + interfaceid = 224; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest006 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest007 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest007 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request007"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestCancel007 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 224; + interfaceid = 224; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest007 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest008 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest008 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request008"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestCancel008 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 222; + devAddr = 222; + interfaceid = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest008 : RequestCancel-----------"); +} \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_transfer_test.cpp b/hdi/test/unittest/common/src/usbd_transfer_test.cpp new file mode 100644 index 00000000..7ca6e544 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_transfer_test.cpp @@ -0,0 +1,824 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_transfer_test.h" +#include +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" +#include "usbd_config_test.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +// OHOS::USB::CtrlTransferParamsParams ctrlparmas; +// OHOS::USB::TransferParams trsparamas; +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +UsbDevice device; + +void UsbdTransferTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdTransferTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d GetDevices=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + USBDevicePipe pipe; + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdTransferTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdTransferTest-----------"); +} + +void UsbdTransferTest::SetUp(void) {} + +void UsbdTransferTest::TearDown(void) {} + +/** + * @tc.name: UsbdControlTransfer001 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer001 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + const USBConfig &config = device.GetConfigs().front(); + uint8_t configId = config.GetId(); + uint32_t length = 255; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 8, 0, 0, &configId, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer001 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer001 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer002 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer002 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer002 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer002 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer003 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer003 : ControlTransfer-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + int32_t intercafeidex = interface.GetId(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t *buffer = (uint8_t *)interface.GetAlternateSetting(); + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0X0A, .0, intercafeidex, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer003 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer003 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer004 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer004 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer004 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer004 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer005 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer005 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer005 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer005 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer006 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer006 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer006 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer006 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer007 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer007 : ControlTransfer-----------"); + int idex = device.GetConfigs().front().GetInterfaces().front().GetEndpoints().front().GetEndpointNumber(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer007 %{public}d idex=%{public}d", __LINE__, + idex); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000010, 0X0C, 0, idex, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer007 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer007 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer008 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer008 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0XFFFF, 1, 1, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdControlTransfer008 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer008 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer009 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer009 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + const USBConfig &config = device.GetConfigs().front(); + uint8_t configId = config.GetId(); + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 0X0F, 0, 0, &configId, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer009 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer009 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer010 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer010 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 11, 0X7FFFFFFF, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer010 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer010 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer011 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer011, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer011 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 7, 0, 0b11111111, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer011 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer011 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer012 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer012, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer012 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t *buffer = nullptr; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 7, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer012 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer012: ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer013 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer013, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer013 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 0; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 7, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer013 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer013 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer014 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer014, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer014 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, -1}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer014 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer014 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer015 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer015, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer015 : ControlTransfer-----------"); + uint8_t busNum = 255; + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer015 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer015 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer016 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer016, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer016 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 255; + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer016 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer016 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead001 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead001 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + uint8_t buffer[255] = {}; + uint32_t length = 8; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead001 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead001 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead002 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead002 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead002 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + busNum = 222; + uint32_t length = 100; + uint8_t buffer[100] = {0}; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead002 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead002 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead003 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead003 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead003 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead003 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + devAddr = 244; + uint32_t length = 100; + uint8_t buffer[100] = {0}; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead003 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead003 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead004 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead004 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead004 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead004 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + interfaceid = 244; + uint8_t *buffer = nullptr; + uint32_t length = 100; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead004 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead004 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead005 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead005 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead005 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead005 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 0; + uint8_t buffer[100] = {}; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead005 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead005 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite001 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite001 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite001 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite001 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ01"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite001 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite001 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite002 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite002 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite002 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite002 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + interfaceid = 99; + busNum = 99; + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ02"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite002 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite002 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite003 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite003 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite003 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite003 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + devAddr = 244; + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ03"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite003 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite003 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite004 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite004 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite004 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite004 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + interfaceid = 255; + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ04"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite004 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite004 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite005 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite005 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite005 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = 255; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite005 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ05"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite005 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite005 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite006 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite006 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite006 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite006 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + devAddr = 99; + uint32_t length = 100; + uint8_t *buffer = nullptr; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite006 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite006 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite007 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite007 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite007 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = 99; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite007 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 0; + uint8_t buffer[100] = "hello world bulk writ07"; + UsbRequest request; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite007 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite007 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite008 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite008 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite008 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite008 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ08"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, -1}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite008 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite008 : BulkTransferWrite-----------"); +} diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn new file mode 100644 index 00000000..10c4be72 --- /dev/null +++ b/interfaces/innerkits/BUILD.gn @@ -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. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("usbsrv_private_config") { + include_dirs = [ + "${usb_manager_path}/services/zidl/include", + "//utils/system/safwk/native/include", + ] +} + +config("usbsrv_public_config") { + include_dirs = [ "native/include" ] +} + +ohos_shared_library("usbsrv_client") { + sources = [ + "${usb_manager_path}/services/zidl/src/usb_srv_proxy.cpp", + "native/src/usb_srv_client.cpp", + "native/src/usb_device.cpp", + "native/src/usb_device_pipe.cpp", + "native/src/usb_request.cpp", + ] + + configs = [ + "${utils_path}:utils_config", + ":usbsrv_private_config", + ":usbsrv_public_config", + ] + + public_configs = [ ":usbsrv_public_config" ] + + deps = [ "//utils/native/base:utils" ] + + external_deps = [ + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + part_name = "usb_manager_native" +} diff --git a/interfaces/innerkits/native/include/iusb_srv.h b/interfaces/innerkits/native/include/iusb_srv.h new file mode 100644 index 00000000..ac71a1db --- /dev/null +++ b/interfaces/innerkits/native/include/iusb_srv.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_INNERKITS_IUSB_SRV_H +#define USBMGR_INNERKITS_IUSB_SRV_H + +#include +#include +#include "iremote_broker.h" +#include "iremote_object.h" +#include "usb_device.h" +#include "usb_info.h" +#include "usb_port.h" + +namespace OHOS { +namespace USB { + +class IUsbSrv : public IRemoteBroker { +public: + enum { + USB_FUN_HAS_RIGHT = 0, + USB_FUN_REQUEST_RIGHT, + USB_FUN_OPEN_DEVICE, + USB_FUN_GET_DEVICE, + USB_FUN_GET_DEVICES, + USB_FUN_GET_CURRENT_FUNCTIONS, + USB_FUN_SET_CURRENT_FUNCTIONS, + USB_FUN_USB_FUNCTIONS_FROM_STRING, + USB_FUN_USB_FUNCTIONS_TO_STRING, + USB_FUN_CLAIM_INTERFACE, + USB_FUN_RELEASE_INTERFACE, + USB_FUN_BULK_TRANSFER_READ, + USB_FUN_BULK_TRANSFER_WRITE, + USB_FUN_CONTROL_TRANSFER, + USB_FUN_SET_ACTIVE_CONFIG, + USB_FUN_GET_ACTIVE_CONFIG, + USB_FUN_SET_INTERFACE, + USB_FUN_GET_PORTS, + USB_FUN_GET_SUPPORTED_MODES, + USB_FUN_SET_PORT_ROLE, + USB_FUN_REQUEST_QUEUE, + USB_FUN_REQUEST_WAIT, + USB_FUN_REQUEST_CANCEL, + USB_FUN_GET_DESCRIPTOR, + USB_FUN_CLOSE_DEVICE, + }; + + virtual int32_t OpenDevice(uint8_t busNum, uint8_t devAddr) = 0; + virtual int32_t HasRight(std::string deviceName) = 0; + virtual int32_t RequestRight(std::string deviceName) = 0; + virtual int32_t GetDevices(std::vector &deviceList) = 0; + virtual int32_t GetCurrentFunctions(int32_t &funcs) = 0; + virtual int32_t SetCurrentFunctions(int32_t funcs) = 0; + virtual int32_t UsbFunctionsFromString(std::string funcs) = 0; + virtual std::string UsbFunctionsToString(int32_t funcs) = 0; + virtual int32_t GetPorts(std::vector &ports) = 0; + virtual int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes) = 0; + virtual int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) = 0; + virtual int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) = 0; + virtual int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) = 0; + virtual int32_t BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpointid, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) = 0; + virtual int32_t BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpointid, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) = 0; + virtual int32_t ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) = 0; + virtual int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configId) = 0; + virtual int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configId) = 0; + virtual int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) = 0; + virtual int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) = 0; + virtual int32_t RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientData, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) = 0; + virtual int32_t RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) = 0; + virtual int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) = 0; + virtual int32_t Close(uint8_t busNum, uint8_t devAddr) = 0; + +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.usb.IUsbSrv"); +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_INNERKITS_IUSB_SRV_H diff --git a/interfaces/innerkits/native/include/usb_config.h b/interfaces/innerkits/native/include/usb_config.h new file mode 100644 index 00000000..fce40039 --- /dev/null +++ b/interfaces/innerkits/native/include/usb_config.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_CONFIG_H +#define USB_CONFIG_H + +#include +#include +#include +#include +#include +#include "usb_common.h" +#include "usb_interface.h" + +namespace OHOS { +namespace USB { +class USBConfig { +public: + USBConfig(uint32_t id, + uint32_t attributes, + std::string name, + uint32_t maxPower, + std::vector interfaces) + { + this->id = id; + this->attributes = attributes; + this->maxPower = maxPower; + this->name = name; + this->interfaces = interfaces; + } + USBConfig() {} + + const int32_t &GetId() const + { + return id; + } + + const int32_t &GetAttributes() const + { + return attributes; + } + + bool GetInterface(uint32_t index, UsbInterface &interface) const + { + if (index >= interfaces.size()) { + return false; + } + interface = interfaces[index]; + return true; + } + + int32_t GetInterfaceCount() const + { + return interfaces.size(); + } + + int32_t GetMaxPower() const + { + return maxPower * 2; + } + + const std::string &GetName() const + { + return name; + } + + bool IsRemoteWakeup() const + { + return (attributes & USB_CFG_REMOTE_WAKEUP) != 0; + } + + bool IsSelfPowered() const + { + return (attributes & USB_CFG_SELF_POWERED) != 0; + } + + void SetInterfaces(const std::vector &interfaces) + { + this->interfaces = interfaces; + } + std::vector &GetInterfaces() + { + return interfaces; + } + void SetId(int32_t id) + { + this->id = id; + } + void SetAttribute(int32_t attributes) + { + this->attributes = attributes; + } + void SetMaxPower(int32_t maxPower) + { + this->maxPower = maxPower; + } + std::string ToString() const + { + std::string str; + std::ostringstream ss; + ss << "name=" << name << "," + << "id=" << id << "," + << "iConfiguration=" << (int32_t)iConfiguration << "," + << "attributes=" << attributes << "," + << "maxPower=" << maxPower << "; "; + str = ss.str(); + ss.str(""); + for (size_t i = 0; i < interfaces.size(); ++i) { + const UsbInterface &interface = interfaces[i]; + str += interface.ToString(); + } + return str; + } + void SetName(std::string Name) + { + this->name = Name; + } + void SetiConfiguration(uint8_t idx) + { + this->iConfiguration = idx; + } + uint8_t GetiConfiguration() + { + return this->iConfiguration; + } + +private: + int32_t id = INVALID_USB_INT_VALUE; + int32_t attributes = INVALID_USB_INT_VALUE; + std::vector interfaces; + int32_t maxPower = INVALID_USB_INT_VALUE; + std::string name; + uint8_t iConfiguration; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_CONFIG_H diff --git a/interfaces/innerkits/native/include/usb_device.h b/interfaces/innerkits/native/include/usb_device.h new file mode 100644 index 00000000..6d7b8e5c --- /dev/null +++ b/interfaces/innerkits/native/include/usb_device.h @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_DEVICE_H +#define USB_DEVICE_H + +#include +#include +#include +#include +#include "iremote_object.h" +#include "usb_config.h" +#include "usb_interface.h" + +namespace OHOS { +namespace USB { +class UsbDevice { +public: + UsbDevice(std::string mName, + std::string mManufacturerName, + std::string mProductName, + std::string mVersion, + uint8_t devAddr, + uint8_t busNum, + int mVendorId, + int mProductId, + int mClass, + int mSubclass, + int mProtocol, + std::vector configs) + { + this->mName = mName; + this->mManufacturerName = mManufacturerName; + this->mProductName = mProductName; + this->mVersion = mVersion; + this->devAddr = devAddr; + this->busNum = busNum; + this->mVendorId = mVendorId; + this->mProductId = mProductId; + this->mClass = mClass; + this->mSubclass = mSubclass; + this->mProtocol = mProtocol; + this->configs = configs; + } + UsbDevice() {} + const std::string &GetName() const + { + return mName; + } + const std::string &GetManufacturerName() const + { + return mManufacturerName; + } + const std::string &GetProductName() const + { + return mProductName; + } + const std::string &GetVersion() const + { + return mVersion; + } + int32_t GetVendorId() const + { + return mVendorId; + } + int32_t GetProductId() const + { + return mProductId; + } + int32_t GetClass() const + { + return mClass; + } + int32_t GetSubclass() const + { + return mSubclass; + } + int32_t GetProtocol() const + { + return mProtocol; + } + int32_t GetConfigCount() const + { + return configs.size(); + } + int32_t GetConfig(uint32_t index, USBConfig &config) const + { + if (index >= configs.size()) { + return ERR_INVALID_VALUE; + } + config = configs[index]; + return ERR_OK; + } + void SetConfigs(const std::vector &configs) + { + this->configs = configs; + } + + uint8_t GetDevAddr() const + { + return devAddr; + } + uint8_t GetBusNum() const + { + return busNum; + } + bool GetDescConfigCount() + { + return descConfigCount; + } + + void SetDevAddr(uint8_t Num) + { + devAddr = Num; + } + void SetBusNum(uint8_t Num) + { + busNum = Num; + } + void SetName(std::string Name) + { + mName = Name; + } + void SetManufacturerName(std::string Name) + { + mManufacturerName = Name; + } + void SetProductName(std::string Name) + { + mProductName = Name; + } + void SetVersion(std::string Name) + { + mVersion = Name; + } + void SetVendorId(int Id) + { + mVendorId = Id; + } + void SetProductId(int Id) + { + mProductId = Id; + } + void SetClass(int Id) + { + mClass = Id; + } + void SetSubclass(int Id) + { + mSubclass = Id; + } + void SetProtocol(int Id) + { + mProtocol = Id; + } + void SetDescConfigCount(uint8_t count) + { + descConfigCount = count; + } + + std::vector &GetConfigs() + { + return configs; + } + + std::string ToString() const + { + std::string str; + std::ostringstream ss; + ss << "mName=" << mName << "," + << "mManufacturerName=" << mManufacturerName << "," + << "mProductName=" << mProductName << "," + << "mVersion=" << mVersion << "," + << "mSerial=" << mSerial << "," + << "busNum=" << (int32_t)busNum << "," + << "devAddr=" << (int32_t)devAddr << "," + << "mVendorId=" << mVendorId << "," + << "mProductId=" << mProductId << "," + << "mClass=" << mClass << "," + << "mSubclass=" << mSubclass << "," + << "mProtocol=" << mProtocol << "; "; + str = ss.str(); + ss.str(""); + std::string strConfigs; + for (size_t i = 0; i < configs.size(); ++i) { + const USBConfig &config = configs[i]; + strConfigs += config.ToString(); + } + str += strConfigs; + return str; + } + + void SetiManufacturer(uint8_t idx) + { + this->iManufacturer = idx; + } + uint8_t GetiManufacturer() + { + return this->iManufacturer; + } + void SetiProduct(uint8_t idx) + { + this->iProduct = idx; + } + uint8_t GetiProduct() + { + return this->iProduct; + } + void SetiSerialNumber(uint8_t idx) + { + this->iSerialNumber = idx; + } + uint8_t GetiSerialNumber() + { + return this->iSerialNumber; + } + void SetmSerial(std::string Name) + { + this->mSerial = Name; + } + std::string GetmSerial() + { + return this->mSerial; + } + void SetbMaxPacketSize0(uint8_t val) + { + this->bMaxPacketSize0 = val; + } + uint8_t GetbMaxPacketSize0() + { + return this->bMaxPacketSize0; + } + void SetbcdUSB(uint16_t val) + { + this->bcdUSB = val; + } + uint16_t GetbcdUSB() + { + return this->bcdUSB; + } + void SetbcdDevice(uint16_t val) + { + this->bcdDevice = val; + } + uint16_t GetbcdDevice() + { + return this->bcdDevice; + } + +private: + std::string mName; + std::string mManufacturerName; + std::string mProductName; + std::string mVersion; + std::string mSerial; + uint8_t devAddr; + uint8_t busNum; + uint8_t descConfigCount; + + uint8_t bMaxPacketSize0; + uint16_t bcdUSB; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + + int mVendorId; + int mProductId; + int mClass; + int mSubclass; + int mProtocol; + std::vector configs; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_DEVICE_H diff --git a/interfaces/innerkits/native/include/usb_device_pipe.h b/interfaces/innerkits/native/include/usb_device_pipe.h new file mode 100644 index 00000000..4aaf5fd3 --- /dev/null +++ b/interfaces/innerkits/native/include/usb_device_pipe.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_PIPE_H +#define USB_PIPE_H + +#include +#include +#include "iremote_object.h" +#include "iusb_srv.h" + +namespace OHOS { +namespace USB { +class USBDevicePipe { +public: + USBDevicePipe(); + USBDevicePipe(uint8_t busNum, uint8_t devAddr); + int32_t ClaimInterface(const UsbInterface &interface, bool force); + int32_t ReleaseInterface(const UsbInterface &interface); + int32_t BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t timeout); + int32_t ControlTransfer(int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout); + int32_t SetConfiguration(const USBConfig &config); + int32_t SetInterface(const UsbInterface &interface); + int32_t Close(); + + void SetBusNum(uint8_t busNum); + void SetDevAddr(uint8_t devAddr); + uint8_t GetBusNum() const; + uint8_t GetDevAddr() const; + +private: + uint8_t busNum; + uint8_t devAddr; + void *usbClient; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_PIPE_H diff --git a/interfaces/innerkits/native/include/usb_endpoint.h b/interfaces/innerkits/native/include/usb_endpoint.h new file mode 100644 index 00000000..b63d3be5 --- /dev/null +++ b/interfaces/innerkits/native/include/usb_endpoint.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_ENDPOINT_H +#define USB_ENDPOINT_H + +#include +#include +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { +class USBEndpoint { +public: + USBEndpoint(uint32_t address, uint32_t attributes, uint32_t interval, uint32_t maxPacketSize) + { + this->address = address; + this->attributes = attributes; + this->interval = interval; + this->maxPacketSize = maxPacketSize; + } + USBEndpoint() {} + + uint8_t GetNumber() const + { + return address & USB_ENDPOINT_NUMBER_MASK; + } + const int32_t &GetAddress() const + { + return address; + } + + int32_t GetDirection() const + { + return address & USB_ENDPOINT_DIR_MASK; + } + + const int32_t &GetAttributes() const + { + return attributes; + } + + int32_t GetEndpointNumber() const + { + return address & USB_ENDPOINT_NUMBER_MASK; + } + + const int32_t &GetInterval() const + { + return interval; + } + + const int32_t &GetMaxPacketSize() const + { + return maxPacketSize; + } + + int32_t GetType() const + { + return (attributes & USB_ENDPOINT_XFERTYPE_MASK); + } + + std::string ToString() const + { + std::string ret = "USBEndpoint:[Address:"; + ret.append(std::to_string(address)) + .append(", Direction:") + .append(std::to_string(GetDirection())) + .append(", Attributes:") + .append(std::to_string(attributes)) + .append(", EndpointNumber:") + .append(std::to_string(GetEndpointNumber())) + .append(", Interval:") + .append(std::to_string(interval)) + .append(", MaxPacketSize:") + .append(std::to_string(maxPacketSize)) + .append(", Type:") + .append(std::to_string(GetType())) + .append("]"); + return ret; + } + void SetAddr(int32_t val) + { + address = val; + } + void SetAttr(int32_t val) + { + attributes = val; + } + void SetInterval(int32_t val) + { + interval = val; + } + void SetMaxPacketSize(int32_t val) + { + maxPacketSize = val; + } + void SetInterfaceId(uint8_t interfaceId) + { + this->interfaceId = interfaceId; + } + int8_t GetInterfaceId() const + { + return interfaceId; + } + +private: + int32_t address = INVALID_USB_INT_VALUE; + int32_t attributes = INVALID_USB_INT_VALUE; + int32_t interval = INVALID_USB_INT_VALUE; + int32_t maxPacketSize = INVALID_USB_INT_VALUE; + uint8_t interfaceId; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_ENDPOINT_H diff --git a/interfaces/innerkits/native/include/usb_info.h b/interfaces/innerkits/native/include/usb_info.h new file mode 100644 index 00000000..972342de --- /dev/null +++ b/interfaces/innerkits/native/include/usb_info.h @@ -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. + */ + +#ifndef USB_INFO_H +#define USB_INFO_H + +#include +#include + +namespace OHOS { +namespace USB { +static constexpr int32_t INVALID_BATT_INT_VALUE = -1; +static constexpr int32_t INVALID_BATT_TEMP_VALUE = 100; +static constexpr bool INVALID_BATT_BOOL_VALUE = true; + +struct FoundDevice { + int i; +}; + +struct USBPortStatusInfo { + int currentMode; + int currentPowerRole; + int currentDataRole; +}; + +struct USBPortInfo { + int id; + int supportedModes; + USBPortStatusInfo status; +}; + +struct USBDeviceInfo { + int status; + int busNum; + int devNum; +}; + +class UsbInfo { +public: + void SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) const {} + + void setDevInfoStatus(int status) + { + devInfo.status = status; + } + void setDevInfoBusNum(int busNum) + { + devInfo.busNum = busNum; + } + void setDevInfoDevNum(int devNum) + { + devInfo.devNum = devNum; + } + + int getDevInfoStatus() const + { + return devInfo.status; + } + int getDevInfoBusNum() const + { + return devInfo.busNum; + } + int getDevInfoDevNum() const + { + return devInfo.devNum; + } + +private: + // USBPortInfo port; + USBDeviceInfo devInfo; +}; +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_INFO_H diff --git a/interfaces/innerkits/native/include/usb_interface.h b/interfaces/innerkits/native/include/usb_interface.h new file mode 100644 index 00000000..5122d10c --- /dev/null +++ b/interfaces/innerkits/native/include/usb_interface.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_INTERFACE_H +#define USB_INTERFACE_H + +#include +#include +#include +#include +#include "usb_endpoint.h" + +namespace OHOS { +namespace USB { +class UsbInterface { +public: + UsbInterface(int32_t mId, + int32_t mProtocol, + int32_t mClass, + int32_t mSubClass, + int32_t mAlternateSetting, + std::string mName, + std::vector mEndpoints) + { + this->mId = mId; + this->mProtocol = mProtocol; + this->mClass = mClass; + this->mSubClass = mSubClass; + this->mAlternateSetting = mAlternateSetting; + this->mEndpoints = mEndpoints; + } + UsbInterface() {} + const std::string &GetName() const + { + return mName; + } + int32_t GetId() const + { + return mId; + } + int32_t GetClass() const + { + return mClass; + } + int32_t GetSubClass() const + { + return mSubClass; + } + int32_t GetAlternateSetting() const + { + return mAlternateSetting; + } + int32_t GetProtocol() const + { + return mProtocol; + } + int32_t GetEndpointCount() const + { + return mEndpoints.size(); + } + void GetEndpoint(uint32_t index, USBEndpoint &ep) const + { + if (index < mEndpoints.size()) { + ep = mEndpoints[index]; + } + } + std::vector &GetEndpoints() + { + return mEndpoints; + } + void SetEndpoints(const std::vector &eps) + { + mEndpoints = eps; + } + void SetId(int Val) + { + mId = Val; + } + void SetProtocol(int Val) + { + mProtocol = Val; + } + void SetClass(int Val) + { + mClass = Val; + } + void SetSubClass(int Val) + { + mSubClass = Val; + } + void SetAlternateSetting(int Val) + { + mAlternateSetting = Val; + } + void SetName(std::string Name) + { + mName = Name; + } + ~UsbInterface() {} + std::string ToString() const + { + std::string str; + std::ostringstream ss; + ss << "id=" << mId << "," + << "mName=" << mName << "," + << "iInterface=" << (int32_t)iInterface << "," + << "mClass=" << mClass << "," + << "mSubClass=" << mSubClass << "," + << "mProtocol=" << mProtocol << "," + << "mAlternateSetting=" << mAlternateSetting << "; "; + str = ss.str(); + ss.str(""); + for (size_t i = 0; i < mEndpoints.size(); ++i) { + const USBEndpoint &endpoint = mEndpoints[i]; + str += endpoint.ToString(); + } + return str; + } + void SetiInterface(uint8_t idx) + { + this->iInterface = idx; + } + uint8_t GetiInterface() + { + return this->iInterface; + } + +private: + int mId; + int mProtocol; + int mClass; + int mSubClass; + int mAlternateSetting; + std::string mName; + std::vector mEndpoints; + uint8_t iInterface; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_INTERFACE_H diff --git a/interfaces/innerkits/native/include/usb_port.h b/interfaces/innerkits/native/include/usb_port.h new file mode 100644 index 00000000..16b1991d --- /dev/null +++ b/interfaces/innerkits/native/include/usb_port.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_PORT_H +#define USB_PORT_H + +#include +#include +#include "usb_common.h" +#include "usb_port_status.h" + +namespace OHOS { +namespace USB { +// class UsbPort { +// public: +// UsbPort(uint32_t id, uint32_t supportedModes, +// UsbPortStatus *usbPortStatus) { +// mId = id; +// mSupportedModes = supportedModes; +// mUsbPortStatus = usbPortStatus; +// } +// UsbPort(); +// ~UsbPort(); + +// uint32_t getId() const { return mId; } +// uint32_t getSupportedModes() const { return mSupportedModes; } +// UsbPortStatus *getUsbPortStatus() const { return mUsbPortStatus; } + +// private: +// uint32_t mId = INVALID_USB_INT_VALUE; +// uint32_t mSupportedModes = INVALID_USB_INT_VALUE; +// UsbPortStatus *mUsbPortStatus; +// }; + +struct UsbPortStatus { + int32_t currentMode; + /** + * POWER_ROLE_NONE, + * POWER_ROLE_SOURCE, + * POWER_ROLE_SINK + */ + int32_t currentPowerRole; + /** + * DATA_ROLE_NONE, + * DATA_ROLE_HOST, + * DATA_ROLE_DEVICE + */ + int32_t currentDataRole; +}; +struct UsbPort { + int32_t id; + /** + * MODE_NONE + * MODE_DFP + * MODE_UFP + * MODE_DUAL + */ + int32_t supportedModes; + UsbPortStatus *usbPortStatus; +}; + +} // namespace USB +} // namespace OHOS +#endif // USB_PORT_H diff --git a/interfaces/innerkits/native/include/usb_port_status.h b/interfaces/innerkits/native/include/usb_port_status.h new file mode 100644 index 00000000..480e926b --- /dev/null +++ b/interfaces/innerkits/native/include/usb_port_status.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_PORT_STATUS_H +#define USB_PORT_STATUS_H + +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { +// class UsbPortStatus { +// public: +// UsbPortStatus(uint32_t currentMode, uint32_t currentPowerRole, +// uint32_t currentDataRole) { +// mCurrentMode = currentMode; +// mCurrentPowerRole = currentPowerRole; +// mCurrentDataRole = currentDataRole; +// } +// UsbPortStatus() { +// mCurrentMode = 0; +// mCurrentPowerRole = 0; +// mCurrentDataRole = 0; +// } +// ~UsbPortStatus(); + +// int32_t GetCurrentMode() const { return mCurrentMode; } + +// int32_t GetCurrentPowerRole() const { return mCurrentPowerRole; } + +// int32_t GetCurrentDataRole() const { return mCurrentDataRole; } + +// private: +// int32_t mCurrentMode; +// int32_t mCurrentPowerRole; +// int32_t mCurrentDataRole; +// }; +} // namespace USB +} // namespace OHOS + +#endif // USB_PORT_STATUS_H diff --git a/interfaces/innerkits/native/include/usb_request.h b/interfaces/innerkits/native/include/usb_request.h new file mode 100644 index 00000000..d840d97e --- /dev/null +++ b/interfaces/innerkits/native/include/usb_request.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_REQUEST_H +#define USB_REQUEST_H + +#include +#include "iusb_srv.h" +#include "securec.h" +#include "usb_device_pipe.h" +#include "usb_endpoint.h" + +namespace OHOS { +namespace USB { +class UsbSrvClient; +class UsbRequest { +public: + UsbRequest(); + int32_t Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint); + int32_t Queue(uint8_t *buffer, uint32_t length); + int32_t Free(); + int32_t Abort(); + void SetPipe(const USBDevicePipe &pipe) + { + this->pipe = pipe; + } + void SetEndpoint(const USBEndpoint &endpoint) + { + this->endpoint = endpoint; + } + void SetClientData(void *obj, uint32_t objLength) + { + clientData = obj; + clientLength = objLength; + } + void SetBuffer(uint8_t *buffer) + { + this->buffer = buffer; + } + void SetBufferData(uint8_t *data, uint32_t dataSize) + { + if (data == nullptr || dataSize == 0 || length < dataSize) { + return; + } + memcpy_s(buffer, length, data, dataSize); + } + void SetLength(uint8_t length) + { + this->length = length; + } + void *GetClientData() + { + return clientData; + } + const USBDevicePipe &GetPipe() const + { + return pipe; + } + const USBEndpoint &GetEndpoint() const + { + return endpoint; + } + uint32_t GetClientLength() const + { + return clientLength; + } + uint8_t *GetBuffer() const + { + return buffer; + } + uint32_t GetLength() const + { + return length; + } + +public: + USBDevicePipe pipe; + USBEndpoint endpoint; + void *clientData; + uint32_t clientLength; + uint8_t *buffer; + uint32_t length; + +private: + UsbSrvClient *usbClient; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_REQUEST_H diff --git a/interfaces/innerkits/native/include/usb_srv_client.h b/interfaces/innerkits/native/include/usb_srv_client.h new file mode 100644 index 00000000..d10538ac --- /dev/null +++ b/interfaces/innerkits/native/include/usb_srv_client.h @@ -0,0 +1,111 @@ +/* + + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_USB_SRV_CLIENT_H +#define USBMGR_USB_SRV_CLIENT_H + +#include +#include +#include +#include +#include "iremote_object.h" +#include "iusb_srv.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_port.h" +#include "usb_request.h" + +namespace OHOS { +namespace USB { + +const std::string MAXVERSION = "001"; +const std::string SUBVERSION = "001"; +const std::string DLPVERSION = "010"; +const std::string SEVVERSION = MAXVERSION + "." + SUBVERSION + "." + DLPVERSION; + +class UsbSrvClient final : public DelayedRefSingleton { + + DECLARE_DELAYED_REF_SINGLETON(UsbSrvClient) + +public: + DISALLOW_COPY_AND_MOVE(UsbSrvClient); + + int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); + int32_t HasRight(std::string deviceName); + int32_t RequestRight(std::string deviceName); + int32_t GetDevices(std::vector &deviceList); + int32_t GetPorts(std::vector &usbports); + int32_t GetSupportedModes(int32_t portId, int32_t &result); + int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); + int32_t GetCurrentFunctions(int32_t &funcs); + int32_t SetCurrentFunctions(int32_t funcs); + int32_t UsbFunctionsFromString(std::string funcs); + std::string UsbFunctionsToString(int32_t funcs); + int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); + int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); + int32_t BulkTransfer(USBDevicePipe &pip, + const USBEndpoint &endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout); + int32_t ControlTransfer(USBDevicePipe &pip, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout); + int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); + int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); + int32_t GetRawDescriptors(uint8_t *buffer, uint32_t length); + int32_t GetFileDescriptor(); + bool Close(const USBDevicePipe &pip); + int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); + + int32_t RequestInitialize(UsbRequest &request); + int32_t RequestFree(UsbRequest &request); + int32_t RequestAbort(UsbRequest &request); + int32_t RequestQueue(UsbRequest &request, uint8_t *buffer, uint32_t length); + + std::string GetVersion() + { + return SEVVERSION; + } + +private: + class UsbSrvDeathRecipient : public IRemoteObject::DeathRecipient { + public: + UsbSrvDeathRecipient() = default; + ~UsbSrvDeathRecipient() = default; + void OnRemoteDied(const wptr &remote); + + private: + DISALLOW_COPY_AND_MOVE(UsbSrvDeathRecipient); + }; + + static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); + int32_t Connect(); + sptr proxy_{nullptr}; + sptr deathRecipient_{nullptr}; + void ResetProxy(const wptr &remote); + std::mutex mutex_; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SRV_CLIENT_H diff --git a/interfaces/innerkits/native/src/usb_device.cpp b/interfaces/innerkits/native/src/usb_device.cpp new file mode 100644 index 00000000..3653a2b1 --- /dev/null +++ b/interfaces/innerkits/native/src/usb_device.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_device.h" + +namespace OHOS { +namespace USB { + +} // namespace USB +} // namespace OHOS diff --git a/interfaces/innerkits/native/src/usb_device_pipe.cpp b/interfaces/innerkits/native/src/usb_device_pipe.cpp new file mode 100644 index 00000000..f2821e43 --- /dev/null +++ b/interfaces/innerkits/native/src/usb_device_pipe.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_device_pipe.h" +#include "iusb_srv.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_request.h" +#include "usb_srv_client.h" + +namespace OHOS { +namespace USB { +USBDevicePipe::USBDevicePipe() : usbClient(&UsbSrvClient::GetInstance()) {} +USBDevicePipe::USBDevicePipe(uint8_t busNum, uint8_t devAddr) + : busNum(busNum), devAddr(devAddr), usbClient(&UsbSrvClient::GetInstance()) +{ +} + +int32_t USBDevicePipe::Close() +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + int32_t ret = ERR_OK; + bool bSuccess = ((UsbSrvClient *)usbClient)->Close(*this); + if (!bSuccess) { + ret = ERR_INVALID_VALUE; + } + return ret; +} +int32_t USBDevicePipe::ClaimInterface(const UsbInterface &interface, bool force) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->ClaimInterface(*this, interface, force); +} +int32_t USBDevicePipe::ReleaseInterface(const UsbInterface &interface) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->ReleaseInterface(*this, interface); +} + +int32_t USBDevicePipe::BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t timeout) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + return ((UsbSrvClient *)usbClient)->BulkTransfer(*this, endpoint, buffer, length, timeout); +} + +int32_t USBDevicePipe::ControlTransfer(int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + return ((UsbSrvClient *)usbClient) + ->ControlTransfer(*this, requestType, request, value, index, buffer, length, timeout); +} +int32_t USBDevicePipe::SetConfiguration(const USBConfig &config) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->SetConfiguration(*this, config); +} +int32_t USBDevicePipe::SetInterface(const UsbInterface &interface) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->SetInterface(*this, interface); +} +void USBDevicePipe::SetBusNum(uint8_t busNum) +{ + this->busNum = busNum; +} +void USBDevicePipe::SetDevAddr(uint8_t devAddr) +{ + this->devAddr = devAddr; +} +uint8_t USBDevicePipe::GetBusNum() const +{ + return busNum; +} +uint8_t USBDevicePipe::GetDevAddr() const +{ + return devAddr; +} +} // namespace USB +} // namespace OHOS diff --git a/interfaces/innerkits/native/src/usb_request.cpp b/interfaces/innerkits/native/src/usb_request.cpp new file mode 100644 index 00000000..eba471ad --- /dev/null +++ b/interfaces/innerkits/native/src/usb_request.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_request.h" +#include "usb_common.h" +#include "usb_srv_client.h" + +namespace OHOS { +namespace USB { +UsbRequest::UsbRequest() + : clientData(nullptr), clientLength(0), buffer(nullptr), length(0), usbClient(&UsbSrvClient::GetInstance()) +{ +} +int32_t UsbRequest::Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) +{ + this->pipe = pipe; + this->endpoint = endpoint; + return usbClient->RequestInitialize(*this); +} + +int32_t UsbRequest::Queue(uint8_t *buffer, uint32_t length) +{ + this->buffer = buffer; + this->length = length; + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : buffer=%{public}p, length=%{public}d", __func__, buffer, length); + return usbClient->RequestQueue(*this, buffer, length); +} + +int32_t UsbRequest::Free() +{ + return usbClient->RequestFree(*this); +} + +int32_t UsbRequest::Abort() +{ + return usbClient->RequestAbort(*this); +} +} // namespace USB +} // namespace OHOS diff --git a/interfaces/innerkits/native/src/usb_srv_client.cpp b/interfaces/innerkits/native/src/usb_srv_client.cpp new file mode 100644 index 00000000..31ad54ae --- /dev/null +++ b/interfaces/innerkits/native/src/usb_srv_client.cpp @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_srv_client.h" +#include +#include "datetime_ex.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "usb_common.h" + +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" + +namespace OHOS { +namespace USB { +#define USB_MAX_REQUEST_DATA_SIZE 1024 + +UsbSrvClient::UsbSrvClient() +{ + Connect(); +} +UsbSrvClient::~UsbSrvClient() {} + +void UsbSrvClient::PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << 二进制数据流[" << length << "字节] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_INNERKIT, "%{public}s", oss.str().c_str()); +} +int32_t UsbSrvClient::Connect() +{ + std::lock_guard lock(mutex_); + if (proxy_ != nullptr) { + return ERR_OK; + } + sptr sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sm == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:fail to get Registry", __func__); + return E_GET_SYSTEM_ABILITY_MANAGER_FAILED; + } + sptr remoteObject_ = sm->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + if (remoteObject_ == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "GetSystemAbility failed."); + return E_GET_USB_SERVICE_FAILED; + } + proxy_ = iface_cast(remoteObject_); + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s :Connect UsbService ok.", __func__); + return ERR_OK; +} + +void UsbSrvClient::ResetProxy(const wptr &remote) +{ + std::lock_guard lock(mutex_); + RETURN_IF(proxy_ == nullptr); + auto serviceRemote = proxy_->AsObject(); + if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) { + serviceRemote->RemoveDeathRecipient(deathRecipient_); + proxy_ = nullptr; + } +} + +void UsbSrvClient::UsbSrvDeathRecipient::OnRemoteDied(const wptr &remote) +{ + if (remote == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbSrvDeathRecipient::OnRemoteDied failed, remote is nullptr."); + return; + } + UsbSrvClient::GetInstance().ResetProxy(remote); + USB_HILOGI(MODULE_USB_INNERKIT, "UsbSrvDeathRecipient::Recv death notice."); +} + +int32_t UsbSrvClient::OpenDevice(const UsbDevice &device, USBDevicePipe &pipe) +{ + int32_t ret; + USB_HILOGI(MODULE_USB_INNERKIT, " Calling OpenDevice Start!"); + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->OpenDevice(device.GetBusNum(), device.GetDevAddr()); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + return ret; + } + + pipe.SetBusNum(device.GetBusNum()); + pipe.SetDevAddr(device.GetDevAddr()); + return ERR_OK; +} + +int32_t UsbSrvClient::HasRight(std::string deviceName) +{ + int32_t ret = 0; + USB_HILOGI(MODULE_USB_INNERKIT, " Calling HasRight Start!"); + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->HasRight(deviceName); + if (ret) { + USB_HILOGI(MODULE_USB_INNERKIT, " Calling HasRight False!"); + } + return ret; +} + +int32_t UsbSrvClient::RequestRight(std::string deviceName) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->RequestRight(deviceName); + if (ret) { + USB_HILOGI(MODULE_USB_INNERKIT, " Calling RequestRight False!"); + } + return ret; +} + +int32_t UsbSrvClient::GetDevices(std::vector &deviceList) +{ + int32_t ret; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->GetDevices(deviceList); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s list size = %{public}d!", __func__, deviceList.size()); + return ret; +} + +int32_t UsbSrvClient::GetCurrentFunctions(int32_t &funcs) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->GetCurrentFunctions(funcs); + if (ret < ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + USB_HILOGI(MODULE_USB_INNERKIT, " Calling GetCurrentFunctions Success!"); + return ret; +} +int32_t UsbSrvClient::SetCurrentFunctions(int32_t funcs) +{ + RETURN_IF_WITH_RET(Connect() != ERR_OK, false); + int32_t ret = proxy_->SetCurrentFunctions(funcs); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + return ret; + } + USB_HILOGI(MODULE_USB_INNERKIT, " Calling SetCurrentFunctions Success!"); + return ret; +} + +int32_t UsbSrvClient::UsbFunctionsFromString(std::string funcs) +{ + int32_t result = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + result = proxy_->UsbFunctionsFromString(funcs); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling UsbFunctionsFromString Success!"); + return result; +} + +std::string UsbSrvClient::UsbFunctionsToString(int32_t funcs) +{ + std::string result; + RETURN_IF_WITH_RET(Connect() != ERR_OK, result); + result = proxy_->UsbFunctionsToString(funcs); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling UsbFunctionsToString Success!"); + return result; +} + +int32_t UsbSrvClient::GetPorts(std::vector &usbports) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling GetPorts"); + ret = proxy_->GetPorts(usbports); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + return ret; +} + +int32_t UsbSrvClient::GetSupportedModes(int32_t portId, int32_t &result) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling GetSupportedModes"); + ret = proxy_->GetSupportedModes(portId, result); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + return ret; +} + +int32_t UsbSrvClient::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling SetPortRole"); + ret = proxy_->SetPortRole(portId, powerRole, dataRole); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + return ret; +} + +int32_t UsbSrvClient::ClaimInterface(USBDevicePipe &pipe, const UsbInterface &interface, bool force) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + ret = proxy_->ClaimInterface(pipe.GetBusNum(), pipe.GetDevAddr(), interface.GetId()); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + return ret; +} +int32_t UsbSrvClient::ReleaseInterface(USBDevicePipe &pipe, const UsbInterface &interface) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + ret = proxy_->ReleaseInterface(pipe.GetBusNum(), pipe.GetDevAddr(), interface.GetId()); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + return ret; +} +int32_t UsbSrvClient::BulkTransfer(USBDevicePipe &pipe, + const USBEndpoint &endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ret; + } + PrintBuffer("UsbSrvClient::BulkTransfer", (const uint8_t *)buffer, length); + if (USB_ENDPOINT_DIR_IN == endpoint.GetDirection()) { + ret = proxy_->BulkTransferRead(pipe.GetBusNum(), pipe.GetDevAddr(), endpoint.GetInterfaceId(), + endpoint.GetAddress(), buffer, length, timeout); + } else if (USB_ENDPOINT_DIR_OUT == endpoint.GetDirection()) { + ret = proxy_->BulkTransferWrite(pipe.GetBusNum(), pipe.GetDevAddr(), endpoint.GetInterfaceId(), + endpoint.GetAddress(), buffer, length, timeout); + } + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + return ret; +} +int32_t UsbSrvClient::ControlTransfer(USBDevicePipe &pipe, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ret; + } + ret = proxy_->ControlTransfer(pipe.GetBusNum(), pipe.GetDevAddr(), requestType, request, value, index, buffer, + length, timeout); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + + return ret; +} +int32_t UsbSrvClient::SetConfiguration(USBDevicePipe &pipe, const USBConfig &config) +{ + int32_t ret = ERR_OK; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + ret = proxy_->SetActiveConfig(pipe.GetBusNum(), pipe.GetDevAddr(), config.GetId()); + return ret; +} +int32_t UsbSrvClient::SetInterface(USBDevicePipe &pipe, const UsbInterface &interface) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + return proxy_->SetInterface(pipe.GetBusNum(), pipe.GetDevAddr(), interface.GetId(), + interface.GetAlternateSetting()); +} +int32_t UsbSrvClient::GetRawDescriptors(uint8_t *buffer, uint32_t length) +{ + length = 0; + return 0; +} +int32_t UsbSrvClient::GetFileDescriptor() +{ + return 0; +} + +bool UsbSrvClient::Close(const USBDevicePipe &pipe) +{ + int32_t ret = ERR_OK; + RETURN_IF_WITH_RET(proxy_ == nullptr, false); + ret = proxy_->Close(pipe.GetBusNum(), pipe.GetDevAddr()); + return (ret == ERR_OK); +} + +int32_t UsbSrvClient::PipeRequestWait(USBDevicePipe &pipe, int64_t timeout, UsbRequest &req) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + int32_t ret = ERR_OK; + uint32_t length = USB_MAX_REQUEST_DATA_SIZE; + uint8_t *buffer = new uint8_t[length]; + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + uint32_t clientLength = sizeof(UsbRequest); + uint8_t *clientObj = new uint8_t[clientLength]; + ret = proxy_->RequestWait(pipe.GetBusNum(), pipe.GetDevAddr(), timeout, clientObj, clientLength, buffer, length); + if (ret != ERR_OK) { + delete[] buffer; + delete[] clientObj; + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s :failed width ret = %{public}d.", __func__, ret); + return ret; + } + + PrintBuffer("UsbSrvClient::PipeRequestWait out", (const uint8_t *)clientObj, clientLength); + UsbRequest *sendReq = reinterpret_cast(clientObj); + if (sendReq == nullptr || clientLength == 0) { + delete[] buffer; + delete[] clientObj; + return ERR_INVALID_VALUE; + } + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : buffer=%{public}p, length=%{public}d", __func__, sendReq->GetBuffer(), + sendReq->GetLength()); + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : clientData=%{public}p, ClientLength=%{public}d", __func__, + sendReq->GetClientData(), sendReq->GetClientLength()); + + req = *sendReq; + if (length > 0) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : buffer=%{public}p, length=%{public}d.", __func__, req.GetBuffer(), + req.GetLength()); + req.SetLength(length); + req.SetBuffer(buffer); + } else { + delete[] buffer; + } + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : ok", __func__); + delete[] clientObj; + return ERR_OK; +} + +int32_t UsbSrvClient::RequestInitialize(UsbRequest &request) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &endpoint = request.GetEndpoint(); + return proxy_->ClaimInterface(pipe.GetBusNum(), pipe.GetDevAddr(), endpoint.GetInterfaceId()); +} + +int32_t UsbSrvClient::RequestFree(UsbRequest &request) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &ep = request.GetEndpoint(); + return proxy_->ReleaseInterface(pipe.GetBusNum(), pipe.GetDevAddr(), ep.GetInterfaceId()); +} + +int32_t UsbSrvClient::RequestAbort(UsbRequest &request) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &ep = request.GetEndpoint(); + return proxy_->RequestCancel(pipe.GetBusNum(), pipe.GetDevAddr(), ep.GetInterfaceId(), ep.GetAddress()); +} + +int32_t UsbSrvClient::RequestQueue(UsbRequest &request, uint8_t *buffer, uint32_t length) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &ep = request.GetEndpoint(); + return proxy_->RequestQueue(pipe.GetBusNum(), pipe.GetDevAddr(), ep.GetInterfaceId(), ep.GetAddress(), &request, + sizeof(UsbRequest), const_cast(buffer), length); +} +} // namespace USB +} // namespace OHOS diff --git a/interfaces/kits/java/BUILD.gn b/interfaces/kits/java/BUILD.gn new file mode 100644 index 00000000..f3a90d8c --- /dev/null +++ b/interfaces/kits/java/BUILD.gn @@ -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. + +import("//build/config/ohos/rules.gni") +import("//build/ohos.gni") + +USB_MANAGER_ROOT = "//base/usb/usb_manager" +ADAPTER_DIR = "$USB_MANAGER_ROOT/adapter" +INTERFACES_ROOT = "$USB_MANAGER_ROOT/interfaces" + +java_library("usb_manager_java") { + java_files = [ + "$INTERFACES_ROOT/kits/java/ohos/usb/USBLoggerFactory.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBDevice.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBDevicePipe.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBInterface.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBCore.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBRequest.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBConfig.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBEndpoint.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/package-info.java", + ] + + deps = [ "//utils/java:utils_maple_java" ] + + external_deps = [ + "appexecfwk:appexecfwk_java", + "appexecfwk:appexecfwk_java_maple", + "hilog:hilog_maple_java", + "samgr:samgr_java", + "samgr:samgr_java_maple", + ] + + subsystem_name = "usb" + part_name = "usb_manager" +} + +ohos_maple_java("usb_manager_maple_java") { + deps = [ ":usb_manager_java" ] + external_deps = [ "hilog:hilog_maple_java" ] + so_name = "usb_manager_java" + part_name = "usb_manager" + output_dir = "$root_build_dir/usb/" +} diff --git a/interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java b/interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java new file mode 100644 index 00000000..50adf081 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java @@ -0,0 +1,42 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.RemoteException; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; + +public interface IUSBDevicePipeController extends IRemoteBroker { + + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int length, int timeout) throws RemoteException; + + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout) throws RemoteException; + + boolean claimInterface(USBInterface interfaceObj, boolean force) throws RemoteException; + + void close() throws RemoteException; + + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int offset, int length, int timeout) throws RemoteException; + + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) throws RemoteException; + + int getFileDescriptor() throws RemoteException; + + byte[] getRawDescriptors() throws RemoteException; + + String getSerial() throws RemoteException; + + boolean releaseInterface(USBInterface interfaceObj) throws RemoteException; + + USBRequest requestWait(long timeout) throws TimeoutException, RemoteException; + + USBRequest requestWait() throws RemoteException; + + boolean setConfiguration(USBConfig config) throws RemoteException; + + boolean setInterface(USBInterface interfaceObj) throws RemoteException; + + boolean openByInt(String name, int fd) throws RemoteException; + +} diff --git a/interfaces/kits/java/ohos/usb/IUSBRequestController.java b/interfaces/kits/java/ohos/usb/IUSBRequestController.java new file mode 100644 index 00000000..990baa03 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/IUSBRequestController.java @@ -0,0 +1,28 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.RemoteException; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; + +import java.util.List; + +public interface IUsbRequestController extends IRemoteBroker { + + void abort() throws RemoteException; + + void free() throws RemoteException; + + boolean initialize(USBDevicePipe connection, USBEndpoint ep) throws RemoteException; + + boolean queue(ByteBuffer buffer) throws RemoteException; + + boolean queue(ByteBuffer buffer, int length) throws RemoteException; + + void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) throws RemoteException; + + void setClientData(Object data) throws RemoteException; + +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/IUsbCoreController.java b/interfaces/kits/java/ohos/usb/IUsbCoreController.java new file mode 100644 index 00000000..13d34442 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/IUsbCoreController.java @@ -0,0 +1,43 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.RemoteException; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; + +import java.util.List; + +public interface IUsbCoreController extends IRemoteBroker { + + + HashMap getDevices() throws RemoteException; + + USBDevicePipe connectDevice(USBDevice device) throws RemoteException; + + boolean hasRight(USBDevice device) throws RemoteException; + + void requestRight(USBDevice device, String intentName) throws RemoteException; + + String usbFunctionsToString(long functions) throws RemoteException; + + long usbFunctionsFromString(String functions) throws RemoteException; + + String getCurrentFunctions() throws RemoteException; + + void setCurrentFunctions(long functions) throws RemoteException; + + void setCurrentFunction(String functions, boolean usbDataUnlocked) throws RemoteException; + + void setHdcEnabled(boolean enable) throws RemoteException; + + void addFunction(String functions, String function) throws RemoteException; + + void removeFunction(String functions, String function) throws RemoteException; + + void setPortRoles(int powerRole,int dataRole) throws RemoteException; + + UsbPortStatus getPortStatus(USBPort port) throws RemoteException; + +} diff --git a/interfaces/kits/java/ohos/usb/USBConfig.java b/interfaces/kits/java/ohos/usb/USBConfig.java new file mode 100644 index 00000000..4d43cad6 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBConfig.java @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Gets information about USB configuration. + * + *

When using this class, a USB device is attached to a USB host. According to the USB protocol specifications, + * a device contains one or more configurations, a configuration contains one or more interfaces, and an interface + * contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBConfig { + private int id; + + private int maxPower; + + private String name; + + private boolean isRemoteWakeup; + + private boolean isSelfPowered; + + private USBInterface[] interfaces; + + public USBConfig(int id, int maxPower, String name, boolean isRemoteWakeup, boolean isSelfPowered) { + this.id = id; + this.maxPower = maxPower; + this.name = name; + this.isRemoteWakeup = isRemoteWakeup; + this.isSelfPowered = isSelfPowered; + } + + /** + * Get a {@code USBInterface} object by index in the {@code USBConfig}. + * + * @param index Indicates the {@code USBInterface} object index in the {@code USBConfig}. + * @return Returns the {@code USBInterface} object . + * @since 5 + */ + public USBInterface getInterface(int index) { + if (interfaces == null || index < 0 || index >= interfaces.length) { + return null; + } + + return interfaces[index]; + } + + /** + * Sets a local {@code USBInterface} object. + * + * @param interfaces Indicates a local {@code USBInterface} object. + * @since 5 + */ + public void setInterfaces(USBInterface[] interfaces) { + this.interfaces = interfaces; + } + + /** + * Get the number of interfaces of the configuration. + * + * @return Returns the number of interfaces of the configuration. + * @since 5 + */ + public int getInterfaceCount() { + if (interfaces == null) { + return 0; + } + + return interfaces.length; + } + + /** + * Get the current configuration ID. + * + * @return Returns the current configuration ID. + * @since 5 + */ + public int getId() { + return id; + } + + /** + * Get the maximum power consumption of the current configuration. + * + * @return Returns the maximum power consumption. + * @since 5 + */ + public int getMaxPower() { + return maxPower; + } + + /** + * Get the current configuration name. + * + * @return Returns the current configuration name. + * @since 5 + */ + public String getName() { + return name; + } + + /** + * Checks whether the current configuration supports remote wakeup. + * + * @return Returns {@code true} if the configuration supports remote wakeup; returns {@code false} otherwise. + * @since 5 + */ + public boolean isRemoteWakeup() { + return isRemoteWakeup; + } + + /** + * Checks whether the configuration supports an independent power source. + * + * @return Returns {@code true} if the configuration supports an independent power source; + * returns {@code false} otherwise. + * @since 5 + */ + public boolean isSelfPowered() { + return isSelfPowered; + } +} + diff --git a/interfaces/kits/java/ohos/usb/USBCore.java b/interfaces/kits/java/ohos/usb/USBCore.java new file mode 100644 index 00000000..2b9a5dbf --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBCore.java @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.StringJoiner; + +import ohos.app.Context; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * This class allows you to obtain USB devices currently attached, obtain USB device status, + * and communicate with USB devices. + * Currently, only the host mode is supported. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBCore { + + /** + * A constructor used to create a {@code USBCore}. + * + * @since 5 + */ + public USBCore() { + + } + + /** + * Returns the hash map of USB devices. + * + *

The hash map contains devices and their names. Applications can traverse USB devices in the hash map to + * perform operations on the devices. For details on the operations, see {@link ohos.usb.USBDevice}. + * + * @return Returns a hash map containing devices and their names. + * @since 5 + */ + public HashMap getDevices() { + HashMap results = new HashMap(); + native_get_devices(results); + return results; + } + + public HashMap getPeripherals() { + + } + + /** + * Opens a USB device based on device information returned by {@link ohos.usb.USBCore#getDevices}. + * + *

A {@link ohos.usb.USBDevicePipe} instance is returned. Data transfer is performed based on the + * instance. + * + * @param device Indicates a {@link ohos.usb.USBDevicePipe} instance. + * @return Returns a {@link ohos.usb.USBDevicePipe} instance. + * @since 5 + */ + public USBDevicePipe connectDevice(USBDevice device) { + return native_connnect_device(device); + } + + /** + * Returns true if the caller has right to access the device. + * + * @param device to check right for + * @return {@code true} if caller has right to access this device + * @since 5 + */ + public boolean hasRight(USBDevice device) { + return native_has_right(device); + } + + /** + * Requests temporary permission for the given package to access the device. + * + * @param device Device to request permissions for + * @param intentName Intent for returning result + */ + public void requestRight(USBDevice device, String intentName) { + native_request_right(device, intentName); + } + + /** + * Converts the given function mask to string. Maintains ordering with respect to init scripts. + * + * @param functions the usb functions long value + * @return String representation of given mask + * @since 5 + */ + public String usbFunctionsToString(long functions) { + return native_usb_function_to_string(functions); + } + + /** + * Parses a string of usb functions that are comma separated. + * + * @param functions the usb functions + * @return A mask of all valid functions in the string + * @since 5 + */ + public long usbFunctionsFromString(String functions) { + return native_usb_function_from_string(functions); + } + + public String getCurrentFunctions() { + return native_get_current_functions(); + } + + public void setCurrentFunctions(long functions) { + native_set_current_functions(functions); + } + + public void setCurrentFunction(String functions, boolean usbDataUnlocked) { + native_set_current_function(functions, usbDataUnlocked); + } + + public void setHdcEnabled(boolean enable) { + native_set_hdc_enabled(enable); + } + + public void addFunction(String functions, String function) { + native_add_function(functions, function); + } + + public void removeFunction(String functions, String function) { + native_remove_function(functions, function); + } + + public void setPortRoles(int powerRole,int dataRole) { + native_set_port_roles(powerRole, dataRole); + } + + public UsbPortStatus getPortStatus(USBPort port) { + return native_get_port_status(port); + } + + private native void native_get_devices(HashMap results); + + private native USBDevicePipe native_connnect_device(USBDevice device); + + private native boolean native_has_right(USBDevice device); + + private native void native_request_right(USBDevice device, String intentName); + + private native String native_usb_function_to_string(long functions); + + private native long native_usb_function_from_string(String functions); + + private native String native_get_current_functions(); + + private native void native_set_current_functions(long functions); + + private native void native_set_current_function(String functions, boolean usbDataUnlocked); + + private native void native_set_hdc_enabled(boolean enable); + + private native void native_add_function(String functions, String function); + + private native void native_remove_function(String functions, String function); + + private native void native_set_port_roles(int powerRole,int dataRole); + + private native UsbPortStatus native_get_port_status(USBPort port); +} + + + + + + diff --git a/interfaces/kits/java/ohos/usb/USBDevice.java b/interfaces/kits/java/ohos/usb/USBDevice.java new file mode 100644 index 00000000..428c24e7 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBDevice.java @@ -0,0 +1,290 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Get configuration information of a USB device. For details on the information + * structure, see USB protocol specifications. + * + *

+ * When using this class, a USB device is attached to a USB host. According to + * the USB protocol specifications, a device contains one or more + * configurations, a configuration contains one or more interfaces, and an + * interface contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBDevice { + + private final int deviceId; + + private final String deviceName; + + private final String manufacturerName; + + private final String productName; + + private final String version; + + private final String serialNumber; + + private final int vendorId; + + private final int productId; + + private final int classId; + + private final int subclass; + + private final int protocol; + + private USBConfig[] configs; + + private USBInterface[] interfaces; + + /** + * A constructor used to create a {@code USBDevice}. + * + * @param deviceId Indicates the id of the USB device, which is usually determined by the low layer. + * @param deviceName Indicates the name of the USB device, which is usually determined by the low layer. + * @param vendorId Indicates the vendor ID of the USB device, which is assigned by the USB-IF. + * @param productId Indicates the product ID of the USB device, which is assigned by the USB-IF. + * @param classId Indicates the class code of the USB device, which is assigned by the USB-IF. + * @param subClassId Indicates the subclass code of the USB device, which is assigned by the USB-IF. + * @param protocolId Indicates the protocol code of the USB device, which is assigned by the USB-IF. + * @param manufacturerName Indicates the manufacturer name of the USB device. + * @param productName Indicates the product name of the USB device. + * @param version Indicates the version number of the USB device. + * @param serialNumber Indicates the serial number of the USB device. + * + * @since 5 + */ + public USBDevice(int deviceId, String deviceName, int vendorId, int productId, int classId, int subClassId, int protocolId, + String manufacturerName, String productName, String version, String serialNumber) { + this.deviceId = deviceId; + this.deviceName = deviceName; + this.vendorId = vendorId; + this.productId = productId; + this.classId = classId; + this.subclass = subClassId; + this.protocol = protocolId; + this.manufacturerName = manufacturerName; + this.productName = productName; + this.version = version; + this.serialNumber = serialNumber; + } + + /** + * Gets the {@code Class} field of a USB device. + * + * @return Returns the {@code Class} field. + * @since 5 + */ + public int getDeviceClass() { + return classId; + } + + /** + * Gets the {@code Id} field of a USB device. + * + * @return Returns the {@code Id} field. + * @since 5 + */ + public int getDeviceId() { + return deviceId; + } + + /** + * Get the {@code Name} field of a USB device. + * + * @return Returns the {@code Name} field. + * @since 5 + */ + public String getDeviceName() { + return deviceName; + } + + /** + * Get the {@code Name} field of a USB device. + * + * @param id Id of the USB device. + * @return Returns the {@code Name} field. + * @since 5 + */ + public static String getDeviceName(int id) { + return "default_dev"; + } + + /** + * Get the {@code Protocol} field of a USB device. + * + * @return Returns the {@code Protocol} field. + * @since 5 + */ + public int getDeviceProtocol() { + return protocol; + } + + /** + * Get the {@code SubClass} field of a USB device. + * + * @return Returns the {@code SubClass} field. + * @since 5 + */ + public int getDeviceSubclass() { + return subclass; + } + + /** + * Sets interfaces for a local object. + * + * @param interfaces Indicates the array of a {@code USBInterface} object. + * @since 5 + */ + public void setInterfaces(USBInterface[] interfaces) { + this.interfaces = interfaces; + } + + /** + * Get an interface instance of this device by index. + * + * @param index Indicates the interface index. + * @return Returns the interface. + * @since 5 + */ + public USBInterface getInterface(int index) { + if (interfaces == null || index < 0 || index >= interfaces.length) { + return null; + } + return interfaces[index]; + } + + /** + * Get the number of interfaces of this device. + * + * @return Returns the number of interfaces. + * @since 5 + */ + public int getInterfaceCount() { + if (interfaces == null) { + return 0; + } + + return interfaces.length; + } + + /** + * Get the manufacturer string of this device. + * + * @return Returns the manufacturer string of this device. + * @since 5 + */ + public String getManufacturerName() { + return manufacturerName; + } + + /** + * Get the {@code ProductId} field of a USB device. + * + * @return Returns the {@code ProductId} field. + * @since 5 + */ + public int getProductId() { + return productId; + } + + /** + * Get the {@code ProductName} field of a USB device. + * + * @return Returns the {@code ProductName} field. + * @since 5 + */ + public String getProductName() { + return productName; + } + + /** + * Get the {@code SerialNumber} field of a USB device. + * + * @return Returns the {@code SerialNumber} field. + * @since 5 + */ + public String getSerialNumber() { + return serialNumber; + } + + /** + * Get the {@code VendorId} field of a USB device. + * + * @return Returns the {@code VendorId} field. + * @since 5 + */ + public int getVendorId() { + return vendorId; + } + + /** + * Get the {@code Version} field of a USB device. + * + * @return Returns the {@code Version} field. + * @since 5 + */ + public String getVersion() { + return version; + } + + /** + * Get a {@code USBConfig} instance of this device by index. + * + * @param index Indicates the configuration index. + * @return Returns the corresponding {@code USBConfig} object. + * @since 5 + */ + public USBConfig getConfiguration(int index) { + if (configs == null || index < 0 || index >= configs.length) { + return null; + } + return configs[index]; + } + + /** + * Get the number of configurations of this device. + * + * @return Returns the number of configurations. + * @since 5 + */ + public int getConfigurationCount() { + if (configs == null) { + return 0; + } + return configs.length; + } + + /** + * Sets configurations of this device. + * + * @param configs Indicates the array of a {@code USBConfig} object. + * @since 5 + */ + public void setConfigurations(USBConfig[] configs) { + this.configs = configs; + } +} diff --git a/interfaces/kits/java/ohos/usb/USBDevicePipe.java b/interfaces/kits/java/ohos/usb/USBDevicePipe.java new file mode 100644 index 00000000..e8ebb792 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBDevicePipe.java @@ -0,0 +1,263 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import java.util.concurrent.TimeoutException; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Provides methods for transferring data and control messages between USB devices. + * + *

Applications can get device descriptors from {@link ohos.usb.USBDevice} to operate the USB devices. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBDevicePipe { + /** + * Indicates a {@code USBDevice}. + */ + public final USBDevice device; + + public USBDevicePipe(USBDevice device) { + this.device = device; + } + + /** + * Performs bulk data transfer on a specified endpoint. + * + * @param epObj the endpoint instance. + * @param buffer Indicates the buffer for bulk data transfer. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. The value {@code 0} indicates that the + * transfer never times out. + * @return Returns a value greater than or equal to {@code 0} if the data transfer is successful; returns a + * negative value otherwise. + * @since 5 + */ + public int bulkTransfer(USBEndpoint epObj, byte[] buffer, int length, int timeout) { + return native_bulk_transfer(epObj, buffer, 0, length, timeout); + } + + /** + * Performs bulk data transfer on a specified endpoint. + * + * @param epObj the endpoint instance. + * @param buffer Indicates the buffer for bulk data transfer. + * @param offset Indicates the offset from first byte in the buffer. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. The value {@code 0} indicates that the + * transfer never times out. + * @return Returns a value greater than or equal to {@code 0} if the data transfer is successful; returns a negative + * value otherwise. + * @since 5 + */ + public int bulkTransfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout) { + return native_bulk_transfer(epObj, buffer, offset, length, timeout); + } + + /** + * Claims that a specified interface is exclusively occupied. This must be done before transferring data to the + * endpoint of the {@code interfaceObj} interface. + * + * @param interfaceObj Indicates the interface to be exclusively occupied. + * @param force Indicates whether the kernel driver is disconnected. The value {@code true} indicates that the + * kernel driver is disconnected. The value {@code false} indicates that the kernel driver is connected + * @return Returns {@code true} if the claim is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean claimInterface(USBInterface interfaceObj, boolean force) { + return native_claim_interface(interfaceObj, force); + } + + /** + * Closes the request. + */ + public void close() { + native_close(); + } + + /** + * Performs control message transfer on endpoint zero. + * + * @param requestType Indicates the type of request initiated for control message transfer. For details, + * see USB protocol specifications. If the most significant bit is 1, data is written from the host. If the most + * significant bit is 0, data is written into the host. + * @param request Indicates the request ID. + * @param value Indicates the value of the transfer. + * @param index Indicates the index of the transfer. + * @param buffer Indicates the buffer from which data is to be transferred. + * @param offset Indicates the offset address starting from 0 in the data buffer. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. + * @return Returns the number of bytes transferred; returns {@code 0} if the transfer fails. + * @since 5 + */ + public int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int offset, + int length, int timeout) { + return native_control_transfer(requestType, request, value, index, buffer, offset, length, timeout); + } + + /** + * Performs control message transfer on endpoint zero. + * + * @param requestType Indicates the type of request initiated for control message transfer. For details, see USB + * protocol specifications. If the most significant bit is 1, data is written from the host. If the most + * significant bit is 0, data is written into the host. + * @param request Indicates the request ID. + * @param value Indicates the value of the transfer. + * @param index Indicates the index of the transfer. + * @param buffer Indicates the buffer from which data is to be transferred. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. + * @return Returns the number of bytes transferred; returns {@code 0} if the transfer fails. + * @since 5 + */ + public int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, + int timeout) { + return controlTransfer(requestType, request, value, index, buffer, 0, length, timeout); + } + + /** + * Get the file descriptor. + * + * @return Returns the file descriptor. + * @since 5 + */ + public int getFileDescriptor() { + return native_get_file_descriptor(); + } + + /** + * Get the original USB descriptors. + * + * @return Returns the original USB descriptors. + * @since 5 + */ + public byte[] getRawDescriptors() { + return native_get_raw_descriptors(); + } + + /** + * Get the serial number, in string. + * + * @return Returns the serial number. + * @since 5 + */ + public String getSerial() { + return native_get_serial(); + } + + /** + * Claims that a specified interface is released. + * + * @param interfaceObj Indicates the interface to release. + * @return Returns {@code true} if the release is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean releaseInterface(USBInterface interfaceObj) { + return native_release_interface(interfaceObj); + } + + /** + * Waits for the result returned by the {@link ohos.usb.USBRequest#queue} method. This is an + * asynchronous + * method call. If the operation times out, a timeout exception is thrown. + * + * @param timeout Indicates the timeout period, in milliseconds. The value {@code 0} indicates no waiting. + * @return Returns a {@link ohos.usb.USBRequest} object. + * @throws TimeoutException Throws this exception if the specified timeout elapses. + * @since 5 + */ + public USBRequest requestWait(long timeout) throws TimeoutException { + return native_request_wait(timeout); + } + + /** + * Waits for the result returned by the {@link ohos.usb.USBRequest#queue} method. + * + * @return Returns a {@link ohos.usb.USBRequest} object. + * @since 5 + */ + public USBRequest requestWait() { + return native_request_wait(); + } + + /** + * Sets the current USB configuration. + * + * @param config The config instance. + * @return Returns {@code true} if the setting is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean setConfiguration(USBConfig config) { + return native_set_configuration(config); + } + + /** + * Sets the current USB interface. + * + * @param interfaceObj Indicates a {@code USBInterface} object. + * @return Returns {@code true} if the setting is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean setInterface(USBInterface interfaceObj) { + return native_set_interface(interfaceObj); + } + + /** + * Performs an open process on the file descriptor. + * + * @param name Indicates the device name. + * @param fd Indicates the file descriptor of the device connection. + * @return Returns the result of the open process. + */ + public boolean openByInt(String name, int fd) { + return native_open_by_int(name, fd); + } + + private native int native_bulk_transfer(USBEndpoint epObj, byte[] buffer, int length, int timeout); + + private native int native_bulk_transfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout); + + private native boolean native_claim_interface(USBInterface interfaceObj, boolean force); + + private native void native_close(); + + private native int native_control_transfer(int requestType, int request, int value, int index, byte[] buffer, int offset, int length, int timeout); + + private native int native_get_file_descriptor(); + + private native byte[] native_get_raw_descriptors(); + + private native String native_get_serial(); + + private native boolean native_release_interface(USBInterface interfaceObj); + + private native USBRequest native_request_wait(long timeout); + + private native USBRequest native_request_wait(); + + private native boolean native_set_configuration(USBConfig config); + + private native boolean native_set_interface(USBInterface interfaceObj); + + private native boolean native_open_by_int(String name, int fd); + +} diff --git a/interfaces/kits/java/ohos/usb/USBDevicePipeController.java b/interfaces/kits/java/ohos/usb/USBDevicePipeController.java new file mode 100644 index 00000000..88904b7c --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBDevicePipeController.java @@ -0,0 +1,142 @@ +package ohos.usb; + +import java.util.concurrent.TimeoutException; + +import ohos.aafwk.ability.Ability; +import ohos.aafwk.ability.Lifecycle; +import ohos.app.Context; +import ohos.event.intentagent.IntentAgent; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.SystemCap; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; +import ohos.nfc.tag.TagInfo; + +@SystemCap("SystemCapability.Communication.USB") +public class USBDevicePipeController { + + private static UsbDevicePipeController sUsbDevicePipeController; + private UsbDevicePipeControllerProxy mUsbDevicePipeControllerProxy; + private Context mContext; + + /** + * A callback to be invoked when the system finds a tag while the foreground page is operating in reader mode. + * + */ + public interface ReaderModeCallback extends IRemoteBroker { + /** + * Indicates the transaction code of the callback specific to inter-process communication (IPC). + */ + int TRANSACTION_ON_CALLBACK = 1; + + /** + * Called when a tag is discovered. + * + * @param tagInfo Indicates information of the discovered tag. + * @since 4 + */ + void onTagDiscovered(TagInfo tagInfo); + } + + /** + * Provides ReaderModeCallback for communicate with remote. + * + * @since 4 + */ + public class ReaderModeCallbackStub extends RemoteObject implements ReaderModeCallback { + private ReaderModeCallback callback; + + public ReaderModeCallbackStub(ReaderModeCallback callback) { + super(); + this.callback = callback; + } + + private void readInterfaceToken(Parcel data) { + data.readInt(); + data.readInt(); + data.readString(); + } + + @Override + public boolean onRemoteRequest( + int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { + HiLog.debug(LABEL, "call ReaderModeCallbackStub's onTransact"); + + switch (code) { + case TRANSACTION_ON_CALLBACK: { + readInterfaceToken(data); + + TagInfo tagInfo = new TagInfo(null, null, null, 0); + if (tagInfo instanceof Sequenceable) { + data.readSequenceable((Sequenceable) tagInfo); + } + onTagDiscovered(tagInfo); + + // writeNoException + reply.writeInt(0); + break; + } + default: { + + return super.onRemoteRequest(code, data, reply, option); + } + } + return true; + } + + @Override + public IRemoteObject asObject() { + return this; + } + + @Override + public void onTagDiscovered(TagInfo tagInfo) { + if (callback != null) { + callback.onTagDiscovered(tagInfo); + } + } + } + + private UsbDevicePipeController(Context context) { + mUsbDevicePipeControllerProxy = UsbDevicePipeControllerProxy.getInstance(); + mContext = context; + } + + /** + * Obtains a singleton instance of the {@code NfcController} class. + * + *

If no singleton instance is available, a singleton instance will be created. + * + * @param context Indicates the application context. + * @return Returns a singleton instance. + * @throws IllegalArgumentException if the caller is missing required context. + * @since 1 + */ + public static synchronized UsbDevicePipeController getInstance(Context context) throws IllegalArgumentException { + if (sUsbDevicePipeController == null) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + sUsbDevicePipeController = new UsbDevicePipeController(context.getApplicationContext()); + } + return sUsbDevicePipeController; + } + + /** + * get the context of application + * + * @return the context of application + * @hide + */ + public Context getContext() { + return mContext; + } +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/USBEndpoint.java b/interfaces/kits/java/ohos/usb/USBEndpoint.java new file mode 100644 index 00000000..838d52cc --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBEndpoint.java @@ -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. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Get endpoint information about a USB device. + * + *

When using this class, a USB device is attached to a USB host. According to the USB protocol specifications, + * a device contains one or more configurations, a configuration contains one or more interfaces, and an interface + * contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBEndpoint { + private int address; + + private int attributes; + + private int direction; + + private int number; + + private int interval; + + private int maxPacketSize; + + private int type; + + /** + * Creates a {@code USBEndpoint} instance. + * + * @param address Indicates the USB endpoint address, which consists of the endpoint ID and data transfer direction. + * @param attributes Indicates USB endpoint attributes, such as the data transfer type. + * @param direction Indicates the USB endpoint direction. Value 0 indicates OUT, and value 1 indicates IN. + * @param number Indicates the USB endpoint number, which uniquely identifies a USB endpoint on a USB device. + * @param interval Indicates the polling interval of the USB endpoint during data transfer. + * @param maxPacketSize Indicates the maximum packet size of the USB endpoint, that is, the maximum size of packets + * that can be received or transmitted by the endpoint after it is activated. + * @param type Indicates the USB endpoint type. + * + * @since 5 + */ + public USBEndpoint(int address, int attributes, int direction, int number, int interval, int maxPacketSize, + int type) { + this.address = address; + this.attributes = attributes; + this.direction = direction; + this.number = number; + this.interval = interval; + this.maxPacketSize = maxPacketSize; + this.type = type; + } + + /** + * Get the endpoint address. + * + * @return Returns the endpoint address. + * @since 5 + */ + public int getAddress() { + return address; + } + + /** + * Get the endpoint attributes. + * + * @return Returns the endpoint attributes. + * @since 5 + */ + public int getAttributes() { + return attributes; + } + + /** + * Get the endpoint direction. + * + * @return Returns the endpoint direction. + * @since 5 + */ + public int getDirection() { + return direction; + } + + /** + * Get the endpoint number. + * + * @return Returns the endpoint number. + * @since 5 + */ + public int getEndpointNumber() { + return number; + } + + /** + * Get the endpoint interval. + * + * @return Returns the endpoint interval, in ms. + * @since 5 + */ + public int getInterval() { + return interval; + } + + /** + * Get the maximum packet size of this endpoint. + * + * @return Returns the maximum packet size. + * @since 5 + */ + public int getMaxPacketSize() { + return maxPacketSize; + } + + /** + * Get the endpoint type. + * + * @return Returns the endpoint type. + * @since 5 + */ + public int getType() { + return type; + } + + @Override + public String toString() { + return new StringBuilder( + "USBEndpoint[address=" + address + ", attributes=" + attributes + ", direction=" + direction + ", number=" + + number + ", interval=" + interval + ", maxPacketSize=" + maxPacketSize + ", type=" + type + + "]").toString(); + } +} + + diff --git a/interfaces/kits/java/ohos/usb/USBInterface.java b/interfaces/kits/java/ohos/usb/USBInterface.java new file mode 100644 index 00000000..8034935f --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBInterface.java @@ -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. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Get interface and endpoint information about a USB device. + * + *

+ * When using this class, a USB device is attached to a USB host. According to + * the USB protocol specifications, a device contains one or more + * configurations, a configuration contains one or more interfaces, and an + * interface contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBInterface { + private final int id; + + private final int alternateSetting; + + private final String name; + + private final int classType; + + private final int subclass; + + private final int protocol; + + private USBEndpoint[] endpoints; + + /** + * Creates a {@code USBInterface} object. + * + * @param id Indicates the ID of an interface. + * @param alternateSetting Indicates the alternative configuration of the interface. + * @param name Indicates the interface name. + * @param class Indicates the interface class. + * @param subClass Indicates the interface subclass. + * @param protocol Indicates the protocol supported by the interface. + * + * @since 5 + */ + public USBInterface(int id, int alternateSetting, String name, int Class, int subClass, int protocol) { + this.id = id; + this.alternateSetting = alternateSetting; + this.name = name; + this.classType = Class; + this.subclass = subClass; + this.protocol = protocol; + } + + /** + * Get the {@code AlternateSetting} field of a USB interface. + * + * @return Returns the {@code AlternateSetting} field. + * @since 5 + */ + public int getAlternateSetting() { + return alternateSetting; + } + + /** + * Get the {@code localId} field of a USB interface. + * + * @return Returns the {@code InterfaceId} field. + * @since 5 + */ + public int getId() { + return id; + } + + /** + * Get the {@code InterfaceClass} field of a USB interface. + * + * @return Returns the {@code InterfaceClass} field. + * @since 5 + */ + public int getInterfaceClass() { + return classType; + } + + /** + * Get the {@code InterfaceProtocol} field of a USB interface. + * + * @return Returns the {@code InterfaceProtocol} field. + * @since 5 + */ + public int getInterfaceProtocol() { + return protocol; + } + + /** + * Get the {@code InterfaceSubclass} field of a USB interface. + * + * @return Returns the {@code InterfaceSubclass} field. + * @since 5 + */ + public int getInterfaceSubclass() { + return subclass; + } + + /** + * Get the {@code localName} field of a USB interface. + * + * @return Returns the {@code InterfaceName} field. + * @since 5 + */ + public String getName() { + return name; + } + + /** + * Get a {@code USBEndpoint} instance of this interface by index. + * + * @param index Indicates the endpoint index. + * @return Returns the {@code USBEndpoint} instance. + */ + public USBEndpoint getEndpoint(int index) { + if (endpoints == null || index < 0 || index >= endpoints.length) { + return null; + } + return endpoints[index]; + } + + /** + * Get the number of endpoints. + * + * @return Returns the number of endpoints. + * @since 5 + */ + public int getEndpointCount() { + if (endpoints == null) { + return 0; + } + return endpoints.length; + } + + /** + * Sets the endpoints list for a local {@code USBEndpoint} object. + * + * @param endpoints Indicates the endpoints of the interface. + * @since 5 + */ + public void setEndpoints(USBEndpoint[] endpoints) { + this.endpoints = endpoints; + } + + @Override + public String toString() { + return new StringBuilder( + "USBInterface[id=" + id + ", alternateSetting=" + alternateSetting + ", name=" + name + ", class=" + + classType + ", subclass=" + subclass + ", protocol=" + protocol + "]").toString(); + } +} diff --git a/interfaces/kits/java/ohos/usb/USBLoggerFactory.java b/interfaces/kits/java/ohos/usb/USBLoggerFactory.java new file mode 100644 index 00000000..c9413b64 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBLoggerFactory.java @@ -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. + */ + +package ohos.usb; + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; + +/** + * An USB logger factory class + * + * @since 5 + * {@hide} + */ + +public class USBLoggerFactory { + private static final int DOMAIN = 0xD002A00; + + private static final String DEFAULT_TAG = "UsbService"; + + private USBLoggerFactory() { + } + + public static HiLogLabel getHilogLabel(String tag) { + if (tag == null || tag.isEmpty()) { + return USBLoggerFactory.getHilogLabel(); + } + return new HiLogLabel(HiLog.LOG_CORE, USBLoggerFactory.DOMAIN, tag); + } + + public static HiLogLabel getHilogLabel() { + return new HiLogLabel(HiLog.LOG_CORE, USBLoggerFactory.DOMAIN, DEFAULT_TAG); + } +} diff --git a/interfaces/kits/java/ohos/usb/USBPort.java b/interfaces/kits/java/ohos/usb/USBPort.java new file mode 100644 index 00000000..2a99499d --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBPort.java @@ -0,0 +1,4 @@ +package ohos.usb; + +public class USBPort { +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/USBRequest.java b/interfaces/kits/java/ohos/usb/USBRequest.java new file mode 100644 index 00000000..926f8ea5 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBRequest.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import java.nio.ByteBuffer; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Implements bulk transfer of data and control messages between USB devices. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBRequest { + private Object clientData; + + + public USBRequest() { + + } + + /** + * Aborts a pending queue operation. + */ + public void abort() { + native_abort(); + } + + /** + * Frees all resources related to this request. + */ + public void free() { + native_free(); + } + + /** + * Initializes a specified endpoint for data transfer. + * + * @param connection Indicates a {@code USBDevicePipe} instance. + * @param ep Indicates an instance of the {@code USBEndpoint} class. + * @return Returns {@code true} if the initialization is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean initialize(USBDevicePipe connection, USBEndpoint ep) { + return native_initialize(connection, ep); + } + + /** + * Transfers data on the requested endpoint, and queues the request. + * + * @param buffer Indicates the buffer from which data is to be transferred. + * @return Returns {@code true} if the data transfer is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean queue(ByteBuffer buffer) { + return native_queue(buffer); + } + + /** + * Transfers data on the requested endpoint, and queues the request. + * + * @param buffer Indicates the buffer from which data is to be transferred. + * @param length Indicates the length of buffer. + * @return Returns {@code true} if the data transfer is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean queue(ByteBuffer buffer, int length) { + return native_queue(buffer, length); + } + + /** + * Dequeues a request to send or receive data on its endpoint. + * + * @param useBufferOverflowInsteadOfIllegalArg Specifies whether to replace the illegal parameter + * with a buffer overflow. + * @since 5 + */ + public void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) { + native_dequeue(useBufferOverflowInsteadOfIllegalArg); + } + + /** + * Sets client data of the {@code USBRequst} instance. + * + * @param data The client data to be set. + * @since 5 + */ + public void setClientData(Object data) { + native_set_client_data(data); + } + + /** + * Gets client data of the {@code USBRequst} instance. + * + * @since 5 + * @return Returns the client data. + */ + public Object getClientData() { + return clientData; + } + + private native void native_abort(); + + private native void native_free(); + + private native boolean native_initialize(USBDevicePipe connection, USBEndpoint ep); + + private native boolean native_queue(ByteBuffer buffer); + + private native boolean native_queue(ByteBuffer buffer, int length); + + private native void native_set_client_data(Object data); + + private native void native_dequeue(boolean useBufferOverflowInsteadOfIllegalArg); +} diff --git a/interfaces/kits/java/ohos/usb/UsbCoreController.java b/interfaces/kits/java/ohos/usb/UsbCoreController.java new file mode 100644 index 00000000..e2b32a88 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbCoreController.java @@ -0,0 +1,142 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.aafwk.ability.Lifecycle; +import ohos.app.Context; +import ohos.event.intentagent.IntentAgent; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.SystemCap; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; +import ohos.nfc.tag.TagInfo; + +import java.util.List; + +@SystemCap("SystemCapability.Communication.USB") +public class UsbCoreController { + + private static UsbCoreController sUsbCoreController; + private UsbCoreControllerProxy mUsbCoreControllerProxy; + private Context mContext; + + /** + * A callback to be invoked when the system finds a tag while the foreground page is operating in reader mode. + * + */ + public interface ReaderModeCallback extends IRemoteBroker { + /** + * Indicates the transaction code of the callback specific to inter-process communication (IPC). + */ + int TRANSACTION_ON_CALLBACK = 1; + + /** + * Called when a tag is discovered. + * + * @param tagInfo Indicates information of the discovered tag. + * @since 4 + */ + void onTagDiscovered(TagInfo tagInfo); + } + + /** + * Provides ReaderModeCallback for communicate with remote. + * + * @since 4 + */ + public class ReaderModeCallbackStub extends RemoteObject implements ReaderModeCallback { + private ReaderModeCallback callback; + + public ReaderModeCallbackStub(ReaderModeCallback callback) { + super(); + this.callback = callback; + } + + private void readInterfaceToken(Parcel data) { + data.readInt(); + data.readInt(); + data.readString(); + } + + @Override + public boolean onRemoteRequest( + int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { + HiLog.debug(LABEL, "call ReaderModeCallbackStub's onTransact"); + + switch (code) { + case TRANSACTION_ON_CALLBACK: { + readInterfaceToken(data); + + TagInfo tagInfo = new TagInfo(null, null, null, 0); + if (tagInfo instanceof Sequenceable) { + data.readSequenceable((Sequenceable) tagInfo); + } + onTagDiscovered(tagInfo); + + // writeNoException + reply.writeInt(0); + break; + } + default: { + + return super.onRemoteRequest(code, data, reply, option); + } + } + return true; + } + + @Override + public IRemoteObject asObject() { + return this; + } + + @Override + public void onTagDiscovered(TagInfo tagInfo) { + if (callback != null) { + callback.onTagDiscovered(tagInfo); + } + } + } + + private UsbCoreController(Context context) { + mUsbCoreControllerProxy = UsbCoreControllerProxy.getInstance(); + mContext = context; + } + + /** + * Obtains a singleton instance of the {@code NfcController} class. + * + *

If no singleton instance is available, a singleton instance will be created. + * + * @param context Indicates the application context. + * @return Returns a singleton instance. + * @throws IllegalArgumentException if the caller is missing required context. + * @since 1 + */ + public static synchronized UsbCoreController getInstance(Context context) throws IllegalArgumentException { + if (sUsbCoreController == null) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + sUsbCoreController = new UsbCoreController(context.getApplicationContext()); + } + return sUsbCoreController; + } + + /** + * get the context of application + * + * @return the context of application + * @hide + */ + public Context getContext() { + return mContext; + } +} diff --git a/interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java b/interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java new file mode 100644 index 00000000..d356d016 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java @@ -0,0 +1,414 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.interwork.utils.PacMapEx; +import ohos.usb.UsbCoreController.ReaderModeCallback; +import ohos.usb.UsbCoreController.ReaderModeCallbackStub; +import ohos.rpc.IRemoteObject; +import ohos.rpc.IRemoteObject.DeathRecipient; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.safwk.java.SystemAbilityDefinition; + +import java.util.List; + +public class UsbCoreControllerProxy implements IUsbCoreController { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE,UsbKitsUtils.USB_DOMAIN_ID, "UsbCoreControllerProxy"); + private static final String USB_CORE_CONTROLLER = "ohos.usb.IUSBCoreController"; + private static UsbCoreControllerProxy sUsbCoreControllerProxy; + private final Object mRemoteLock = new Object(); + private IRemoteObject mRemoteObject; + + private UsbCoreControllerProxy() { + + } + + /** + * Gets a {@cod UsbControllerProxy} instance. + * + * @return Returns the instance of UsbControllerProxy. + */ + public static synchronized UsbCoreControllerProxy getInstance() { + if (sUsbCoreControllerProxy == null) { + sUsbCoreControllerProxy = new UsbCoreControllerProxy(); + } + return sUsbCoreControllerProxy; + } + + @Override + public IRemoteObject asObject() { + if (mRemoteObject != null) { + return mRemoteObject; + } + synchronized (mRemoteLock) { + mRemoteObject = SysAbilityManager.getSysAbility(SystemAbilityDefinition.NFC_MANAGER_SYS_ABILITY_ID); + if (mRemoteObject != null) { + mRemoteObject.addDeathRecipient(new UsbCoreControllerDeathRecipient(), 0); + HiLog.info(LABEL, "Get UsbManagerService completed."); + } else { + HiLog.error(LABEL, "getSysAbility(UsbManagerService) failed."); + } + return mRemoteObject; + } + } + + @Override + public HashMap getDevices() throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(1, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "getDevices call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + public USBDevicePipe connectDevice(USBDevice device) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + boolean hasRight(USBDevice device) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void requestRight(USBDevice device, String intentName) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + String usbFunctionsToString(long functions) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + long usbFunctionsFromString(String functions) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + String getCurrentFunctions() throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setCurrentFunctions(long functions) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setCurrentFunction(String functions, boolean usbDataUnlocked) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setHdcEnabled(boolean enable) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void addFunction(String functions, String function) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void removeFunction(String functions, String function) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setPortRoles(int powerRole,int dataRole) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + UsbPortStatus getPortStatus(USBPort port) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + // Implementation of IPC Death Recipient. + private class UsbCoreControllerDeathRecipient implements DeathRecipient { + @Override + public void onRemoteDied() { + HiLog.warn(LABEL, "UsbCoreControllerDeathRecipient::onRemoteDied."); + setRemoteObject(null); + } + } + + private void setRemoteObject(IRemoteObject remoteObject) { + synchronized (mRemoteLock) { + mRemoteObject = remoteObject; + } + } +} diff --git a/interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java b/interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java new file mode 100644 index 00000000..9432ac91 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java @@ -0,0 +1,173 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.interwork.utils.PacMapEx; +import ohos.usb.UsbDevicePipeController.ReaderModeCallback; +import ohos.usb.UsbDevicePipeController.ReaderModeCallbackStub; +import ohos.rpc.IRemoteObject; +import ohos.rpc.IRemoteObject.DeathRecipient; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.safwk.java.SystemAbilityDefinition; + +import java.util.List; + +public class UsbDevicePipeControllerProxy implements IUsbDevicePipeController { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE,UsbKitsUtils.USB_DOMAIN_ID, "UsbDevicePipeControllerProxy"); + private static final String USB_DevicePipe_CONTROLLER = "ohos.usb.IUSBDevicePipeController"; + private static UsbDevicePipeControllerProxy sUsbDevicePipeControllerProxy; + private final Object mRemoteLock = new Object(); + private IRemoteObject mRemoteObject; + + private UsbDevicePipeControllerProxy() { + + } + + /** + * Gets a {@cod UsbControllerProxy} instance. + * + * @return Returns the instance of UsbControllerProxy. + */ + public static synchronized UsbDevicePipeControllerProxy getInstance() { + if (sUsbDevicePipeControllerProxy == null) { + sUsbDevicePipeControllerProxy = new UsbDevicePipeControllerProxy(); + } + return sUsbDevicePipeControllerProxy; + } + + @Override + public IRemoteObject asObject() { + if (mRemoteObject != null) { + return mRemoteObject; + } + synchronized (mRemoteLock) { + mRemoteObject = SysAbilityManager.getSysAbility(SystemAbilityDefinition.NFC_MANAGER_SYS_ABILITY_ID); + if (mRemoteObject != null) { + mRemoteObject.addDeathRecipient(new UsbDevicePipeControllerDeathRecipient(), 0); + HiLog.info(LABEL, "Get UsbManagerService completed."); + } else { + HiLog.error(LABEL, "getSysAbility(UsbManagerService) failed."); + } + return mRemoteObject; + } + } + + @Override + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int length, int timeout) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_DevicePipe_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(1, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "getDevices call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout) throws RemoteException { + + } + + @Override + boolean claimInterface(USBInterface interfaceObj, boolean force) throws RemoteException { + + } + + @Override + void close() throws RemoteException { + + } + + @Override + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int offset, int length, int timeout) throws RemoteException { + + } + + @Override + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) throws RemoteException { + + } + + @Override + int getFileDescriptor() throws RemoteException { + + } + + @Override + byte[] getRawDescriptors() throws RemoteException { + + } + + @Override + String getSerial() throws RemoteException { + + } + + @Override + boolean releaseInterface(USBInterface interfaceObj) throws RemoteException { + + } + + @Override + USBRequest requestWait(long timeout) throws TimeoutException, RemoteException{ + + } + + @Override + USBRequest requestWait() throws RemoteException { + + } + + @Override + boolean setConfiguration(USBConfig config) throws RemoteException { + + } + + @Override + boolean setInterface(USBInterface interfaceObj) throws RemoteException { + + } + + @Override + boolean openByInt(String name, int fd) throws RemoteException { + + } + + // Implementation of IPC Death Recipient. + private class UsbDevicePipeControllerDeathRecipient implements DeathRecipient { + @Override + public void onRemoteDied() { + HiLog.warn(LABEL, "UsbDevicePipeControllerDeathRecipient::onRemoteDied."); + setRemoteObject(null); + } + } + + private void setRemoteObject(IRemoteObject remoteObject) { + synchronized (mRemoteLock) { + mRemoteObject = remoteObject; + } + } +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/UsbKitsUtils.java b/interfaces/kits/java/ohos/usb/UsbKitsUtils.java new file mode 100644 index 00000000..b85024cd --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbKitsUtils.java @@ -0,0 +1,7 @@ +package ohos.usb; + +public class UsbKitsUtils { + + /** USB Domain ID. */ + public static final int USB_DOMAIN_ID = 0xD002900; +} diff --git a/interfaces/kits/java/ohos/usb/UsbPortStatus.java b/interfaces/kits/java/ohos/usb/UsbPortStatus.java new file mode 100644 index 00000000..c820c43d --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbPortStatus.java @@ -0,0 +1,4 @@ +package ohos.usb; + +public class UsbPortStatus { +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/UsbRequestController.java b/interfaces/kits/java/ohos/usb/UsbRequestController.java new file mode 100644 index 00000000..68d63bb9 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbRequestController.java @@ -0,0 +1,142 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.aafwk.ability.Lifecycle; +import ohos.app.Context; +import ohos.event.intentagent.IntentAgent; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.SystemCap; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; +import ohos.nfc.tag.TagInfo; + +import java.util.List; + +@SystemCap("SystemCapability.Communication.USB") +public class UsbRequestController { + + private static UsbRequestController sUsbRequestController; + private UsbRequestControllerProxy mUsbRequestControllerProxy; + private Context mContext; + + /** + * A callback to be invoked when the system finds a tag while the foreground page is operating in reader mode. + * + */ + public interface ReaderModeCallback extends IRemoteBroker { + /** + * Indicates the transaction code of the callback specific to inter-process communication (IPC). + */ + int TRANSACTION_ON_CALLBACK = 1; + + /** + * Called when a tag is discovered. + * + * @param tagInfo Indicates information of the discovered tag. + * @since 4 + */ + void onTagDiscovered(TagInfo tagInfo); + } + + /** + * Provides ReaderModeCallback for communicate with remote. + * + * @since 4 + */ + public class ReaderModeCallbackStub extends RemoteObject implements ReaderModeCallback { + private ReaderModeCallback callback; + + public ReaderModeCallbackStub(ReaderModeCallback callback) { + super(); + this.callback = callback; + } + + private void readInterfaceToken(Parcel data) { + data.readInt(); + data.readInt(); + data.readString(); + } + + @Override + public boolean onRemoteRequest( + int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { + HiLog.debug(LABEL, "call ReaderModeCallbackStub's onTransact"); + + switch (code) { + case TRANSACTION_ON_CALLBACK: { + readInterfaceToken(data); + + TagInfo tagInfo = new TagInfo(null, null, null, 0); + if (tagInfo instanceof Sequenceable) { + data.readSequenceable((Sequenceable) tagInfo); + } + onTagDiscovered(tagInfo); + + // writeNoException + reply.writeInt(0); + break; + } + default: { + + return super.onRemoteRequest(code, data, reply, option); + } + } + return true; + } + + @Override + public IRemoteObject asObject() { + return this; + } + + @Override + public void onTagDiscovered(TagInfo tagInfo) { + if (callback != null) { + callback.onTagDiscovered(tagInfo); + } + } + } + + private UsbRequestController(Context context) { + mUsbRequestControllerProxy = UsbRequestControllerProxy.getInstance(); + mContext = context; + } + + /** + * Obtains a singleton instance of the {@code NfcController} class. + * + *

If no singleton instance is available, a singleton instance will be created. + * + * @param context Indicates the application context. + * @return Returns a singleton instance. + * @throws IllegalArgumentException if the caller is missing required context. + * @since 1 + */ + public static synchronized UsbRequestController getInstance(Context context) throws IllegalArgumentException { + if (sUsbRequestController == null) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + sUsbRequestController = new UsbRequestController(context.getApplicationContext()); + } + return sUsbRequestController; + } + + /** + * get the context of application + * + * @return the context of application + * @hide + */ + public Context getContext() { + return mContext; + } +} diff --git a/interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java b/interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java new file mode 100644 index 00000000..27a88791 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java @@ -0,0 +1,134 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.interwork.utils.PacMapEx; +import ohos.usb.UsbRequestController.ReaderModeCallback; +import ohos.usb.UsbRequestController.ReaderModeCallbackStub; +import ohos.rpc.IRemoteObject; +import ohos.rpc.IRemoteObject.DeathRecipient; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.safwk.java.SystemAbilityDefinition; + +import java.util.List; + +public class UsbRequestControllerProxy implements IUsbRequestController { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE,UsbKitsUtils.USB_DOMAIN_ID, "UsbRequestControllerProxy"); + private static final String USB_Request_CONTROLLER = "ohos.usb.IUSBRequestController"; + private static UsbRequestControllerProxy sUsbRequestControllerProxy; + private final Object mRemoteLock = new Object(); + private IRemoteObject mRemoteObject; + + private UsbRequestControllerProxy() { + + } + + /** + * Gets a {@cod UsbControllerProxy} instance. + * + * @return Returns the instance of UsbControllerProxy. + */ + public static synchronized UsbRequestControllerProxy getInstance() { + if (sUsbRequestControllerProxy == null) { + sUsbRequestControllerProxy = new UsbRequestControllerProxy(); + } + return sUsbRequestControllerProxy; + } + + @Override + public IRemoteObject asObject() { + if (mRemoteObject != null) { + return mRemoteObject; + } + synchronized (mRemoteLock) { + mRemoteObject = SysAbilityManager.getSysAbility(SystemAbilityDefinition.NFC_MANAGER_SYS_ABILITY_ID); + if (mRemoteObject != null) { + mRemoteObject.addDeathRecipient(new UsbRequestControllerDeathRecipient(), 0); + HiLog.info(LABEL, "Get UsbManagerService completed."); + } else { + HiLog.error(LABEL, "getSysAbility(UsbManagerService) failed."); + } + return mRemoteObject; + } + } + + @Override + void abort() throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(1, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "getDevices call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void free() throws RemoteException { + + } + + @Override + boolean initialize(USBDevicePipe connection, USBEndpoint ep) throws RemoteException { + + } + + @Override + boolean queue(ByteBuffer buffer) throws RemoteException { + + } + + @Override + boolean queue(ByteBuffer buffer, int length) throws RemoteException { + + } + + @Override + void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) throws RemoteException { + + } + + @Override + void setClientData(Object data) throws RemoteException { + + } + + + // Implementation of IPC Death Recipient. + private class UsbRequestControllerDeathRecipient implements DeathRecipient { + @Override + public void onRemoteDied() { + HiLog.warn(LABEL, "UsbRequestControllerDeathRecipient::onRemoteDied."); + setRemoteObject(null); + } + } + + private void setRemoteObject(IRemoteObject remoteObject) { + synchronized (mRemoteLock) { + mRemoteObject = remoteObject; + } + } +} diff --git a/interfaces/kits/java/ohos/usb/package-info.java b/interfaces/kits/java/ohos/usb/package-info.java new file mode 100644 index 00000000..f7a002e0 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/package-info.java @@ -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. + */ + +/** + * Provides basic USB communication capabilities for other peripherals and devices running OHOS. + * + *

The basic USB communication capabilities include control transfer and bulk transfer. + * + * @since 5 + */ + +package ohos.usb; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.usb.d.ts b/interfaces/kits/js/@ohos.usb.d.ts new file mode 100644 index 00000000..7d3eb2cb --- /dev/null +++ b/interfaces/kits/js/@ohos.usb.d.ts @@ -0,0 +1,789 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare namespace usb { + /** + * 获取USB服务版本号,测试用 + * + * @return USB服务当前的版本号. + * @since 8 + */ + function getVersion(): string; + + /* usb core functions begin */ + /** + * 获取USB设备列表 + * + * @return 设备信息{@link USBDevice}列表. + * @since 8 + */ + function getDevices(): Array>; + + /** + * 根据{@link getDevices()}返回的设备信息打开USB设备 + * + * @param device 设备信息,{@link getDevices()}返回的列表中的一个设备信息 + * @return 指定的传输通道 {@link USBDevicePipe} 对象. + * @since 8 + */ + function connectDevice(device: USBDevice): Readonly; + + /** + * 判断是否有权访问设备 + * + * @param deviceName 设备名称,{@link USBDevice.name} + * @return true 有权限, false 没有权限 + * @since 8 + */ + function hasRight(deviceName: string): boolean; + + /** + * 请求给定软件包的临时权限以访问设备 + * + * @param deviceName 设备名称,{@link USBDevice.name} + * @return true 请求权限成功, false 请求权限失败 + * @since 8 + */ + function requestRight(deviceName: string): Promise; + + /** + * 将给定的功能列表描述字符串转换为功能列表的数字组合掩码 + * + * @param funcs 支持的功能列表描述符 + * @return 功能列表的数字组合掩码 + * @systemapi + * @since 8 + */ + function usbFunctionsFromString(funcs: string): number; + + /** + * 将给定的功能列表的数字组合掩码转换为功能列表描述字符串 + * + * @param funcs 支持的功能列表的数字组合掩码 + * @return 支持的功能列表描述字符串 + * @systemapi + * @since 8 + */ + function usbFunctionsToString(funcs: FunctionType): string; + + /** + * 在设备模式下设置当前的USB功能列表 + * + * @param funcs 设置支持的功能列表的数字组合掩码{@link FunctionType} + * @return true 设置成功, false 设置失败 + * @systemapi + * @since 8 + */ + function setCurrentFunctions(funcs: FunctionType): Promise; + /** + * 获取设备模式下的当前USB功能列表的数字组合掩码 + * + * @return 支持的功能列表的数字组合掩码{@link FunctionType} + * @systemapi + * @since 8 + */ + function getCurrentFunctions(): FunctionType; + + /* usb port functions begin */ + /** + * 获取物理USB端口描述信息{@link USBPort}列表 + * + * @return {@link USBPort}列表 + * @systemapi + * @since 8 + */ + function getPorts(): Array; + + /** + * 获取指定的端口{@link USBPort}支持的模式列表的组合掩码 + * + * @return 支持的模式列表的组合掩码{@link PortModeType} + * @systemapi + * @since 8 + */ + function getSupportedModes(portId: number): PortModeType; + + /** + * 设置指定的端口{@link USBPort}支持的角色模式,包含充电角色、数据传输角色 + * + * @param portId 端口的唯一标识 + * @param powerRole 充电的角色{@link PowerRoleType} + * @param dataRole 数据传输的角色{@link DataRoleType} + * @return 支持的模式 + * @systemapi + * @since 8 + */ + function setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise; + + /* usb pipe functions begin */ + /** + * 获取接口 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param iface 用于确定需要获取接口的索引 {@link USBInterface}. + * @param force 是否强制获取 + * @return 成功:0;失败:错误码 + * @since 8 + */ + function claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number; + /** + * 释放接口 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param iface 用于确定需要释放接口的索引 {@link USBInterface}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number; + /** + * 设置设备配置 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param config 用于确定需要设置配置的索引 {@link USBConfig}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function setConfiguration(pipe: USBDevicePipe, config: USBConfig): number; + /** + * 设置设备接口 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param iface 用于确定需要设置接口的索引 {@link USBInterface}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function setInterface(pipe: USBDevicePipe, iface: USBInterface): number; + /** + * 获取原始的USB描述符 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @return 返回获取的原始数据 + * @since 8 + */ + function getRawDescriptor(pipe: USBDevicePipe): Uint8Array; + /** + * 获取文件描述符 + * + * @param pipe 用于确定设备 {@link USBDevicePipe}. + * @return 返回设备对应的文件描述符 + * @since 8 + */ + function getFileDescriptor(pipe: USBDevicePipe): number; + /** + * 控制传输 + * + * @param pipe 用于确定设备 {@link USBDevicePipe}. + * @param contrlparam 控制传输参数 + * @param timeout 超时时间,可选参数,默认为0不超时 + * @return 传输或接收到的数据块大小,异常返回-1 + * @since 8 + */ + function controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise; + + /** + * 批量传输 + * + * @param pipe 用于确定设备 {@link USBDevicePipe}. + * @param endpoint 用于确定传输的端口 {@link USBEndpoint}. + * @param buffer 用于写入或读取的缓冲区 + * @param timeout 超时时间,可选参数,默认为0不超时 + * @return 传输或接收到的数据块大小,异常返回-1 + * @since 8 + */ + function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, + timeout?: number): Promise; + + /** + * 关闭USBDevicePipe + * + * @param pipe 用于确定pipe {@link USBDevicePipe}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function closePipe(pipe: USBDevicePipe): number; + + /** + * 通过USB发送和接收数据的端口。通过{@link USBInterface}获取。 + * + * @since 8 + */ + interface USBEndpoint { + /** + * 端点地址 + * + * @since 8 + */ + address: number; + + /** + * 端点属性 + * + * @since 8 + */ + attributes: number; + + /** + * 端点间隔 + * + * @since 8 + */ + interval: number; + + /** + * 端点最大数据包大小 + * + * @since 8 + */ + maxPacketSize: number; + + /** + * 端点的方向。 + * + * @since 8 + */ + direction: USBRequestDirection; + + /** + * 端点号 + * + * @since 8 + */ + number: number; + + /** + * 端点类型 + * + * @since 8 + */ + type: number; + + /** + * 端点所属的接口的唯一标识{@link USBInterface.id} + * + * @since 8 + */ + interfaceId: number; + } + + + /** + * 一个{@link USBConfig}中可以含有多个interface,每个interface提供一个功能。 + * + * @since 8 + */ + interface USBInterface { + /** + * 接口的唯一标识 + * + * @since 8 + */ + id: number; + + /** + * 接口的协议 + * + * @since 8 + */ + protocol: number; + + /** + * 设备类型 + * + * @since 8 + */ + clazz: number; + + /** + * 设备子类 + * + * @since 8 + */ + subClass: number; + + /** + *在同一个接口中的多个描述符中进行切换设置 + * + * @since 8 + */ + alternateSetting: number; + + /** + * 接口名称 + * + * @since 8 + */ + name: string; + + /** + * 当前接口所包含的端点{@link USBEndpoint} + * + * @since 8 + */ + endpoints: Array; + } + + /** + * USB配置,一个{@link USBDevice}中可以含有多个配置。 + * + * @since 8 + */ + interface USBConfig { + /** + * 配置的唯一标识 + * + * @since 8 + * + * + */ + id: number; + + /** + * 配置的属性 + * + * @since 8 + */ + attributes: number; + + /** + * 最大功耗,以毫安为单位 + * + * @since 8 + */ + maxPower: number; + + /** + * 配置的名称,可以为空 + * + * @since 8 + */ + name: string; + + /** + * 检查当前配置是否支持远程唤醒 + * + * @since 8 + */ + isRemoteWakeup: boolean; + + /** + * 检查当前配置是否支持独立电源 + * + * @since 8 + */ + isSelfPowered: boolean; + + /** + * 配置支持的接口属性{@link USBInterface} + * + * @since 8 + */ + interfaces: Array; + } + + /** + * USB设备信息。 + * + * @since 8 + */ + interface USBDevice { + /** + * 总线地址 + * + * @since 8 + */ + busNum: number; + /** + * 设备地址 + * + * @since 8 + */ + devAddress: number; + /** + * 序列号 + * + * @since 8 + */ + serial: string; + /** + * 设备名字 + * + * @since 8 + */ + name: string; + /** + * 产商信息 + * + * @since 8 + */ + manufacturerName: string; + /** + * 产品信息 + * + * @since 8 + */ + productName: string; + /** + * 版本 + * + * @since 8 + */ + version: string; + /** + * 厂商ID + * + * @since 8 + */ + vendorId: number; + /** + * 产品ID + * + * @since 8 + */ + productId: number; + /** + * 设备类 + * + * @since 8 + */ + clazz: number; + /** + * 设备子类 + * + * @since 8 + */ + subClass: number; + /** + * 设备协议码 + * + * @since 8 + */ + protocol: number; + /** + * 设备配置描述符信息 {@link USBConfig}. + * + * @since 8 + */ + configs: Array; + } + + /** + * USB设备消息控制通道,用于确定设备 + * + * @since 8 + */ + interface USBDevicePipe { + /** + * 总线地址 + * + * @since 8 + */ + busNum: number; + /** + * 设备地址 + * + * @since 8 + */ + devAddress: number; + } + + /** + * 电源角色类型 + * + * @since 8 + */ + enum PowerRoleType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * 外部供电 + * + * @since 8 + */ + SOURCE, + /** + * 内部供电 + * + * @since 8 + */ + SINK + } + + /** + * 数据角色类型 + * + * @since 8 + */ + enum DataRoleType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * host模式,主设备模式 + * + * @since 8 + */ + HOST, + /** + * device模式,从设备模式 + * + * @since 8 + */ + DEVICE + } + + /** + * port模式类型 + * + * @since 8 + */ + enum PortModeType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * host 数据下行,对外提供电源 + * + * @since 8 + */ + DFP, + /** + * device 数据上行,需要外部供电 + * + * @since 8 + */ + UFP + } + + /** + * USB设备端口角色信息 + * + * @since 8 + */ + interface USBPortStatus { + /** + * 当前的USB模式 + * + * @since 8 + */ + currentMode: number; + + /** + * 当前设备充电模式 + * + * @since 8 + */ + currentPowerRole: number; + + /** + * 当前设备数据传输模式 + * + * @since 8 + */ + currentDataRole: number; + } + + /** + * USB设备端口信息 + * + * @since 8 + */ + interface USBPort { + /** + * USB端口信息唯一标识 + * + * @since 8 + */ + id: number; + + /** + * 当前端口支持的模式列表的组合掩码 + * + * @since 8 + */ + supportedModes: PortModeType; + + /** + * 当前端口角色信息 {@link USBPortStatus} + * + * @since 8 + */ + status: USBPortStatus; + } + + /** + * 控制传输参数 + * + * @since 8 + */ + interface USBControlParams { + /** + * 请求类型 + * + * @since 8 + */ + request: number; + /** + * 请求目标类型 + * + * @since 8 + */ + target: USBRequestTargetType; + /** + * 控制请求类型 + * + * @since 8 + */ + reqType: USBControlRequestType; + /** + * 请求参数 + * + * @since 8 + */ + value: number; + /** + * 根据请求参数value的不同有所不同 + * + * @since 8 + */ + index: number; + /** + * @用于写入或读取的缓冲区 + * @since 8 + */ + data: Uint8Array; + } + + /** + * 请求目标类型 + * + * @since 8 + */ + enum USBRequestTargetType { + /** + * 设备 + * + * @since 8 + */ + USB_REQUEST_TARGET_DEVICE = 0, + /** + * 接口 + * + * @since 8 + */ + USB_REQUEST_TARGET_INTERFACE, + /** + * 端点 + * + * @since 8 + */ + USB_REQUEST_TARGET_ENDPOINT, + /** + * 其他 + * + * @since 8 + */ + USB_REQUEST_TARGET_OTHER + } + + /** + * 控制请求类型 + * @since 8 + */ + enum USBControlRequestType { + /** + * 标准 + * + * @since 8 + */ + USB_REQUEST_TYPE_STANDARD = 0, + /** + * 类 + * + * @since 8 + */ + USB_REQUEST_TYPE_CLASS, + /** + * 厂商 + * + * @since 8 + */ + USB_REQUEST_TYPE_VENDOR + } + + /** + * 请求方向 + * @since 8 + */ + enum USBRequestDirection { + /** + * 写数据,主设备往从设备 + * + * @since 8 + */ + USB_REQUEST_DIR_TO_DEVICE = 0, + /** + * 读数据,从设备往主设备 + * + * @since 8 + */ + USB_REQUEST_DIR_FROM_DEVICE = 0x80 + } + + + /** + * function 模式 + * + * @since 8 + */ + enum FunctionType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * 串口设备 + * + * @since 8 + */ + ACM = 1, + /** + * 网口设备 + * + * @since 8 + */ + ECM = 2, + /** + * HDC设备 + * + * @since 8 + */ + HDC = 4 + } + +} + +export default usb; diff --git a/interfaces/kits/js/napi/BUILD.gn b/interfaces/kits/js/napi/BUILD.gn new file mode 100644 index 00000000..cc25288f --- /dev/null +++ b/interfaces/kits/js/napi/BUILD.gn @@ -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. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("usbnapi_private_config") { + include_dirs = [ + "//foundation/ace/napi/native_engine", + "//foundation/ace/napi/interfaces/kits", + "//utils/system/safwk/native/include", + "//third_party/node/src", + "//base/usbmgr/usb_manager/interfaces/innerkits/native/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include", + ] +} + +ohos_shared_library("usb") { + sources = [ "usb_info.cpp" ] + configs = [ + "${utils_path}:utils_config", + ":usbnapi_private_config", + ] + deps = [ + "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "//foundation/ace/napi:ace_napi", + "//utils/native/base:utils", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + + subsystem_name = "usb" + part_name = "usb_manager_native" +} diff --git a/interfaces/kits/js/napi/usb_async_context.h b/interfaces/kits/js/napi/usb_async_context.h new file mode 100644 index 00000000..3af6ae6d --- /dev/null +++ b/interfaces/kits/js/napi/usb_async_context.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "napi/native_api.h" +#include "napi/native_node_api.h" +#include "usb_device_pipe.h" +#include "usb_endpoint.h" +#include "usb_request.h" + +namespace OHOS { +namespace USB { + +struct USBAsyncContext { + napi_env env; + napi_async_work work; + + napi_deferred deferred; + napi_status status; +}; + +struct USBRightAsyncContext : USBAsyncContext { + std::string deviceName; + bool hasRight = false; +}; + +struct USBFunctionAsyncContext : USBAsyncContext { + int32_t functions; +}; + +struct USBPortRoleAsyncContext : USBAsyncContext { + int32_t portId; + int32_t powerRole; + int32_t dataRole; +}; + +struct USBControlTransferAsyncContext : USBAsyncContext { + USBDevicePipe pipe; + int32_t request; + int32_t target; + int32_t reqType; + int32_t directon; + int32_t value; + int32_t index; + uint8_t *buffer; + uint32_t bufferLength; + int32_t timeout = 0; +}; + +struct USBBulkTransferAsyncContext : USBAsyncContext { + uint8_t *buffer; + uint32_t bufferLength; + int32_t timeout = 0; + USBDevicePipe pipe; + USBEndpoint endpoint; +}; + +struct USBQueueAsyncContext : USBAsyncContext { + UsbRequest req; + uint8_t *buffer; + uint32_t bufferLength; +}; +} // namespace USB +} // namespace OHOS diff --git a/interfaces/kits/js/napi/usb_info.cpp b/interfaces/kits/js/napi/usb_info.cpp new file mode 100644 index 00000000..8ce73cbc --- /dev/null +++ b/interfaces/kits/js/napi/usb_info.cpp @@ -0,0 +1,1459 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 +#include +#include +#include "hilog_wrapper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "securec.h" +#include "usb_async_context.h" +#include "usb_device_pipe.h" +#include "usb_endpoint.h" +#include "usb_srv_client.h" + +using namespace OHOS; +using namespace OHOS::USB; +const int32_t MSEC_TIME = 1000; +const int32_t INDEX_0 = 0; +const int32_t INDEX_1 = 1; +const int32_t INDEX_2 = 2; +const int32_t INDEX_3 = 3; +const int32_t PARAM_COUNT_1 = 1; +const int32_t PARAM_COUNT_2 = 2; +const int32_t PARAM_COUNT_3 = 3; +const int32_t PARAM_COUNT_4 = 4; +const int32_t STR_DEFAULT_SIZE = 256; + +static void ParseUsbDevicePipe(napi_env env, napi_value &obj, USBDevicePipe &pip); + +static void JsValueToString(const napi_env &env, const napi_value &value, const int bufLen, std::string &target) +{ + char *buf = (char *)malloc(bufLen); + + if (buf == nullptr) { + USB_HILOGE(MODULE_JS_NAPI, "%{public}s nullptr js object to string malloc failed", __func__); + } + (void)memset_s(buf, bufLen, 0, bufLen); + size_t result = 0; + napi_get_value_string_utf8(env, value, buf, bufLen, &result); + + target = buf; + free(buf); + buf = nullptr; +} +static void JsObjectToString(const napi_env &env, + const napi_value &object, + const char *fieldStr, + const int bufLen, + std::string &fieldRef) +{ + if (bufLen <= 0) + return; + + bool hasProperty = false; + napi_has_named_property(env, object, fieldStr, &hasProperty); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + napi_typeof(env, field, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_string, "Wrong argument type. String expected."); + char *buf = (char *)malloc(bufLen); + if (buf == nullptr) { + USB_HILOGE(MODULE_JS_NAPI, "%{public}s nullptr js object to string malloc failed", __func__); + } + (void)memset_s(buf, bufLen, 0, bufLen); + size_t result = 0; + napi_get_value_string_utf8(env, field, buf, bufLen, &result); + fieldRef = buf; + free(buf); + buf = nullptr; + } else { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s js to str no property: %{public}s", __func__, fieldStr); + } +} + +static bool JsObjectGetProperty(const napi_env &env, const napi_value &object, const char *fieldStr, napi_value *value) +{ + bool hasProperty = false; + napi_has_named_property(env, object, fieldStr, &hasProperty); + if (hasProperty) { + napi_get_named_property(env, object, fieldStr, value); + } else { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s js object has no property: %{public}s", __func__, fieldStr); + } + return hasProperty; +} + +static void JsObjectToInt(const napi_env &env, const napi_value &object, const char *fieldStr, int &fieldRef) +{ + bool hasProperty = false; + napi_has_named_property(env, object, fieldStr, &hasProperty); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + napi_typeof(env, field, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, field, &fieldRef); + } else { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s js to int no property: %{public}s", __func__, fieldStr); + } +} + +static bool JsUint8ArrayParse(const napi_env &env, + const napi_value &object, + uint8_t **uint8Buffer, + size_t &bufferSize, + size_t &offset) +{ + bool isTypedArray = false; + if (napi_is_typedarray(env, object, &isTypedArray) != napi_ok || !isTypedArray) { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s invalid type", __func__); + return false; + } + + napi_typedarray_type type; + napi_value buffer; + + napi_status infoStatus = + napi_get_typedarray_info(env, object, &type, &bufferSize, (void **)uint8Buffer, &buffer, &offset); + if (infoStatus != napi_ok) { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s get typedarray info failed, status: %{public}d", __func__, infoStatus); + return false; + } + + if (type != napi_uint8_array) { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s not Uint8Array type: %{public}d", __func__, type); + return false; + } + + return true; +} + +static void ProcessPromise(napi_env env, USBAsyncContext *asyncContext, napi_value result) +{ + if (asyncContext->deferred) { + if (asyncContext->status == napi_ok) { + napi_resolve_deferred(env, asyncContext->deferred, result); + } else { + napi_reject_deferred(env, asyncContext->deferred, result); + } + } +} + +static void Uint8ArrayToJsValue(const napi_env &env, uint8_t *uint8Buffer, size_t bufferSize, napi_value &result) +{ + if (uint8Buffer == nullptr || bufferSize < 0) { + napi_get_undefined(env, &result); + return; + } + + uint8_t *nativeArraybuffer = new uint8_t[bufferSize]; + napi_value nativeValue = nullptr; + napi_create_arraybuffer(env, bufferSize, (void **)&nativeArraybuffer, &nativeValue); + memcpy_s(nativeArraybuffer, bufferSize, uint8Buffer, bufferSize); + napi_create_typedarray(env, napi_uint8_array, bufferSize, nativeValue, 0, &result); +} + +static void SetValueUtf8String(const napi_env &env, const char *fieldStr, const char *str, napi_value &result) +{ + napi_value value; + napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, fieldStr, value); +} + +static void SetValueInt32(const napi_env &env, const char *fieldStr, const int intValue, napi_value &result) +{ + napi_value value; + napi_create_int32(env, intValue, &value); + napi_set_named_property(env, result, fieldStr, value); +} + +static void SetValueBool(const napi_env &env, const char *fieldStr, const bool boolValue, napi_value &result) +{ + napi_value value; + napi_get_boolean(env, boolValue, &value); + napi_set_named_property(env, result, fieldStr, value); +} + +static void CreateUsbDevicePipe(napi_env env, napi_value &obj, const USBDevicePipe &pip) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "busNum", pip.GetBusNum(), obj); + SetValueInt32(env, "devAddress", pip.GetDevAddr(), obj); +} + +static void CtoJSUsbEndpoint(const napi_env &env, napi_value &obj, USBEndpoint &usbEndpoint) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "address", usbEndpoint.GetAddress(), obj); + SetValueInt32(env, "attributes", usbEndpoint.GetAttributes(), obj); + SetValueInt32(env, "interval", usbEndpoint.GetInterval(), obj); + SetValueInt32(env, "maxPacketSize", usbEndpoint.GetMaxPacketSize(), obj); + SetValueInt32(env, "direction", usbEndpoint.GetDirection(), obj); + SetValueInt32(env, "number", usbEndpoint.GetEndpointNumber(), obj); + SetValueInt32(env, "type", usbEndpoint.GetType(), obj); + SetValueInt32(env, "interfaceId", usbEndpoint.GetInterfaceId(), obj); +} + +static void CtoJSUsbInterface(const napi_env &env, napi_value &obj, UsbInterface &usbInterface) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "id", usbInterface.GetId(), obj); + SetValueInt32(env, "protocol", usbInterface.GetProtocol(), obj); + SetValueInt32(env, "clazz", usbInterface.GetClass(), obj); + SetValueInt32(env, "subclass", usbInterface.GetSubClass(), obj); + SetValueInt32(env, "alternateSetting", usbInterface.GetAlternateSetting(), obj); + SetValueUtf8String(env, "name", usbInterface.GetName().c_str(), obj); + napi_value arr; + napi_create_array(env, &arr); + for (int32_t i = 0; i < usbInterface.GetEndpointCount(); ++i) { + USBEndpoint usbEndpoint; + usbInterface.GetEndpoint(i, usbEndpoint); + napi_value obj; + CtoJSUsbEndpoint(env, obj, usbEndpoint); + napi_set_element(env, arr, i, obj); + } + napi_set_named_property(env, obj, "endpoints", arr); +} + +static void CtoJSUsbConfig(const napi_env &env, napi_value &obj, USBConfig &usbConfig) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "id", usbConfig.GetId(), obj); + SetValueInt32(env, "attributes", usbConfig.GetAttributes(), obj); + SetValueBool(env, "isRemoteWakeup", usbConfig.IsRemoteWakeup(), obj); + SetValueBool(env, "isSelfPowered", usbConfig.IsSelfPowered(), obj); + SetValueInt32(env, "maxPower", usbConfig.GetMaxPower(), obj); + SetValueUtf8String(env, "name", usbConfig.GetName().c_str(), obj); + napi_value arr; + napi_create_array(env, &arr); + for (int32_t i = 0; i < usbConfig.GetInterfaceCount(); ++i) { + UsbInterface usbInterface; + usbConfig.GetInterface(i, usbInterface); + napi_value obj; + CtoJSUsbInterface(env, obj, usbInterface); + napi_set_element(env, arr, i, obj); + } + napi_set_named_property(env, obj, "interfaces", arr); +} + +static void CtoJSUsbDevice(const napi_env &env, napi_value &obj, UsbDevice *usbDevice) +{ + napi_create_object(env, &obj); + SetValueUtf8String(env, "name", usbDevice->GetName().c_str(), obj); + SetValueUtf8String(env, "serial", usbDevice->GetmSerial().c_str(), obj); + SetValueUtf8String(env, "manufacturerName", usbDevice->GetManufacturerName().c_str(), obj); + SetValueUtf8String(env, "productName", usbDevice->GetProductName().c_str(), obj); + SetValueUtf8String(env, "version", usbDevice->GetVersion().c_str(), obj); + SetValueInt32(env, "vendorId", usbDevice->GetVendorId(), obj); + SetValueInt32(env, "productId", usbDevice->GetProductId(), obj); + SetValueInt32(env, "clazz", usbDevice->GetClass(), obj); + SetValueInt32(env, "subclass", usbDevice->GetSubclass(), obj); + SetValueInt32(env, "protocol", usbDevice->GetProtocol(), obj); + SetValueInt32(env, "devAddress", usbDevice->GetDevAddr(), obj); + SetValueInt32(env, "busNum", usbDevice->GetBusNum(), obj); + napi_value arr; + napi_create_array(env, &arr); + for (int32_t i = 0; i < usbDevice->GetConfigCount(); ++i) { + USBConfig usbConfig; + usbDevice->GetConfig(i, usbConfig); + napi_value obj; + CtoJSUsbConfig(env, obj, usbConfig); + napi_set_element(env, arr, i, obj); + } + napi_set_named_property(env, obj, "configs", arr); +} + +static UsbSrvClient &g_usbClient = UsbSrvClient::GetInstance(); + +/* ============================================= Parsers ============================================= */ +// js to c +static void ParseEndpointObj(napi_env env, napi_value endpointObj, USBEndpoint &ep) +{ + int32_t address, attributes, interval, maxPacketSize, interfaceId = 0; + JsObjectToInt(env, endpointObj, "address", address); + JsObjectToInt(env, endpointObj, "attributes", attributes); + JsObjectToInt(env, endpointObj, "interval", interval); + JsObjectToInt(env, endpointObj, "maxPacketSize", maxPacketSize); + JsObjectToInt(env, endpointObj, "interfaceId", interfaceId); + ep = USBEndpoint(address, attributes, interval, maxPacketSize); + ep.SetInterfaceId(interfaceId); +} + +static bool ParseEndpointsObjs(napi_env env, napi_value interfaceObj, std::vector &eps) +{ + // Get the array. + bool result = false; + napi_status status = napi_is_array(env, interfaceObj, &result); + if (result && status == napi_ok) { + napi_value endpointsObjs; + bool isGetObjSuccess = JsObjectGetProperty(env, interfaceObj, "endpoints", &endpointsObjs); + if (!isGetObjSuccess) { + return false; + } + + uint32_t endpointCount = 0; + status = napi_get_array_length(env, endpointsObjs, &endpointCount); + + for (uint32_t k = 0; k < endpointCount; ++k) { + napi_value endpointObj; + napi_status status = napi_get_element(env, endpointsObjs, k, &endpointObj); + if (status != napi_ok) { + return false; + } + USBEndpoint ep; + ParseEndpointObj(env, endpointObj, ep); + eps.push_back(ep); + } + } + + return false; +} + +struct PipeControlParam { + int32_t request; + int32_t target; + int32_t reqType; + int32_t value; + int32_t index; + uint8_t *data; + size_t dataLength; +}; + +static void ParsePipeControlParam(napi_env env, napi_value jsObj, PipeControlParam &controlParam) +{ + int32_t request, target, reqType, value, index = 0; + JsObjectToInt(env, jsObj, "request", request); + JsObjectToInt(env, jsObj, "target", target); + JsObjectToInt(env, jsObj, "reqType", reqType); + JsObjectToInt(env, jsObj, "value", value); + JsObjectToInt(env, jsObj, "index", index); + + napi_value dataValue; + JsObjectGetProperty(env, jsObj, "data", &dataValue); + + uint8_t *data = nullptr; + size_t dataLength = 0; + size_t offset = 0; + JsUint8ArrayParse(env, dataValue, &data, dataLength, offset); + controlParam.request = request; + controlParam.target = target; + controlParam.reqType = reqType; + controlParam.value = value; + controlParam.index = index; + controlParam.data = data; + controlParam.dataLength = dataLength; +} + +static void ParseInterfaceObj(napi_env env, napi_value interfaceObj, UsbInterface &interface) +{ + int32_t mId, mProtocol, mClass, mSubClass, mAlternateSetting = 0; + std::string mName; + JsObjectToInt(env, interfaceObj, "id", mId); + JsObjectToInt(env, interfaceObj, "protocol", mProtocol); + JsObjectToInt(env, interfaceObj, "clazz", mClass); + JsObjectToInt(env, interfaceObj, "subclass", mSubClass); + JsObjectToInt(env, interfaceObj, "alternateSetting", mAlternateSetting); + JsObjectToString(env, interfaceObj, "name", 32, mName); + std::vector eps; + ParseEndpointsObjs(env, interfaceObj, eps); + interface = UsbInterface(mId, mProtocol, mClass, mSubClass, mAlternateSetting, mName, eps); +} + +static bool ParseInterfacesObjs(napi_env env, napi_value configObj, std::vector &interfaces) +{ + bool result = false; + napi_status status = napi_is_array(env, configObj, &result); + if (result && status == napi_ok) { + napi_value interfacesObjs; + bool isGetObjSuccess = JsObjectGetProperty(env, configObj, "interfaces", &interfacesObjs); + if (!isGetObjSuccess) { + return false; + } + uint32_t interfaceCount = 0; + status = napi_get_array_length(env, interfacesObjs, &interfaceCount); + for (uint32_t i = 0; i < interfaceCount; ++i) { + napi_value interfaceObj; + napi_status status = napi_get_element(env, interfacesObjs, i, &interfaceObj); + if (status != napi_ok) { + return false; + } + UsbInterface interface; + ParseInterfaceObj(env, interfaceObj, interface); + interfaces.push_back(interface); + } + } + + return false; +} + +static void ParseConfigObj(napi_env env, napi_value configObj, USBConfig &config) +{ + int32_t id, attributes, maxPower = 0; + std::string name; + JsObjectToInt(env, configObj, "id", id); + JsObjectToInt(env, configObj, "attributes", attributes); + JsObjectToInt(env, configObj, "maxPower", maxPower); + JsObjectToString(env, configObj, "name", 32, name); + + std::vector interfaces; + ParseInterfacesObjs(env, configObj, interfaces); + config = USBConfig(id, attributes, name, maxPower, interfaces); +} + +static void ParseConfigsObjs(napi_env env, napi_value deviceObj, std::vector &configs) +{ + napi_value configsObj; + JsObjectGetProperty(env, deviceObj, "configs", &configsObj); + napi_valuetype valueType; + napi_typeof(env, configsObj, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_object, "Wrong argument type. object expected."); + + uint32_t configCount = 0; + napi_get_array_length(env, configsObj, &configCount); + for (uint32_t i = 0; i < configCount; ++i) { + napi_value configObj; + napi_get_element(env, configsObj, i, &configObj); + USBConfig config; + ParseConfigObj(env, configObj, config); + configs.push_back(config); + } +} + +static void ParseUsbDevicePipe(napi_env env, napi_value &obj, USBDevicePipe &pip) +{ + napi_valuetype valueType; + napi_typeof(env, obj, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_object, "Wrong argument type. object expected."); + + int32_t busNum = 0; + JsObjectToInt(env, obj, "busNum", busNum); + pip.SetBusNum((uint8_t)busNum); + int32_t devAddr = 0; + JsObjectToInt(env, obj, "devAddress", devAddr); + pip.SetDevAddr((uint8_t)devAddr); +} + +static long getTimeDiff(timeval startTime, timeval endTime) +{ + return (endTime.tv_sec - startTime.tv_sec) * MSEC_TIME + (endTime.tv_usec - startTime.tv_usec) / MSEC_TIME; +} + +/* ============================================= Usb Core ============================================= */ + +static napi_value CoreGetDevices(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + + std::vector deviceList; + int32_t ret = g_usbClient.GetDevices(deviceList); + napi_value result; + if (ret != ERR_OK) { + napi_get_undefined(env, &result); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, get device faild ret : %{public}d", __func__, ret); + return result; + } + + napi_create_array(env, &result); + int32_t i = 0; + for (auto &ent1 : deviceList) { + napi_value element; + napi_create_object(env, &element); + napi_value device; + CtoJSUsbDevice(env, device, &ent1); + napi_set_element(env, result, i, device); + ++i; + } + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreConnectDevice(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_value deviceObj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, deviceObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + UsbDevice dev; + std::string mName, mManufacturerName, mProductName, mVersion; + int32_t devAddr, busNum, mVendorId, mProductId, mClass, mSubclass, mProtocol = 0; + JsObjectToString(env, deviceObj, "name", 32, mName); /* manufacturer max length is 32 + '\0' */ + JsObjectToString(env, deviceObj, "manufacturerName", 32, + mManufacturerName); /* manufacturer max length is 32 + '\0' */ + JsObjectToString(env, deviceObj, "productName", 32, mProductName); + JsObjectToString(env, deviceObj, "version", 32, mVersion); + JsObjectToInt(env, deviceObj, "devAddress", devAddr); + JsObjectToInt(env, deviceObj, "busNum", busNum); + JsObjectToInt(env, deviceObj, "vendorId", mVendorId); + JsObjectToInt(env, deviceObj, "productId", mProductId); + JsObjectToInt(env, deviceObj, "clazz", mClass); + JsObjectToInt(env, deviceObj, "subclass", mSubclass); + JsObjectToInt(env, deviceObj, "protocol", mProtocol); + std::vector configs; + ParseConfigsObjs(env, deviceObj, configs); + dev = UsbDevice(mName, mManufacturerName, mProductName, mVersion, devAddr, busNum, mVendorId, mProductId, mClass, + mSubclass, mProtocol, configs); + USBDevicePipe pip; + int32_t ret = g_usbClient.OpenDevice(dev, pip); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms, ret : %{public}d", __func__, + getTimeDiff(start, end), ret); + napi_value pipObj = nullptr; + if (ret == ERR_OK) { + CreateUsbDevicePipe(env, pipObj, pip); + return pipObj; + } else if (ret == ERR_PERMISSION_DENIED) { + napi_throw_error(env, nullptr, "permission denied, need call requestRight to get permission"); + return pipObj; + } else { + napi_get_undefined(env, &pipObj); + return pipObj; + } +} + +static napi_value CoreHasRight(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value args[PARAM_COUNT_1] = {0}; + napi_value jsthis; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + + NAPI_ASSERT(env, type == napi_string, "Wrong argument type. String expected."); + + std::string deviceName; + JsValueToString(env, args[INDEX_0], STR_DEFAULT_SIZE, deviceName); + int32_t result = g_usbClient.HasRight(deviceName); + USB_HILOGD(MODULE_JS_NAPI, "client called result %{public}d", result); + + napi_value napiValue = nullptr; + napi_get_boolean(env, result == ERR_OK, &napiValue); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return napiValue; +} + +static napi_value CoreRequestRight(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value args[PARAM_COUNT_1] = {0}; + napi_value jsthis; + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + NAPI_ASSERT(env, type == napi_string, "Wrong argument type. String expected."); + std::string deviceName; + JsValueToString(env, args[INDEX_0], STR_DEFAULT_SIZE, deviceName); + + auto *asyncContext = new USBRightAsyncContext(); + asyncContext->env = env; + asyncContext->deviceName = deviceName; + + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "RequestRight", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBRightAsyncContext *asyncContext = (USBRightAsyncContext *)data; + int32_t ret = g_usbClient.RequestRight(asyncContext->deviceName); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call CoreRequestRight async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBRightAsyncContext *asyncContext = (USBRightAsyncContext *)data; + napi_value queryResult = nullptr; + napi_get_boolean(env, asyncContext->status == napi_ok, &queryResult); + + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreUsbFunctionsFromString(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_string, "Wrong argument type. String expected."); + + // get value string argument of napi converted. + std::string funcs; + JsValueToString(env, argv[INDEX_0], STR_DEFAULT_SIZE, funcs); + + int32_t numFuncs = g_usbClient.UsbFunctionsFromString(funcs); + + napi_value result; + napi_create_int32(env, numFuncs, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreUsbFunctionsToString(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. String expected."); + + int32_t funcs; + napi_get_value_int32(env, argv[INDEX_0], &funcs); + std::string strFuncs = g_usbClient.UsbFunctionsToString(funcs); + + napi_value result; + napi_create_string_utf8(env, strFuncs.c_str(), NAPI_AUTO_LENGTH, &result); + + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreSetCurrentFunctions(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + + int32_t funcs = 0; + napi_get_value_int32(env, argv[INDEX_0], &funcs); + + auto *asyncContext = new USBFunctionAsyncContext(); + asyncContext->env = env; + asyncContext->functions = funcs; + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "SetCurrentFunctions", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBFunctionAsyncContext *asyncContext = (USBFunctionAsyncContext *)data; + int32_t ret = g_usbClient.SetCurrentFunctions(asyncContext->functions); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call CoreSetCurrentFunctions async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBFunctionAsyncContext *asyncContext = (USBFunctionAsyncContext *)data; + napi_value queryResult = nullptr; + napi_get_boolean(env, asyncContext->status == napi_ok, &queryResult); + + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreGetCurrentFunctions(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + int32_t cfuncs; + int32_t ret = g_usbClient.GetCurrentFunctions(cfuncs); + napi_value result; + if (ret != ERR_OK) { + napi_get_undefined(env, &result); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, get ports faild ret : %{public}d", __func__, ret); + return result; + } + napi_create_int32(env, cfuncs, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreGetPorts(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + + std::vector ports; + + int32_t ret = g_usbClient.GetPorts(ports); + napi_value result; + if (ret != ERR_OK) { + napi_get_undefined(env, &result); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, get ports faild ret : %{public}d", __func__, ret); + return result; + } + + napi_create_array(env, &result); + for (uint32_t i = 0; i < ports.size(); ++i) { + napi_value port; + napi_create_object(env, &port); + SetValueInt32(env, "id", ports[i]->id, port); + SetValueInt32(env, "supportedModes", ports[i]->supportedModes, port); + napi_value usbPortStatus; + napi_create_object(env, &usbPortStatus); + SetValueInt32(env, "currentMode", ports[i]->usbPortStatus->currentMode, usbPortStatus); + SetValueInt32(env, "currentPowerRole", ports[i]->usbPortStatus->currentPowerRole, usbPortStatus); + SetValueInt32(env, "currentDataRole", ports[i]->usbPortStatus->currentDataRole, usbPortStatus); + napi_set_named_property(env, port, "status", usbPortStatus); + napi_set_element(env, result, i, port); + } + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +/* ============================================= Usb Port ============================================= */ + +static napi_value PortGetSupportedModes(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value args[PARAM_COUNT_1] = {0}; + napi_value jsthis; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + + int32_t id = 0; + int32_t result = 0; + napi_get_value_int32(env, args[INDEX_0], &id); + int32_t ret = g_usbClient.GetSupportedModes(id, result); + if (ret) { + USB_HILOGD(MODULE_JS_NAPI, "%{public}s:false ret = %{public}d", __func__, ret); + } + napi_value napiValue = nullptr; + NAPI_CALL(env, napi_create_int32(env, result, &napiValue)); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, result : %{public}d, takes : %{public}ld ms", __func__, result, + getTimeDiff(start, end)); + return napiValue; +} + +static napi_value PortSetPortRole(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_3; + napi_value args[PARAM_COUNT_3] = {0}; + napi_value jsthis; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + NAPI_CALL(env, napi_typeof(env, args[INDEX_1], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + NAPI_CALL(env, napi_typeof(env, args[INDEX_2], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + + int32_t id, powerRole, dataRole = 0; + napi_get_value_int32(env, args[INDEX_0], &id); + napi_get_value_int32(env, args[INDEX_1], &powerRole); + napi_get_value_int32(env, args[INDEX_2], &dataRole); + + auto *asyncContext = new USBPortRoleAsyncContext(); + asyncContext->env = env; + asyncContext->portId = id; + asyncContext->dataRole = dataRole; + asyncContext->powerRole = powerRole; + + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "PortSetPortRole", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBPortRoleAsyncContext *asyncContext = (USBPortRoleAsyncContext *)data; + int32_t ret = + g_usbClient.SetPortRole(asyncContext->portId, asyncContext->powerRole, asyncContext->dataRole); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call PortSetPortRole async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBPortRoleAsyncContext *asyncContext = (USBPortRoleAsyncContext *)data; + napi_value queryResult = nullptr; + + napi_get_boolean(env, asyncContext->status == napi_ok, &queryResult); + + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeClaimInterface(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_3; + napi_value argv[PARAM_COUNT_3] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + + UsbInterface interface; + napi_value obj2 = argv[INDEX_1]; + napi_typeof(env, obj2, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + ParseInterfaceObj(env, obj2, interface); + + bool isForce = false; + if (argc >= PARAM_COUNT_3) { + napi_typeof(env, argv[INDEX_2], &type); + NAPI_ASSERT(env, type == napi_boolean, "Wrong argument type. Object expected."); + napi_get_value_bool(env, argv[INDEX_2], &isForce); + } + + int32_t ret = pip.ClaimInterface(interface, isForce); + USB_HILOGD(MODULE_JS_NAPI, "pip call ClaimInterface ret: %{public}d", ret); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeReleaseInterface(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_2; + napi_value argv[PARAM_COUNT_2] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + + UsbInterface interface; + napi_value obj2 = argv[INDEX_1]; + ParseInterfaceObj(env, obj2, interface); + int32_t ret = pip.ReleaseInterface(interface); + USB_HILOGD(MODULE_JS_NAPI, "pip call PipeReleaseInterface ret: %{public}d", ret); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeSetInterface(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_2; + napi_value argv[PARAM_COUNT_2] = {0}; + napi_value thiz; + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_value pipeObj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, pipeObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, pipeObj, pip); + + napi_value interfaceObj = argv[INDEX_1]; + napi_typeof(env, interfaceObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + UsbInterface interface; + ParseInterfaceObj(env, interfaceObj, interface); + int32_t ret = g_usbClient.SetInterface(pip, interface); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeSetConfiguration(napi_env env, napi_callback_info info) +{ + struct timeval start; + gettimeofday(&start, nullptr); + + size_t argc = PARAM_COUNT_2; + napi_value argv[PARAM_COUNT_2] = {0}; + napi_value thiz; + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_valuetype type; + napi_value pipeObj = argv[INDEX_0]; + + napi_typeof(env, pipeObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + USBDevicePipe pip; + ParseUsbDevicePipe(env, pipeObj, pip); + + napi_value configObj = argv[INDEX_1]; + napi_typeof(env, configObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + USBConfig config; + ParseConfigObj(env, configObj, config); + + int32_t ret = g_usbClient.SetConfiguration(pip, config); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d, takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeGetRawDescriptors(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + + napi_value result; + int32_t ret = g_usbClient.GetRawDescriptors(nullptr, 0); + if (ret == ERR_OK) { + Uint8ArrayToJsValue(env, nullptr, 0, result); + } else { + napi_get_undefined(env, &result); + } + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeGetFileDescriptor(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + int32_t fd = g_usbClient.GetFileDescriptor(); + napi_value result; + SetValueInt32(env, "fd", fd, result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeControlTransfer(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + + size_t argc = PARAM_COUNT_3; + napi_value argv[PARAM_COUNT_3] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + // pipe param + napi_value pipeObj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, pipeObj, &type); + NAPI_ASSERT(env, type == napi_object, "argv[INDEX_0] wrong argument type, object expected."); + USBDevicePipe pipe; + ParseUsbDevicePipe(env, pipeObj, pipe); + + // control params + PipeControlParam controlParam; + ParsePipeControlParam(env, argv[INDEX_1], controlParam); + + // timeout param + int32_t timeout = 0; + if (argc >= PARAM_COUNT_3) { + napi_get_value_int32(env, argv[INDEX_2], &timeout); + } + + auto *asyncContext = new USBControlTransferAsyncContext(); + asyncContext->env = env; + asyncContext->pipe = pipe; + asyncContext->request = controlParam.request; + asyncContext->target = controlParam.target; + asyncContext->reqType = controlParam.reqType; + asyncContext->value = controlParam.value; + asyncContext->index = controlParam.index; + + if ((asyncContext->reqType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT) { + uint8_t *nativeArraybuffer = new uint8_t[controlParam.dataLength]; + memcpy_s(nativeArraybuffer, controlParam.dataLength, controlParam.data, controlParam.dataLength); + asyncContext->buffer = nativeArraybuffer; + } else { + asyncContext->buffer = controlParam.data; + } + + asyncContext->bufferLength = controlParam.dataLength; + asyncContext->timeout = timeout; + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "PipeControlTransfer", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBControlTransferAsyncContext *asyncContext = (USBControlTransferAsyncContext *)data; + int32_t ret = asyncContext->pipe.ControlTransfer( + asyncContext->reqType, asyncContext->request, asyncContext->value, asyncContext->index, + asyncContext->buffer, asyncContext->bufferLength, asyncContext->timeout); + if ((asyncContext->reqType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT) { + delete asyncContext->buffer; + asyncContext->buffer = nullptr; + } + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call PipeControlTransfer async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBControlTransferAsyncContext *asyncContext = (USBControlTransferAsyncContext *)data; + napi_value queryResult = nullptr; + + if (asyncContext->status == napi_ok) { + napi_create_int32(env, asyncContext->bufferLength, &queryResult); + } else { + napi_value message = nullptr; + napi_create_string_utf8(env, "PipeControlTransfer failed", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &queryResult); + } + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeBulkTransfer(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_4; + napi_value argv[PARAM_COUNT_4] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_3), "Failed to get cb info"); + + napi_valuetype type; + + USBDevicePipe pip; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_object, "argv[INDEX_0] wrong argument type, object expected"); + ParseUsbDevicePipe(env, argv[INDEX_0], pip); + + USBEndpoint ep; + napi_typeof(env, argv[INDEX_1], &type); + NAPI_ASSERT(env, type == napi_object, "argv[INDEX_1] Wrong argument type. Object expected."); + ParseEndpointObj(env, argv[INDEX_1], ep); + + uint8_t *buffer = nullptr; + size_t offset; + size_t bufferSize; + bool hasBuffer = JsUint8ArrayParse(env, argv[INDEX_2], &buffer, bufferSize, offset); + int32_t timeout = 0; + if (argc > PARAM_COUNT_3) { + napi_get_value_int32(env, argv[INDEX_3], &timeout); + } + + napi_value result = nullptr; + auto *asyncContext = new USBBulkTransferAsyncContext(); + napi_create_promise(env, &asyncContext->deferred, &result); + if (!hasBuffer) { + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s %{public}d : failed buffer is null", __func__, __LINE__); + asyncContext->status = napi_invalid_arg; + napi_value queryResult = nullptr; + napi_value message = nullptr; + napi_create_string_utf8(env, "Bulk transfer invalid arg", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &queryResult); + ProcessPromise(env, asyncContext, queryResult); + delete asyncContext; + return result; + } + + asyncContext->env = env; + asyncContext->pipe = pip; + asyncContext->endpoint = ep; + + if (ep.GetDirection() == USB_ENDPOINT_DIR_OUT) { + uint8_t *nativeArraybuffer = new uint8_t[bufferSize]; + memcpy_s(nativeArraybuffer, bufferSize, buffer, bufferSize); + asyncContext->buffer = nativeArraybuffer; + } else { + asyncContext->buffer = buffer; + } + + asyncContext->bufferLength = bufferSize; + asyncContext->timeout = timeout; + + napi_value resource = nullptr; + napi_create_string_utf8(env, "PipeBulkTransfer", NAPI_AUTO_LENGTH, &resource); + + status = napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + + USBBulkTransferAsyncContext *asyncContext = (USBBulkTransferAsyncContext *)data; + int32_t ret = asyncContext->pipe.BulkTransfer(asyncContext->endpoint, asyncContext->buffer, + asyncContext->bufferLength, asyncContext->timeout); + + if (asyncContext->endpoint.GetDirection() == USB_ENDPOINT_DIR_OUT) { + delete asyncContext->buffer; + asyncContext->buffer = nullptr; + } + + USB_HILOGD(MODULE_JS_NAPI, "call pipe result %{public}d", ret); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call PipeBulkTransfer async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBBulkTransferAsyncContext *asyncContext = (USBBulkTransferAsyncContext *)data; + napi_value queryResult = nullptr; + if (asyncContext->status == napi_ok) { + napi_create_int32(env, asyncContext->bufferLength, &queryResult); + } else { + napi_value message = nullptr; + napi_create_string_utf8(env, "PipeBulkTransfer failed", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &queryResult); + } + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + if (status != napi_ok) { + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, create async work failed, takes : %{public}ld ms", __func__, + getTimeDiff(start, end)); + return result; + } + napi_queue_async_work(env, asyncContext->work); + gettimeofday(&end, nullptr); + + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeClose(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + int32_t ret = pip.Close(); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, result %{public}d, takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value GetVersion(napi_env env, napi_callback_info info) +{ + std::string version = g_usbClient.GetVersion(); + USB_HILOGD(MODULE_JS_NAPI, "call %{public}s, version is %{public}s", __func__, version.c_str()); + napi_value result; + napi_create_string_utf8(env, version.c_str(), NAPI_AUTO_LENGTH, &result); + return result; +} + +EXTERN_C_START +/* + * function for module exports + */ +static napi_value UsbInit(napi_env env, napi_value exports) +{ + USB_HILOGD(MODULE_JS_NAPI, "enter"); + + napi_property_descriptor desc[] = { + /* usb core */ + DECLARE_NAPI_FUNCTION("getDevices", CoreGetDevices), DECLARE_NAPI_FUNCTION("connectDevice", CoreConnectDevice), + DECLARE_NAPI_FUNCTION("hasRight", CoreHasRight), DECLARE_NAPI_FUNCTION("requestRight", CoreRequestRight), + DECLARE_NAPI_FUNCTION("usbFunctionsFromString", CoreUsbFunctionsFromString), + DECLARE_NAPI_FUNCTION("usbFunctionsToString", CoreUsbFunctionsToString), + DECLARE_NAPI_FUNCTION("setCurrentFunctions", CoreSetCurrentFunctions), + DECLARE_NAPI_FUNCTION("getCurrentFunctions", CoreGetCurrentFunctions), + DECLARE_NAPI_FUNCTION("getPorts", CoreGetPorts), + + /* usb port */ + DECLARE_NAPI_FUNCTION("getSupportedModes", PortGetSupportedModes), + DECLARE_NAPI_FUNCTION("setPortRoles", PortSetPortRole), + + /* usb device pipe */ + DECLARE_NAPI_FUNCTION("claimInterface", PipeClaimInterface), + DECLARE_NAPI_FUNCTION("releaseInterface", PipeReleaseInterface), + DECLARE_NAPI_FUNCTION("bulkTransfer", PipeBulkTransfer), + DECLARE_NAPI_FUNCTION("controlTransfer", PipeControlTransfer), + DECLARE_NAPI_FUNCTION("setInterface", PipeSetInterface), + DECLARE_NAPI_FUNCTION("setConfiguration", PipeSetConfiguration), + DECLARE_NAPI_FUNCTION("getRawDescriptor", PipeGetRawDescriptors), + DECLARE_NAPI_FUNCTION("getFileDescriptor", PipeGetFileDescriptor), + DECLARE_NAPI_FUNCTION("closePipe", PipeClose), + + /* fort test get usb service version */ + DECLARE_NAPI_FUNCTION("getVersion", GetVersion)}; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + + USB_HILOGD(MODULE_JS_NAPI, "return"); + + return exports; +} +EXTERN_C_END + +/* + * Module definition + */ +static napi_module g_module = {.nm_version = 1, + .nm_flags = 0, + .nm_filename = "usb", + .nm_register_func = UsbInit, + .nm_modname = "usb", + .nm_priv = ((void *)0), + .reserved = {0}}; + +/* + * Module registration + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&g_module); +} diff --git a/interfaces/kits/js/test/CheckEmptyUtils.js b/interfaces/kits/js/test/CheckEmptyUtils.js new file mode 100644 index 00000000..cc244d5a --- /dev/null +++ b/interfaces/kits/js/test/CheckEmptyUtils.js @@ -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. + */ + +export default { + + /** + * Check obj is empty. + * + * @param {object} obj + * @return {boolean} true(empty) + */ + isEmpty(obj) { + return (typeof obj == 'undefined' || obj == null || JSON.stringify(obj) == '{}' || JSON.stringify(obj) == 'undefined'); + }, + + /** + * Check str is empty. + * + * @param {string} str + * @return {boolean} true(empty) + */ + checkStrIsEmpty(str) { + return str.trim().length == 0; + }, + + /** + * Check array is empty. + * + * @param {Array}arr + * @return {boolean} true(empty) + */ + isEmptyArr(arr) { + return arr.length == 0; + }, + + // ArrayBuffer转为字符串,参数为ArrayBuffer对象 + ab2str(buf) { + return String.fromCharCode.apply(null, new Uint8Array(buf)); + }, + + // 字符串转为ArrayBuffer对象,参数为字符串 + str2ab(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; + }, + + // 简单阻塞的粗暴实现 + sleep(delay) { + for (var t = Date.now(); Date.now() - t <= delay;); + } +} + \ No newline at end of file diff --git a/interfaces/kits/js/test/DateAndTimeUtil.js b/interfaces/kits/js/test/DateAndTimeUtil.js new file mode 100644 index 00000000..09ab1bdb --- /dev/null +++ b/interfaces/kits/js/test/DateAndTimeUtil.js @@ -0,0 +1,114 @@ +/** + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const twelve = 12; +/** + * date package tool class + */ +export default class DateAndTimeUtil{ + constructor() { + }; + /** + * + * Get the current time + */ + now() { + const datetime = new Date(); + const hours = datetime.getHours(); + const minutes = datetime.getMinutes(); + return this.concatTime(hours, minutes); + }; + + /** + * + * Get the current time + */ + nowWithSeconds() { + const datetime = new Date(); + const hours = datetime.getHours(); + const minutes = datetime.getMinutes(); + const seconds = datetime.getMilliseconds() + console.info("now: " + hours + ":" + minutes + ":" + seconds) + var now = this.concatTimeWithSeconds(hours, minutes, seconds); + console.info("now concat: " + now); + return now; + }; + + /** + * format + * @param value + * @return + */ + fill(value) { + return (value > 9 ? "" : "0") + value; + }; + /** + * concat date + * @param year m d + * @return + */ + concatDate(year, month, date) { + return year + this.year + month + this.month + date + this.day; + }; + + concatTime(hours, minutes) { + return `${this.fill(hours)}:${this.fill(minutes)}`; + }; + + concatTimeWithSeconds(hours, minutes, milliseconds) { + return `${this.fill(hours)}:${this.fill(minutes)}:${this.fill(milliseconds)}`; + }; + /** + * Turn to 24-hour clock + * @param str + * @return + */ + transform24(str) { + const timeFlag = str.substr(0, 2); + if (timeFlag == this.morning) { + const h = str.substr(2).split(":")[0]; + if (h == twelve) { + const time = "0" + ":" + str.substr(2).split(":")[1]; + return time; + } else { + return h + ":" + str.substr(2).split(":")[1]; + } + } else { + const h = str.substr(2).split(":")[0]; + const h1 = parseInt(h) + twelve; + if (h != twelve) { + const time = h1 + ":" + str.substr(2).split(":")[1]; + return time; + } + } + }; + /** + * Turn to 12-hour clock + * @param str + * @return + */ + transform12(str) { + const hours = str.substring(0, str.indexOf(":")); + const minutes = str.split(":")[1]; + if (hours < twelve) { + return this.morning.concat(`${hours}:${minutes}`); + } + if (hours == twelve) { + return this.afternoon.concat(`${hours}:${minutes}`); + } else { + const reduceHours = parseInt(hours) - twelve; + return this.afternoon.concat(`${reduceHours}:${minutes}`); + } + }; +} diff --git a/interfaces/kits/js/test/EventConstants.js b/interfaces/kits/js/test/EventConstants.js new file mode 100644 index 00000000..728c4fa2 --- /dev/null +++ b/interfaces/kits/js/test/EventConstants.js @@ -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. + */ + +/** + * Constants of events that will be registered to system. + */ +const EventConstants = { + /** + * Bitmask used for extracting the USBEndpoint type from it's address + */ + USB_ENDPOINT_XFERTYPE_MASK : 0x03, + + /** + * Control USBEndpoint type + */ + USB_ENDPOINT_XFER_CONTROL : 0, + + /** + * Isochronous USBEndpoint type + */ + USB_ENDPOINT_XFER_ISOC : 1, + + /** + * Bulk USBEndpoint type + */ + USB_ENDPOINT_XFER_BULK : 2, + + /** + * Interrupt USBEndpoint type + */ + USB_ENDPOINT_XFER_INT : 3, + + /** + * Bitmask used for extracting the USBEndpoint number from it's address + */ + USB_ENDPOINT_NUMBER_MASK : 0x0f, + + /** + * Bitmask used for extracting the USBEndpoint direction from it's address + */ + USB_ENDPOINT_DIR_MASK : 0x80, + + /** + * Used to signify direction of data for USBEndpoint is OUT, host to device + */ + USB_ENDPOINT_DIR_OUT : 0, + + /** + * Used to signify direction of data for USBEndpoint is IN, device to host + */ + USB_ENDPOINT_DIR_IN : 0x80 +} + +export default EventConstants; \ No newline at end of file diff --git a/interfaces/kits/js/test/ListUsb.test.js b/interfaces/kits/js/test/ListUsb.test.js new file mode 100644 index 00000000..0fb646b7 --- /dev/null +++ b/interfaces/kits/js/test/ListUsb.test.js @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* host test case */ +require('./UsbCoreJsunit.test.js') +require('./UsbDevicePipeJsunit.test.js') + +/* device test case */ +require('./UsbFunctionsJsunit.test.js') + +/* device and host test case */ +require('./UsbPortJsunit.test.js') diff --git a/interfaces/kits/js/test/UsbCoreJsunit.test.js b/interfaces/kits/js/test/UsbCoreJsunit.test.js new file mode 100644 index 00000000..73b0b7b0 --- /dev/null +++ b/interfaces/kits/js/test/UsbCoreJsunit.test.js @@ -0,0 +1,254 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + + +/* usb core functions test */ +describe('UsbCoreJsFunctionsTest', function () { + + beforeAll(function () { + console.log("*************Usb Unit UsbCoreJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("begin test getversion :" + Version) + // 切换为host + var usbPortList = usb.getPorts() + if (usbPortList.length > 0){ + if (usbPortList[0].status.currentMode == 2){ + usb.setPortRoles(usbPortList[0].id, 1, 1).then(data => { + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + }); + console.log("*************Usb Unit Begin switch to host*************"); + } + } + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + console.log("*************Usb Unit UsbCoreJsFunctionsTest End*************"); + }) + + var g_device_list + + /* * + * @tc.number : get_devices_test_01 + * @tc.name : getDevices + * @tc.desc : 获取设备列表 + */ + it('get_devices_test_01', 0, function () { + console.info('usb get_device_01 begin'); + g_device_list = usb.getDevices(); + if (g_device_list.length == 0) { + console.info("usb case get_devices list is null") + expect(false).assertTrue(); + return + } + console.info('usb get_devices_test_01: PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : connect_device_01 + * @tc.name : connectDevice + * @tc.desc : 打开设备 关闭设备 + */ + it('connect_device_01', 0, function () { + console.info('usb connect_device_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var usbDevicePipe = usb.connectDevice(g_device_list[i]) + var isPipClose = usb.closePipe(usbDevicePipe); + expect(isPipClose == 0).assertTrue(); + } + + console.info('usb connect_device_01 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : connect_device_02 + * @tc.name : connectDevice + * @tc.desc : 反向测试 错误参数 打开设备失败 即通过 + */ + it('connect_device_02', 0, function () { + console.info('usb connect_device_02 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var device = g_device_list[i] + device.busNum = i + 1000 + device.devAddress = i + 10000 + var usbDevicePipe = usb.connectDevice(device) + expect(CheckEmptyUtils.isEmpty(usbDevicePipe)).assertTrue(); + } + + console.info('usb connect_device_02 : PASS'); + }) + + /* * + * @tc.number : has_right_01 + * @tc.name : hasRight + * @tc.desc : 权限查询 连接设备 关闭设备 + */ + it('has_right_01', 0, function () { + console.info('usb has_right_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var hasRight = usb.hasRight(g_device_list[i].name) + expect(hasRight).assertTrue(); + if (hasRight){ + var pip = usb.connectDevice(g_device_list[i]); + expect(CheckEmptyUtils.isEmpty(pip)).assertTrue(); + if (!CheckEmptyUtils.isEmpty(pip)){ + var isPipClose = usb.closePipe(pip); + expect(isPipClose == 0).assertTrue(); + } + } + } + + console.info('usb has_right_01 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : has_right_02 + * @tc.name : hasRight + * @tc.desc : 反向测试 给错误设备名字 + */ + + it('has_right_02', 0, function () { + console.info('usb has_right_02 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var deviceName = g_device_list[i].name + deviceName = deviceName + "$#" + var hasRight = usb.hasRight(deviceName) + expect(hasRight == false).assertTrue(); + } + + console.info('usb has_right_02 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : request_right_01 + * @tc.name : requestRight + * @tc.desc : 请求权限 + */ + it('request_right_01', 0, function () { + console.info('usb request_right_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + usb.requestRight(g_device_list[i].name).then(hasRight=>{ + expect(hasRight).assertTrue(); + console.info('usb request_right_01 : PASS'); + }).catch(error=>{ + console.info("usb case device request right failed : " + error + ' :' + g_device_list[i].name); + expect(false).assertTrue(); + }); + } + }) + + /* * + * @tc.number : request_right_02 + * @tc.name : requestRight + * @tc.desc : 反向测试 错误设备名字 请求权限 + */ + it('request_right_02', 0, function () { + console.info('usb request_right_02 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var diviceName = g_device_list[i].name + diviceName = diviceName + "@#" + usb.requestRight(diviceName).then(hasRight=>{ + expect(hasRight).assertFalse(); + console.info('usb request_right_02 : PASS'); + }).catch(error=>{ + expect(error).assertFalse(); + console.info('usb request_right_02 error: ' + error); + }); + } + }) + + + /* * + * @tc.number : get_file_descriptor_test_01 + * @tc.name : get_file_descriptor + * @tc.desc : 获取文件描述符 + */ + it('get_file_descriptor_test_01', 0, function () { + console.info('usb get_file_descriptor_test_01 begin'); + if (g_device_list.length == 0) { + console.info("usb get_device_list is null") + return; + } + + for (var i = 0; i < g_device_list.length; i++) { + console.info("usb get_devices device: " + JSON.stringify(g_device_list[i])); + var usbDevicePipe = usb.connectDevice(g_device_list[i]) + console.info("usb connect return usbDevicePipe: " + JSON.stringify(usbDevicePipe)); + + if (!CheckEmptyUtils.isEmpty(usbDevicePipe)){ + var retFileDescriptor = usb.getFileDescriptor(usbDevicePipe) + console.info("usb getFileDescriptor return: " + retFileDescriptor); + expect(retFileDescriptor >= 0).assertTrue() + + var ret = usb.closePipe(usbDevicePipe) + console.info("usb closePipe return code: " + ret); + expect(ret == 0).assertTrue() + } + } + + console.info('usb get_file_descriptor_test_01 : PASS'); + }) + +}) diff --git a/interfaces/kits/js/test/UsbDevicePipeJsunit.test.js b/interfaces/kits/js/test/UsbDevicePipeJsunit.test.js new file mode 100644 index 00000000..56206be4 --- /dev/null +++ b/interfaces/kits/js/test/UsbDevicePipeJsunit.test.js @@ -0,0 +1,358 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import EventConstants from './EventConstants.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +/* usb device pipe test */ +describe('UsbDevicePipeJsFunctionsTest', function () { + var g_device_list + var g_pipe + + beforeAll(function () { + console.log("*************Usb Unit UsbDevicePipeJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("usb unit begin test getversion :" + Version) + + // 切换为host + var usbPortList = usb.getPorts() + if (usbPortList.length > 0){ + if (usbPortList[0].status.currentMode == 2){ + usb.setPortRoles(usbPortList[0].id, 1, 1).then(data => { + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + }); + console.log("*************Usb Unit switch to host Begin*************"); + } + } + + g_device_list = usb.getDevices(); + g_pipe = usb.connectDevice(g_device_list[0]) + console.info("usb unit connectDevice g_pipe ret : " + JSON.stringify(g_pipe)); + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + var isPipClose = usb.closePipe(g_pipe) + console.info("usb unit close g_pipe ret : " + isPipClose); + console.log("*************Usb Unit UsbDevicePipeJsFunctionsTest End*************"); + }) + + // 预制传输相关参数 + function getTransferTestParam() { + var testParam = { + device: null, + config: null, + pip: null, + inEndpoint: null, + outEndpoint: null, + interface: null, + usbRequest: null, + sendData:"", + isClaimed: 0, + maxInSize: 1024, + maxOutSize:1024 + } + + console.info("usb case g_device_list.length: " + g_device_list.length); + for (var i = 0; i < g_device_list.length; i++) + { + testParam.device = g_device_list[i] + testParam.config = testParam.device.configs[0] + testParam.pip = g_pipe + for (var j = 0; j < testParam.config.interfaces.length; j++){ + if (testParam.config.interfaces[j].endpoints.length == 0){ + continue + } + + var bfind = false + for (var k = 0; k < testParam.config.interfaces[j].endpoints.length; k++){ + var endpoint = testParam.config.interfaces[j].endpoints[k]; + if (endpoint.type == EventConstants.USB_ENDPOINT_XFER_BULK) { + bfind = true + if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_OUT) { + testParam.outEndpoint = endpoint; + testParam.maxOutSize = endpoint.maxPacketSize; + } else if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_IN) { + testParam.inEndpoint = endpoint + testParam.maxInSize = endpoint.maxPacketSize; + } + } + } + if (bfind){ + testParam.interface = testParam.config.interfaces[j] + break + } + } + } + + return testParam + } + + /* * + * @tc.number : bulk_transfer_test_01 + * @tc.name : bulkTransfer + * @tc.desc : 批量传输 收数据 + */ + it('bulk_transfer_test_01', 0, function () { + console.info('usb bulk_transfer_test_01 begin'); + var testParam = getTransferTestParam() + if (testParam.interface == null || testParam.inEndpoint == null ){ + expect(false).assertTrue(); + return + } + + testParam.isClaimed = usb.releaseInterface(testParam.pip, testParam.interface) + expect(testParam.isClaimed).assertTrue(); + testParam.isClaimed = usb.claimInterface(testParam.pip, testParam.interface, true); + expect(testParam.isClaimed).assertTrue(); + + console.info("usb case readData begin"); + var tmpUint8Array = new Uint8Array(testParam.maxInSize); + usb.bulkTransfer(testParam.pip, testParam.inEndpoint, tmpUint8Array,5000).then(data =>{ + console.info("usb case readData tmpUint8Array buffer : " + CheckEmptyUtils.ab2str(tmpUint8Array)); + console.info('usb case bulk_transfer_test_01 : PASS'); + expect(true).assertTrue(); + }).catch(error=>{ + console.info("usb case readData error : " + JSON.stringify(error)); + expect(false).assertTrue(); + }); + }) + + /* * + * @tc.number : bulk_transfer_test_02 + * @tc.name : bulkTransfer + * @tc.desc : 批量传输 发数据 + */ + it('bulk_transfer_test_02', 0, function () { + console.info('usb bulk_transfer_test_02 begin'); + var testParam = getTransferTestParam() + if (testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + testParam.isClaimed = usb.releaseInterface(testParam.pip, testParam.interface) + expect(testParam.isClaimed).assertTrue(); + testParam.isClaimed = usb.claimInterface(testParam.pip, testParam.interface, true); + expect(testParam.isClaimed).assertTrue(); + + testParam.sendData = "send time 13213213 wzy"; + var tmpUint8Array = CheckEmptyUtils.str2ab(testParam.sendData); + usb.bulkTransfer(testParam.pip, testParam.outEndpoint, tmpUint8Array,5000).then(data =>{ + console.info("usb case write length : " + data); + console.info("usb case readData tmpUint8Array buffer : " + CheckEmptyUtils.ab2str(tmpUint8Array)); + console.info('usb case bulk_transfer_test_02 : PASS'); + expect(true).assertTrue(); + }).catch(error=>{ + console.info("usb write error : " + JSON.stringify(error)); + expect(false).assertTrue(); + }); + + }) + + /* * + * @tc.number : claim_interface_test_01 + * @tc.name : claimInterface + * @tc.desc : 获取接口 并释放 + */ + it('claim_interface_test_01', 0, function () { + console.info('usb claim_interface_test_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + if(g_device_list[0].configs.length == 0){ + console.info("usb case current device.configs.length = 0"); + expect(false).assertTrue(); + return + } + + for (var j = 0; j < g_device_list[0].configs.length; j++){ + if(g_device_list[0].configs[j].interfaces.length == 0){ + console.info("usb case current device.configs.interfaces.length = 0"); + } + for (var k = 0; k < g_device_list[0].configs[j].interfaces.length; k++){ + var isClaim = usb.claimInterface(g_pipe, g_device_list[0].configs[j].interfaces[k], true) + console.info("usb case claimInterface function return: " + isClaim); + expect(isClaim).assertTrue(); + if (isClaim){ + isClaim = usb.releaseInterface(g_pipe, g_device_list[0].configs[j].interfaces[k]) + console.info("usb case releaseInterface function return: " + isClaim); + expect(isClaim).assertTrue(); + } + } + } + + console.info('usb claim_interface_test_01 : PASS'); + expect(true).assertTrue(); + }) + + function getTransferParam(iCmd, iReqType, iValue, iIndex) { + var tmpUint8Array = new Uint8Array(512); + var requestCmd = iCmd + var requestType = iReqType + var value = iValue; + var index = iIndex; + var controlParam = { + request: requestCmd, + reqType: requestType, + value: value, + index: index, + data: tmpUint8Array + } + return controlParam + } + + /* * + * @tc.number : set_interface_test_01 + * @tc.name : setInterface + * @tc.desc : 设置设备接口 + */ + it('set_interface_test_01', 0, function () { + console.info('usb set_interface_test_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + var timeout = 5000; + // SetInterface cmd 11 reqType 0 value 1 index 0 + var controlParam = getTransferParam(1, 0, 1, 0) + + for (var j = 0; j < g_device_list[0].configs.length; j++){ + var ret = usb.setInterface(g_pipe, g_device_list[0].configs[j].interfaces[1]) + console.info("usb case setInterface return : " + ret); + expect(ret).assertTrue(); + } + + console.info('usb set_interface_test_01 : PASS'); + expect(true).assertTrue(); + }) + + + function callControlTransfer(pip, controlParam, timeout, caseName) { + usb.controlTransfer(pip, controlParam, timeout).then(data =>{ + console.info("usb controlTransfer ret data : " + data + " " + caseName); + console.info("usb controlTransfer controlParam.data buffer : " + controlParam.data + " " + caseName); + console.info('usb' + caseName + ': PASS'); + expect(true).assertTrue(); + }).catch(error=>{ + console.info("usb controlTransfer error : " + JSON.stringify(error)); + console.info('usb' + caseName + ': PASS'); + expect(false).assertTrue(); + }); + } + + /* * + * @tc.number : control_transfer_test_01 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetDescriptor: cmd 6 reqType 128 value 512 index 0 + */ + it('control_transfer_test_01', 0, function () { + console.info('usb control_transfer_test_01 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(6, ((1 << 7) | (0 << 5) | (0 & 0x1f)), (2 << 8), 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_01 GetDescriptor") + }) + + /* * + * @tc.number : control_transfer_test_02 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetStatus: cmd 0 reqType 128 value 0 index 0 + */ + it('control_transfer_test_02', 0, function () { + console.info('usb control_transfer_test_02 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(0, 128, 0, 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_02 GetStatus") + }) + + /* * + * @tc.number : control_transfer_test_03 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetConfiguration: cmd 8 reqType 128 value 0 index 0 + */ + it('control_transfer_test_03', 0, function () { + console.info('usb control_transfer_test_03 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(8, 128, 0, 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_03 GetConfiguration") + }) + + /* * + * @tc.number : control_transfer_test_04 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetInterface: cmd 10 reqType 129 value 0 index 1 + */ + it('control_transfer_test_04', 0, function () { + console.info('usb control_transfer_test_04 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(10, 129, 0, 1) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_04 GetInterface") + }) + + /* * + * @tc.number : control_transfer_test_05 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 ClearFeature: cmd 1 reqType 0 value 0 index 0 + */ + it('control_transfer_test_05', 0, function () { + console.info('usb control_transfer_test_05 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(1, 0, 0, 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_05 ClearFeature") + }) + +}) diff --git a/interfaces/kits/js/test/UsbFunctionsJsunit.test.js b/interfaces/kits/js/test/UsbFunctionsJsunit.test.js new file mode 100644 index 00000000..933c3e71 --- /dev/null +++ b/interfaces/kits/js/test/UsbFunctionsJsunit.test.js @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + + +/* usb core functions test */ +describe('UsbFunctionsJsFunctionsTest', function () { + + beforeAll(function () { + console.log("*************Usb Unit UsbFunctionsJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("begin test getversion :" + Version) + // 切换到 device + var usbPortList = usb.getPorts() + if (usbPortList.length > 0){ + if (usbPortList[0].status.currentMode == 1){ + console.info("usb case set data role 1, data role 1"); + usb.setPortRoles(usbPortList[0].id, 1, 1).then(data => { + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + }); + console.log("*************Usb Unit switch to device Begin*************"); + } + } + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + console.log("*************Usb Unit UsbFunctionsJsFunctionsTest End*************"); + }) + + /* * + * @tc.number : get_current_functions_test_01 + * @tc.name : getCurrentFunctions + * @tc.desc : 获取当前设备模式 掩码与描述字符转换 + */ + it('get_current_functions_test_01', 0, function () { + console.info('usb get_current_functions_test_01 begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + + var strMaskCode = usb.usbFunctionsToString(maskCode) + console.info("usb case usbFunctionsToString return str: " + strMaskCode); + var nMaskCode = usb.usbFunctionsFromString(strMaskCode) + console.info("usb case strMaskCode usbFunctionsFromString return int: " + nMaskCode); + expect(nMaskCode).assertEqual(maskCode); + console.info('usb get_current_functions_test_01 : PASS'); + expect(true).assertTrue(); + }) + + + /* * + * @tc.number : get_current_functions_test_02 + * @tc.name : usbFunctionString + * @tc.desc : 反向测试 获取当前设备模式 掩码与描述字符转换 + */ + it('get_current_functions_test_02', 0, function () { + console.info('usb get_current_functions_test_02 begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + + var strMaskCode = usb.usbFunctionsToString(maskCode) + console.info("usb case usbFunctionsToString return str: " + strMaskCode); + var nMaskCode = usb.usbFunctionsFromString(strMaskCode) + console.info("usb case strMaskCode usbFunctionsFromString return int: " + nMaskCode); + + var errmaskCode = -1 + var strMaskCode = usb.usbFunctionsToString(errmaskCode) + expect(CheckEmptyUtils.isEmpty(strMaskCode)).assertFalse(); + console.info("usb case errMaskCode usbFunctionsToString return str: " + strMaskCode); + + var errnStrMaskCode = "HDC" + var nMaskCode = usb.usbFunctionsFromString(errnStrMaskCode) + expect(nMaskCode).assertEqual(-1); + console.info("usb case errnStrMaskCode usbFunctionsFromString return int: " + nMaskCode); + + console.info('usb get_current_functions_test_02 : PASS'); + }) + + function callSetCurFunction(caseName, iValue) { + CheckEmptyUtils.sleep(3000) + console.info("usb case param case name:" + caseName); + console.info("usb case param iValue:" + iValue); + usb.setCurrentFunctions(iValue).then(data => { + console.info("usb case return: " + data); + expect(data).assertTrue(); + console.info("usb " + caseName + ": PASS"); + }).catch(error => { + console.info("usb case " + caseName + " error : " + error); + expect(false).assertTrue(); + }); + } + +// /* * +// * @tc.number : set_current_functions_test_01 +// * @tc.name : setCurrentFunctions +// * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 0 取消所有function功能 +// */ +// it('set_current_functions_test_01', 0, function () { +// console.info('usb set_current_functions_test_01 begin'); +// var maskCode = usb.getCurrentFunctions(); +// console.info("usb case getCurrentFunctions return: " + maskCode); +// var funcString = usb.usbFunctionsToString(maskCode); +// console.info("usb case funcString:" + funcString); +// callSetCurFunction("set_current_functions_test_01 cancle all 0", 0) +// }) + + /* * + * @tc.number : set_current_functions_test_02 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 1 设置为ACM功能 + */ + it('set_current_functions_test_02', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_02 set ACM begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_02 ACM 1", 1) + }) + + /* * + * @tc.number : set_current_functions_test_03 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 2 设置为ECM功能 + */ + it('set_current_functions_test_03', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_03 set ECM begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_03 ECM 2", 2) + }) + + /* * + * @tc.number : set_current_functions_test_04 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 3 设置为ACM、ECM功能 + */ + it('set_current_functions_test_04', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_04 set ACM ECM begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_04 ACM ECM 3", 3) + }) + + /* * + * @tc.number : set_current_functions_test_05 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 4 设置为HDC功能 + */ + it('set_current_functions_test_05', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_05 set HDC begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_05 HDC 4", 4) + }) + + /* * + * @tc.number : set_current_functions_test_06 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 5 设置为ACM、HDC功能 + */ + it('set_current_functions_test_06', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_06 set ACM HDC begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_06 ACM HDC 5", 5) + }) + + /* * + * @tc.number : set_current_functions_test_07 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 6 设置为ECM、HDC功能 + */ + it('set_current_functions_test_07', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_07 set ECM HDC begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_07 ECM HDC 6", 6) + }) + +}) diff --git a/interfaces/kits/js/test/UsbPortJsunit.test.js b/interfaces/kits/js/test/UsbPortJsunit.test.js new file mode 100644 index 00000000..3845ee4f --- /dev/null +++ b/interfaces/kits/js/test/UsbPortJsunit.test.js @@ -0,0 +1,141 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +/* usb core functions test */ +describe('UsbPortJsFunctionsTest', function () { + + beforeAll(function () { + console.log("*************Usb Unit UsbPortJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("begin test getversion :" + Version) + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + console.log("*************Usb Unit UsbPortJsFunctionsTest End*************"); + }) + + + /* * + * @tc.number : get_ports_test_01 + * @tc.name : getPorts + * @tc.desc : 获取USB端口描述信息列表 + */ + it('get_ports_test_01', 0, function () { + console.info('usb get_ports_test_01 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb get_ports_test_01 usbPortList is null'); + expect(false).assertTrue(); + return + } + expect(usbPortList.length > 0).assertTrue(); + console.info('usb get_ports_test_01 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : get_supported_modes_test_01 + * @tc.name : getSupportedModes + * @tc.desc : 获取指定的端口支持的模式列表的组合掩码 + */ + it('get_supported_modes_test_01', 0, function () { + console.info('usb get_supported_modes_test_01 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb get_supported_modes_test_01 usbPortList is null'); + expect(false).assertTrue(); + return + } + + expect(usbPortList.length > 0).assertTrue(); + for (var i = 0; i < usbPortList.length; i++){ + var maskCode = usb.getSupportedModes(usbPortList[i].id) + expect(maskCode).assertEqual(usbPortList[i].supportedModes); + } + + console.info('usb get_supported_modes_test_01 : PASS'); + expect(true).assertTrue(); + }) + + + /* * + * @tc.number : set_port_roles_test_01 + * @tc.name : setPortRoles + * @tc.desc : 切换为Device set powerRole 2 DataRole 2 + */ + it('set_port_roles_test_01', 0, function () { + console.info('usb set_port_roles_test_01 device 2 2 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb set_port_roles_test_01 device 2 2 usbPortList is null'); + expect(false).assertTrue(); + return + } + + for (var i = 0; i < usbPortList.length; i++){ + console.info("usb case set data role 2, data role 2"); + usb.setPortRoles(usbPortList[i].id, 2, 2).then(data => { + console.info("usb case setPortRoles return: " + data); + expect(data).assertTrue(); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + expect(false).assertTrue(); + }); + } + + console.info('usb set_port_roles_test_01 device 2 2: PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : set_port_roles_test_02 + * @tc.name : setPortRoles + * @tc.desc : 切换为host set powerRole 1 DataRole 1 + */ + it('set_port_roles_test_02', 0, function () { + console.info('usb set_port_roles_test_02 host 1 1 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb set_port_roles_test_02 host 1 1 usbPortList is null'); + expect(false).assertTrue(); + return + } + + for (var i = 0; i < usbPortList.length; i++){ + console.info("usb case set data role 1, data role 1"); + CheckEmptyUtils.sleep(5000) + usb.setPortRoles(usbPortList[i].id, 1, 1).then(data => { + expect(data).assertTrue(); + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + expect(false).assertTrue(); + }); + } + + console.info('usb set_port_roles_test_02 host 1 1: PASS'); + expect(true).assertTrue(); + }) + +}) diff --git a/interfaces/kits/js/test/usb_unit.test.js b/interfaces/kits/js/test/usb_unit.test.js new file mode 100644 index 00000000..c179a733 --- /dev/null +++ b/interfaces/kits/js/test/usb_unit.test.js @@ -0,0 +1,495 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import app from '@system.app' +import Context from '@ohos.napi_context' +import usb from '@ohos.usb'; + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe('appInfoTest', function () { + console.log("*************Usb Unit Test Begin*************"); + /* usb core functions test */ + it('get_devices_test', 0, function () { + var result = usb.getDevices(); + console.info('getDevices = ' + result); + expect(result.size() > 0).assertEqual('1'); + }) + it('connect_devices_test', 0, function () { + var device = { + busNum = 1, + devAddr = 1, + name = "", + manufacturerName = "", + productName = "", + version = "", + vendorId = 1, + productId = 1, + clazz = 1, + subclass = 1, + protocol = 1, + hasAudioPlayback = false, + hasAudioCapture = false, + hasMidi = false, + hasVideoPlayback = false, + hasVideoCapture = false, + configs: [{ + id = 1, + attributes = 1, + maxPower = 1, + name = "", + isRemoteWakeup = false, + isSelfPowered = false, + interfaces = [{ + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }] + }] + }; + var result = usb.connectDevice(device); + console.info('connectDevice = ' + result); + expect(Object.keys(result).length >0).assertEqual('1'); + }) + + it('has_right_test', 0, function () { + var deviceName = ""; + var result = usb.hasRight(deviceName); + console.info('hasRight = ' + result); + expect(result === true).assertEqual('1'); + }) + it('request_right_test', 0, function () { + var deviceName = ""; + var result = usb.requestRight(deviceName); + console.info('requestRight = ' + result); + expect(result === true).assertEqual('1'); + }) + + it('usb_functions_from_string_test', 0, function () { + var funcs = ""; + var result = usb.usbFunctionsFromString(funcs); + console.info('usbFunctionsFromString = ' + result); + expect(result > 0).assertEqual('1'); + }) + it('usb_functions_to_string_test', 0, function () { + var funcs = 1; + var result = usb.usbFunctionsToString(funcs); + console.info('usbFunctionsToString = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('set_current_functions_test', 0, function () { + var funcs = 1; + var result = usb.setCurrentFunctions(funcs); + console.info('setCurrentFunctions = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_current_functions_test', 0, function () { + var result = usb.getCurrentFunctions(); + console.info('getCurrentFunctions = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('set_hdc_enabled_test', 0, function () { + var enable = false; + var result = usb.setHdcEnabled(enable); + console.info('setHdcEnabled = ' + result); + expect(result === true).assertEqual('1'); + }) + + it('get_ports_test', 0, function () { + var result = usb.getPorts(); + console.info('getPorts = ' + result); + expect(result.size() > 0).assertEqual('1'); + }) + + /* usb port functions test */ + it('get_supported_modes_test', 0, function () { + var portId = 1; + var result = usb.getSupportedModes(portId); + console.info('getSupportedModes = ' + result); + expect(result > 0).assertEqual('1'); + }) + it('set_port_roles_test', 0, function () { + var portId = 1; + var powerRole = 1; + var dataRole = 1; + var result = usb.setPortRoles(portId, powerRole, dataRole); + console.info('setPortRoles = ' + result); + expect(result === true).assertEqual('1'); + }) + + /* usb pipe functions test */ + it('claim_interface_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var iface = { + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }; + var force = true; + var result = usb.claimInterface(pipe, iface, force); + console.info('claimInterface = ' + result); + expect(result === true).assertEqual('1'); + }) + it('release_interface_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var iface = { + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }; + var result = usb.releaseInterface(pipe, iface); + console.info('releaseInterface = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_serial_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.getSerial(pipe); + console.info('getSerial = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('set_configuration_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var config = { + id = 1, + attributes = 1, + maxPower = 1, + name = "", + isRemoteWakeup = false, + isSelfPowered = false, + interfaces = [{ + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }] + }; + var result = usb.setConfiguration(pipe, config); + console.info('setConfiguration = ' + result); + expect(result === true).assertEqual('1'); + }) + it('set_interface_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var iface = { + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }; + var result = usb.setInterface(pipe, iface); + console.info('setInterface = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_raw_descriptors_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.getRawDescriptors(pipe); + console.info('getRawDescriptors = ' + result); + expect(result.length > 0).assertEqual('1'); + }) + it('get_file_descriptors_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.getFileDescriptors(pipe); + console.info('getFileDescriptors = ' + result); + expect(result > 0).assertEqual('1'); + }) + + it('control_transfer_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var requestType = 1; + var request = 1; + var value = 1; + var index = 1; + var buffer = [1,2,3]; + var length = 1; + var timeout = 1; + var result = usb.controlTransfer(pipe, requestType, request, value, index, buffer, length,timeout); + console.info('controlTransfer = ' + result); + expect(result > 0).assertEqual('1'); + }) + it('bulk_transfer_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }; + var buffer = [1,2,3]; + var length = 1; + var timeout = 1; + var result = usb.bulkTransfer(pipe, endpoint, buffer, length, timeout); + console.info('bulkTransfer = ' + result); + expect(result > 0).assertEqual('1'); + }) + + it('request_wait_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.requestWait(pipe); + console.info('requestWait = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('request_wait_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var timeout = 1; + var result = usb.requestWait(pipe, timeout); + console.info('requestWait = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('close_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.close(pipe, timeout); + console.info('close = ' + result); + expect(result === true).assertEqual('1'); + }) + + /* usb request functions test */ + it('initialize_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }; + var result = usb.initialize(pipe, endpoint); + console.info('initialize = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('free_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var result = usb.free(request); + console.info('free = ' + result); + expect(result === true).assertEqual('1'); + }) + it('abort_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var result = usb.abort(request); + console.info('abort = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_client_data_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var result = usb.getClientData(request); + console.info('getClientData = ' + result); + expect(result.length() > 0).assertEqual('1'); + }) + it('queue_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var buffer = [1,2,3]; + var result = usb.queue(request, buffer); + console.info('queue = ' + result); + expect(result === true).assertEqual('1'); + }) +}) \ No newline at end of file diff --git a/ohos.build b/ohos.build new file mode 100644 index 00000000..fbdfa63f --- /dev/null +++ b/ohos.build @@ -0,0 +1,32 @@ +{ + "subsystem": "usbmgr", + "parts": { + "usb_manager_native": { + "module_list": [ + "//base/usb/usb_manager/hdi:hdi_group", + "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "//base/usb/usb_manager/sa_profile:usbmgr_sa_profile", + "//base/usb/usb_manager/services:usbservice", + "//base/usb/usb_manager/interfaces/kits/js/napi:usb" + ], + "inner_kits": [ + { + "name": "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "header": { + "header_files": [ + "usb_srv_client.h", + "iusb_srv.h", + "usb_info.h" + ], + "header_base": "//base/usb/usb_manager/interfaces/innerkits/native/include" + } + } + ], + "test_list": [ + "//base/usb/usb_manager/services/native/test:usb_service_unittest", + "//base/usb/usb_manager/hdi/test:usbd_client_unittest", + "//base/usb/usb_manager/test/native:usbmgr_native_test" + ] + } + } +} diff --git a/sa_profile/4201.xml b/sa_profile/4201.xml new file mode 100644 index 00000000..cbee7ccb --- /dev/null +++ b/sa_profile/4201.xml @@ -0,0 +1,24 @@ + + + + foundation + + 4201 + libusbservice.z.so + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn new file mode 100644 index 00000000..67e668fa --- /dev/null +++ b/sa_profile/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("usbmgr_sa_profile") { + sources = [ "4201.xml" ] + part_name = "usb_manager_native" +} diff --git a/services/BUILD.gn b/services/BUILD.gn new file mode 100644 index 00000000..935c4a99 --- /dev/null +++ b/services/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("usbsrv_private_config") { + include_dirs = [ "//utils/system/safwk/native/include" ] +} + +config("usbsrv_public_config") { + include_dirs = [ + "native/include", + "${usb_manager_path}/services/zidl/include", + ] +} + +ohos_shared_library("usbservice") { + sources = [ + "${usb_manager_path}/services/zidl/src/usb_srv_stub.cpp", + "native/src/usb_descriptor_parser.cpp", + "native/src/usb_host_manager.cpp", + "native/src/usb_right_manager.cpp", + "native/src/usb_port_manager.cpp", + "native/src/usb_serial_reader.cpp", + "native/src/usb_server_event_handler.cpp", + "native/src/usb_service_subscriber.cpp", + "native/src/usb_service.cpp", + "native/src/usb_function_manager.cpp", + ] + + configs = [ + "${utils_path}:utils_config", + ":usbsrv_private_config", + ] + + public_configs = [ ":usbsrv_public_config" ] + + deps = [ + "${usb_manager_path}/hdi/client:usbd_client", + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + part_name = "usb_manager_native" +} + + diff --git a/services/native/include/usb_descriptor_parser.h b/services/native/include/usb_descriptor_parser.h new file mode 100644 index 00000000..f4d4ed26 --- /dev/null +++ b/services/native/include/usb_descriptor_parser.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 USB_DESCRIPTOR_PARSER_H +#define USB_DESCRIPTOR_PARSER_H +#include "usb_device.h" +#include "usb_interface.h" + +namespace OHOS { +namespace USB { + +class UsbDescriptorParser { +public: + UsbDescriptorParser(); + ~UsbDescriptorParser(); + + static int32_t ParseDeviceDescriptor(const uint8_t *buffer, uint32_t length, UsbDevice &dev); + static int32_t ParseConfigDescriptor(const uint8_t *buffer, uint32_t length, uint32_t &cursor, USBConfig &config); + static int32_t + ParseInterfaceDescriptor(const uint8_t *buffer, uint32_t length, uint32_t &cursor, UsbInterface &interface); + static int32_t ParseEndpointDescriptor(const uint8_t *buffer, uint32_t length, uint32_t &cursor, USBEndpoint &ep); +}; +} // namespace USB +} // namespace OHOS +#endif diff --git a/services/native/include/usb_function_manager.h b/services/native/include/usb_function_manager.h new file mode 100644 index 00000000..c532b7a5 --- /dev/null +++ b/services/native/include/usb_function_manager.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 USB_FUNCTION_MANAGER_H +#define USB_FUNCTION_MANAGER_H + +#include +#include +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { + +class UsbFunctionManager { +public: + static bool AreSettableFunctions(int32_t funcs); + + static int32_t FromStringFunctions(std::string funcs); + static std::string ToStringFunctions(int32_t func); + static void updateFunctions(int32_t func); + static int32_t getCurrentFunctions(); + + static const std::string FUNCTION_NAME_NONE; + static const std::string FUNCTION_NAME_HDC; + static const std::string FUNCTION_NAME_ACM; + static const std::string FUNCTION_NAME_ECM; + + static const int32_t FUNCTION_NONE; + static const int32_t FUNCTION_ACM; + static const int32_t FUNCTION_ECM; + static const int32_t FUNCTION_HDC; + +private: + static const int32_t FUNCTION_SETTABLE; + static const std::map FUNCTION_MAPPING_N2C; + static int currentFunctions; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USB_FUNCTION_MANAGER_H diff --git a/services/native/include/usb_host_manager.h b/services/native/include/usb_host_manager.h new file mode 100644 index 00000000..42d82aae --- /dev/null +++ b/services/native/include/usb_host_manager.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_HOST_MANAGER_H +#define USB_HOST_MANAGER_H + +#include +#include +#include +#include "system_ability.h" +#include "usb_device.h" +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { +typedef std::map MAP_STR_DEVICE; + +class UsbHostManager { +public: + UsbHostManager(SystemAbility *systemAbility); + ~UsbHostManager(); + void getDevices(MAP_STR_DEVICE &devices); + bool DelDevice(uint8_t busNum, uint8_t devNum); + bool AddDevice(UsbDevice *dev); + +private: + MAP_STR_DEVICE devices_; + SystemAbility *systemAbility_; +}; +} // namespace USB +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_port_manager.h b/services/native/include/usb_port_manager.h new file mode 100644 index 00000000..853de2e7 --- /dev/null +++ b/services/native/include/usb_port_manager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_PORT_MANAGER_H +#define USB_PORT_MANAGER_H + +#include +#include +#include +#include +#include "usb_common.h" +#include "usb_port.h" + +namespace OHOS { +namespace USB { +class UsbPortManager { +public: + UsbPortManager(); + typedef std::map PortMap; + PortMap portMap; + + void Init(); + void Init(int32_t test); + int32_t GetPorts(std::vector &ports); + int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); + void SetPortRoles(int32_t portId, int32_t powerRole, int32_t dataRole); + int32_t QueryPort(); + void UpdatePort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode); + void AddPort(UsbPort *port); + void RemovePort(int32_t portId); + +private: +}; + +} // namespace USB + +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_right_manager.h b/services/native/include/usb_right_manager.h new file mode 100644 index 00000000..e6c6a2d2 --- /dev/null +++ b/services/native/include/usb_right_manager.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 USB_RIGHT_MANAGER_H +#define USB_RIGHT_MANAGER_H + +#include +#include +#include +#include +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { +class UsbRightManager { +public: + typedef std::vector PidList; + typedef std::map RightMap; + RightMap rightMap; + + void Init(); + int32_t HasRight(std::string deviceName, int pid); + int32_t RequestRight(std::string deviceName, int pid); + void AddDeviceRight(std::string deviceName, int pid); + void RemoveDeviceRight(std::string deviceName); +}; +} // namespace USB +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_serial_reader.h b/services/native/include/usb_serial_reader.h new file mode 100644 index 00000000..32199739 --- /dev/null +++ b/services/native/include/usb_serial_reader.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 USB_SERIAL_READER_H +#define USB_SERIAL_READER_H + +#include +#include "system_ability.h" +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { + +class UsbSerialReader { +public: + UsbSerialReader(SystemAbility *systemAbility, UsbRightManager *rightManager, std::string serialNumber); + ~UsbSerialReader(); + +private: + SystemAbility *systemAbility_; + UsbRightManager *rightManager_; + std::string serialNumber_; +}; + +} // namespace USB + +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_server_event_handler.h b/services/native/include/usb_server_event_handler.h new file mode 100644 index 00000000..0db4ddc1 --- /dev/null +++ b/services/native/include/usb_server_event_handler.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 USBMGR_USB_SERVER_EVENT_HANDLER_H +#define USBMGR_USB_SERVER_EVENT_HANDLER_H + +#include "event_handler.h" +#include "refbase.h" + +namespace OHOS { +namespace USB { + +class UsbService; + +class UsbServerEventHandler : public AppExecFwk::EventHandler { +public: + UsbServerEventHandler(const std::shared_ptr &runner, const wptr &service); + ~UsbServerEventHandler() = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + +private: + wptr service_; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVER_EVENT_HANDLER_H diff --git a/services/native/include/usb_service.h b/services/native/include/usb_service.h new file mode 100644 index 00000000..197011ad --- /dev/null +++ b/services/native/include/usb_service.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_USB_SERVICE_H +#define USBMGR_USB_SERVICE_H + +#include +#include +#include "delayed_sp_singleton.h" +#include "iremote_object.h" +#include "iusb_srv.h" +#include "system_ability.h" +#include "usb_function_manager.h" +#include "usb_host_manager.h" +#include "usb_port_manager.h" +#include "usb_right_manager.h" +#include "usb_server_event_handler.h" +#include "usb_server_stub.h" +#include "usb_service_subscriber.h" +#include "usbd_api.h" +#include "usbd_client.h" +#include "usbd_subscriber.h" + +namespace OHOS { +namespace USB { + +class UsbService : public SystemAbility, public UsbServerStub { + + DECLARE_SYSTEM_ABILITY(UsbService) + +public: + ~UsbService(); + +private: + friend DelayedSpSingleton; + UsbService(); + +public: + virtual void OnStart() override; + virtual void OnStop() override; + virtual int32_t OnFoundDevice(FoundDevice &info) override; + + bool IsServiceReady() const + { + return ready_; + } + std::shared_ptr GetHandler() const + { + return handler_; + } + + int32_t OpenDevice(uint8_t busNum, uint8_t devAddr) override; + int32_t HasRight(std::string deviceName) override; + int32_t RequestRight(std::string deviceName) override; + int32_t GetDevices(std::vector &deviceList) override; + int32_t GetCurrentFunctions(int32_t &funcs) override; + int32_t SetCurrentFunctions(int32_t funcs) override; + int32_t UsbFunctionsFromString(std::string funcs) override; + std::string UsbFunctionsToString(int32_t funcs) override; + int32_t GetPorts(std::vector &result) override; + int32_t GetSupportedModes(int32_t portId, int32_t &result) override; + int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) override; + + int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + int32_t BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + int32_t BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) override; + int32_t ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) override; + int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) override; + int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) override; + int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) override; + int32_t RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientData, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) override; + int32_t RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) override; + int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) override; + int32_t Close(uint8_t busNum, uint8_t devAddr) override; + bool AddDevice(uint8_t busNum, uint8_t devAddr); + bool DelDevice(uint8_t busNum, uint8_t devAddr); + void UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode); + int32_t GetDeviceInfo(uint8_t busNum, uint8_t devAddr, UsbDevice *dev); + +private: + bool Init(); + bool InitUsbd(); + bool IsCommonEventServiceAbilityExist(); + + bool ready_{false}; + int32_t commEventRetryTimes_{0}; + std::mutex mutex_; + UsbHostManager *usbHostManger_ = nullptr; + UsbRightManager *usbRightManager = nullptr; + UsbPortManager *usbPortManager = nullptr; + UsbFunctionManager *usbFunctionManager = nullptr; + std::shared_ptr eventRunner_; + std::shared_ptr handler_; + sptr usbdSubscriber_; + std::map portMap; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVICE_H diff --git a/services/native/include/usb_service_subscriber.h b/services/native/include/usb_service_subscriber.h new file mode 100644 index 00000000..c1f278f6 --- /dev/null +++ b/services/native/include/usb_service_subscriber.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 USBMGR_USB_SERVICE_SUBSCRIBER_H +#define USBMGR_USB_SERVICE_SUBSCRIBER_H + +#include "usbd_subscriber.h" + +namespace OHOS { +namespace USB { + +class UsbServiceSubscriber : public UsbdSubscriber { +public: + UsbServiceSubscriber(); + ~UsbServiceSubscriber() = default; + int32_t Update(const UsbInfo &info) override; + int32_t DeviceEvent(const UsbInfo &info) override; + int32_t PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) override; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVICE_SUBSCRIBER_H diff --git a/services/native/src/usb_descriptor_parser.cpp b/services/native/src/usb_descriptor_parser.cpp new file mode 100644 index 00000000..79fba57d --- /dev/null +++ b/services/native/src/usb_descriptor_parser.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_descriptor_parser.h" +#include +#include "hilog_wrapper.h" +#include "message_parcel.h" +#include "securec.h" +#include "usb_config.h" +#include "usb_endpoint.h" +#include "usb_interface.h" +#include "usbd_api.h" + +namespace OHOS { +namespace USB { +enum DescriptorType { + DESCRIPTOR_TYPE_DEVICE = 1, + DESCRIPTOR_TYPE_CONFIG = 2, + DESCRIPTOR_TYPE_INTERFACE = 4, + DESCRIPTOR_TYPE_ENDPOINT = 5 +}; + +UsbDescriptorParser::UsbDescriptorParser() {} + +UsbDescriptorParser::~UsbDescriptorParser() {} + +int32_t UsbDescriptorParser::ParseDeviceDescriptor(const uint8_t *buffer, uint32_t length, UsbDevice &dev) +{ + uint32_t cursor = 0; + if (buffer == nullptr || length == 0) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: buffer is null", __func__); + return ERR_NO_INIT; + } + + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang parse begin buffer=%{public}p, length=%{public}d, cursor=%{public}d", __func__, + buffer, length, cursor); + uint32_t deviceDescriptorSize = sizeof(UsbdDeviceDescriptor); + if (length < deviceDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: buffer size error", __func__); + return ERR_INVALID_VALUE; + } + + UsbdDeviceDescriptor deviceDescriptor = *(UsbdDeviceDescriptor *)buffer; + cursor += deviceDescriptorSize; + if (deviceDescriptor.bLength != deviceDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: UsbdDeviceDescriptor size error", __func__); + return ERR_INVALID_VALUE; + } + + dev.SetVendorId(deviceDescriptor.idVendor); + dev.SetProductId(deviceDescriptor.idProduct); + dev.SetClass(deviceDescriptor.bDeviceClass); + dev.SetSubclass(deviceDescriptor.bDeviceSubClass); + dev.SetDescConfigCount(deviceDescriptor.bNumConfigurations); + + dev.SetbMaxPacketSize0(deviceDescriptor.bMaxPacketSize0); + dev.SetbcdDevice(deviceDescriptor.bcdDevice); + dev.SetbcdUSB(deviceDescriptor.bcdUSB); + dev.SetiManufacturer(deviceDescriptor.iManufacturer); + dev.SetiProduct(deviceDescriptor.iProduct); + dev.SetiSerialNumber(deviceDescriptor.iSerialNumber); + return ERR_OK; +} + +int32_t UsbDescriptorParser::ParseConfigDescriptor(const uint8_t *buffer, + uint32_t length, + uint32_t &cursor, + USBConfig &config) +{ + if (buffer == nullptr || length == 0) { + return ERR_INVALID_VALUE; + } + + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang parse begin buffer=%{public}p, length=%{public}d, cursor=%{public}d", __func__, + buffer, length, cursor); + uint32_t configDescriptorSize = sizeof(UsbdConfigDescriptor); + if (length < configDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: fumang buffer size error", __func__); + return ERR_INVALID_VALUE; + } + + UsbdConfigDescriptor configDescriptor = *(UsbdConfigDescriptor *)buffer; + cursor += configDescriptorSize; + if (configDescriptor.bLength != configDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: fumang UsbdDeviceDescriptor size error", __func__); + return ERR_INVALID_VALUE; + } + + config.SetId(configDescriptor.bConfigurationValue); + config.SetAttribute(configDescriptor.bmAttributes); + config.SetMaxPower(configDescriptor.bMaxPower); + config.SetiConfiguration(configDescriptor.iConfiguration); + + std::vector interfaces; + for(int i = 0; (i < configDescriptor.bNumInterfaces) && (cursor < length); ++i) { + uint32_t interfaceCursor = 0; + UsbInterface interface; + ParseInterfaceDescriptor(buffer + cursor + interfaceCursor, length - cursor - interfaceCursor, interfaceCursor, + interface); + if (interface.GetEndpointCount() > 0) { + interfaces.push_back(interface); + } else { + --i; + } + cursor += interfaceCursor; + } + config.SetInterfaces(interfaces); + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang bLength=%{public}d, \ + bDescriptorType=%{public}d, \ + wTotalLength=%{public}d, \ + bNumInterfaces=%{public}d, \ + bConfigurationValue=%{public}d, \ + iConfiguration=%{public}d, \ + bmAttributes=%{public}d, \ + bMaxPower=%{public}d", + __func__, configDescriptor.bLength, configDescriptor.bDescriptorType, configDescriptor.wTotalLength, + configDescriptor.bNumInterfaces, configDescriptor.bConfigurationValue, configDescriptor.iConfiguration, + configDescriptor.bmAttributes, configDescriptor.bMaxPower); + return ERR_OK; +} + +int32_t UsbDescriptorParser::ParseInterfaceDescriptor(const uint8_t *buffer, + uint32_t length, + uint32_t &cursor, + UsbInterface &interface) +{ + if (buffer == nullptr || length == 0) { + return ERR_INVALID_VALUE; + } + + uint32_t descriptorHeaderSize = sizeof(UsbdDescriptorHeader); + while ((uint32_t)cursor < length) { + if (descriptorHeaderSize >= length) { + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + UsbdDescriptorHeader descriptorHeader = *(UsbdDescriptorHeader *)(buffer + cursor); + if (descriptorHeader.bLength > length) { + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + if (descriptorHeader.bDescriptorType == DESCRIPTOR_TYPE_INTERFACE) { + break; + } + cursor += descriptorHeader.bLength; + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: type = %{public}d, length=%{public}d", __func__, + descriptorHeader.bDescriptorType, descriptorHeader.bLength); + } + + UsbdInterfaceDescriptor interfaceDescriptor = *(UsbdInterfaceDescriptor *)(buffer + cursor); + if (interfaceDescriptor.bLength != sizeof(UsbdInterfaceDescriptor)) { + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: UsbdInterfaceDescriptor size error", __func__); + return ERR_INVALID_VALUE; + } + cursor += interfaceDescriptor.bLength; + + interface.SetId(interfaceDescriptor.bInterfaceNumber); + interface.SetProtocol(interfaceDescriptor.bInterfaceProtocol); + interface.SetAlternateSetting(interfaceDescriptor.bAlternateSetting); + interface.SetClass(interfaceDescriptor.bInterfaceClass); + interface.SetSubClass(interfaceDescriptor.bInterfaceSubClass); + interface.SetiInterface(interfaceDescriptor.iInterface); + + std::vector eps; + for (int j = 0; j < interfaceDescriptor.bNumEndpoints; ++j) { + uint32_t epCursor = 0; + USBEndpoint ep; + ParseEndpointDescriptor(buffer + cursor + epCursor, length - cursor - epCursor, epCursor, ep); + ep.SetInterfaceId(interfaceDescriptor.bInterfaceNumber); + eps.push_back(ep); + cursor += epCursor; + } + interface.SetEndpoints(eps); + return ERR_OK; +} +int32_t UsbDescriptorParser::ParseEndpointDescriptor(const uint8_t *buffer, + uint32_t length, + uint32_t &cursor, + USBEndpoint &ep) +{ + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang parse begin buffer=%{public}p, length=%{public}d, cursor=%{public}d", __func__, + buffer, length, cursor); + if (buffer == nullptr || length == 0) { + return ERR_INVALID_VALUE; + } + + uint32_t descriptorHeaderSize = sizeof(UsbdDescriptorHeader); + while ((uint32_t)cursor < length) { + if (descriptorHeaderSize >= length) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + UsbdDescriptorHeader descriptorHeader = *(UsbdDescriptorHeader *)(buffer + cursor); + if (descriptorHeader.bLength > length) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + if (descriptorHeader.bDescriptorType == DESCRIPTOR_TYPE_ENDPOINT) { + break; + } + cursor += descriptorHeader.bLength; + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: error type = %{public}d, length=%{public}d", __func__, + descriptorHeader.bDescriptorType, descriptorHeader.bLength); + } + + UsbdEndpointDescriptor endpointDescriptor = *(UsbdEndpointDescriptor *)(buffer + cursor); + if (endpointDescriptor.bLength != sizeof(UsbdEndpointDescriptor)) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: fumang Endpoint descriptor size error, length=%{public}d", __func__, + endpointDescriptor.bLength); + return ERR_INVALID_VALUE; + } + cursor += endpointDescriptor.bLength; + + ep.SetAddr(endpointDescriptor.bEndpointAddress); + ep.SetAttr(endpointDescriptor.bmAttributes); + ep.SetInterval(endpointDescriptor.bInterval); + ep.SetMaxPacketSize(endpointDescriptor.wMaxPacketSize); + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang bLength=%{public}d, \ + bDescriptorType=%{public}d, \ + bEndpointAddress=%{public}d, \ + bmAttributes=%{public}d, \ + wMaxPacketSize=%{public}d, \ + bInterval=%{public}d", + __func__, endpointDescriptor.bLength, endpointDescriptor.bDescriptorType, + endpointDescriptor.bEndpointAddress, endpointDescriptor.bmAttributes, endpointDescriptor.wMaxPacketSize, + endpointDescriptor.bInterval); + return ERR_OK; +} +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_function_manager.cpp b/services/native/src/usb_function_manager.cpp new file mode 100644 index 00000000..4cf5a653 --- /dev/null +++ b/services/native/src/usb_function_manager.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_function_manager.h" +#include +#include + +namespace OHOS { +namespace USB { + +const std::string UsbFunctionManager::FUNCTION_NAME_NONE = "none"; +const std::string UsbFunctionManager::FUNCTION_NAME_HDC = "hdc"; +const std::string UsbFunctionManager::FUNCTION_NAME_ACM = "acm"; +const std::string UsbFunctionManager::FUNCTION_NAME_ECM = "ecm"; + +const int32_t UsbFunctionManager::FUNCTION_NONE = 0; +const int32_t UsbFunctionManager::FUNCTION_ACM = 1; +const int32_t UsbFunctionManager::FUNCTION_ECM = 2; +const int32_t UsbFunctionManager::FUNCTION_HDC = 4; + +int32_t UsbFunctionManager::currentFunctions = 0; + +const int32_t UsbFunctionManager::FUNCTION_SETTABLE = FUNCTION_HDC | FUNCTION_ACM | FUNCTION_ECM; + +const std::map UsbFunctionManager::FUNCTION_MAPPING_N2C = { + {FUNCTION_NAME_NONE, FUNCTION_NONE}, + {FUNCTION_NAME_ACM, FUNCTION_ACM}, + {FUNCTION_NAME_ECM, FUNCTION_ECM}, + {FUNCTION_NAME_HDC, FUNCTION_HDC}, +}; + +bool UsbFunctionManager::AreSettableFunctions(int32_t funcs) +{ + return funcs == FUNCTION_NONE || ((~FUNCTION_SETTABLE & funcs) == 0); +} + +int32_t UsbFunctionManager::FromStringFunctions(std::string funcs) +{ + if (funcs.compare(FUNCTION_NAME_NONE) == 0) { + return FUNCTION_NONE; + } + + std::regex re(","); + std::vector vec(std::sregex_token_iterator(funcs.begin(), funcs.end(), re, -1), + std::sregex_token_iterator()); + int64_t ret = 0; + for (auto &&item : vec) { + auto it = FUNCTION_MAPPING_N2C.find(item); + if (it != FUNCTION_MAPPING_N2C.end()) { + ret |= it->second; + } else { + std::string msg = "Invalid argument of usb function" + funcs; + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionManager::FromStringFunctions Invalid argument of usb function"); + return ERR_INVALID_VALUE; + } + } + return ret; +} + +std::string UsbFunctionManager::ToStringFunctions(int32_t func) +{ + std::stringstream stream; + if (FUNCTION_NONE == func) { + stream << FUNCTION_NAME_NONE; + return stream.str(); + } + + bool flag = false; + if ((func & FUNCTION_HDC) != 0) { + stream << FUNCTION_NAME_HDC; + flag = true; + } + if ((func & FUNCTION_ACM) != 0) { + if (flag) { + stream << ","; + } + stream << FUNCTION_NAME_ACM; + flag = true; + } + if ((func & FUNCTION_ECM) != 0) { + if (flag) { + stream << ","; + } + stream << FUNCTION_NAME_ECM; + flag = true; + } + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionManager::ToStringFunctions success"); + return stream.str(); +} + +void UsbFunctionManager::updateFunctions(int32_t func) +{ + currentFunctions = func; +} + +int32_t UsbFunctionManager::getCurrentFunctions() +{ + return currentFunctions; +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_host_manager.cpp b/services/native/src/usb_host_manager.cpp new file mode 100644 index 00000000..999e8092 --- /dev/null +++ b/services/native/src/usb_host_manager.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_host_manager.h" +#include "hilog_wrapper.h" +#include "usb_serial_reader.h" + +namespace OHOS { +namespace USB { + +UsbHostManager::UsbHostManager(SystemAbility *systemAbility) +{ + systemAbility_ = systemAbility; +} + +UsbHostManager::~UsbHostManager() {} + +void UsbHostManager::getDevices(MAP_STR_DEVICE &Devices) +{ + Devices = devices_; +} + +bool UsbHostManager::DelDevice(uint8_t busNum, uint8_t devNum) +{ + std::string name = std::to_string(busNum) + "-" + std::to_string(devNum); + MAP_STR_DEVICE::iterator iter = devices_.find(name); + if (iter == devices_.end()) { + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d not exist", + __func__, __LINE__, name.c_str(), busNum, devNum); + return false; + } + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d erase ", __func__, + __LINE__, name.c_str(), busNum, devNum); + devices_.erase(iter); + return true; +} +bool UsbHostManager::AddDevice(UsbDevice *dev) +{ + if (dev == NULL) { + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device is NULL", __func__, __LINE__); + return false; + } + uint8_t busNum = dev->GetBusNum(); + uint8_t devNum = dev->GetDevAddr(); + std::string name = std::to_string(busNum) + "-" + std::to_string(devNum); + MAP_STR_DEVICE::iterator iter = devices_.find(name); + if (iter != devices_.end()) { + USB_HILOGF(MODULE_SERVICE, + "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d already exist", __func__, + __LINE__, name.c_str(), busNum, devNum); + UsbDevice *devOld = iter->second; + devices_.erase(iter); + delete (devOld); + } + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d insert", + __func__, __LINE__, name.c_str(), busNum, devNum); + devices_.insert(std::pair(name, dev)); + return true; +} + +} // namespace USB + +} // namespace OHOS diff --git a/services/native/src/usb_port_manager.cpp b/services/native/src/usb_port_manager.cpp new file mode 100644 index 00000000..7a02efd1 --- /dev/null +++ b/services/native/src/usb_port_manager.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_port_manager.h" +#include "usbd_client.h" + +namespace OHOS { +namespace USB { + const int32_t SUPPORTED_MODES = 3; + +UsbPortManager::UsbPortManager() +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::Init start"); +} + +void UsbPortManager::Init() +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::QueryPort start"); + int ret = QueryPort(); + if (ret) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::QueryPort false"); + } +} + +int32_t UsbPortManager::GetPorts(std::vector &ports) +{ + + if (portMap.size() > 0) { + for (auto it = portMap.begin(); it != portMap.end(); ++it) { + ports.push_back(it->second); + } + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::GetPorts success"); + return ERR_OK; + } + USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::GetPorts false"); + return ERR_INVALID_VALUE; +} + +int32_t UsbPortManager::GetSupportedModes(int32_t portId, int32_t &supportedModes) +{ + auto it = portMap.find(portId); + if (it != portMap.end()) { + supportedModes = it->second->supportedModes; + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::GetSupportedModes success"); + return ERR_OK; + } + USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::GetSupportedModes false"); + return ERR_INVALID_VALUE; +} + +int32_t UsbPortManager::QueryPort() +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::queryPorts run"); + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + int32_t mode = 0; + int ret = UsbdClient::QueryPort(portId, powerRole, dataRole, mode); + USB_HILOGE(MODULE_USB_SERVICE, "portId:%{public}d powerRole:%{public}d dataRole:%{public}d mode:%{public}d ", + portId, powerRole, dataRole, mode); + if (ret) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbdClient::queryPorts false"); + return ret; + } + UsbPortStatus *usbPortStatus = new UsbPortStatus; + UsbPort *usbPort = new UsbPort; + usbPortStatus->currentMode = mode; + usbPortStatus->currentDataRole = dataRole; + usbPortStatus->currentPowerRole = powerRole; + usbPort->id = portId; + usbPort->supportedModes = SUPPORTED_MODES; + usbPort->usbPortStatus = usbPortStatus; + AddPort(usbPort); + return ret; +} + +void UsbPortManager::UpdatePort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::updatePort run"); + auto it = portMap.find(portId); + if (it != portMap.end()) { + if (it->second->id == portId) { + it->second->usbPortStatus->currentPowerRole = powerRole; + it->second->usbPortStatus->currentDataRole = dataRole; + it->second->usbPortStatus->currentMode = mode; + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::updatePort seccess"); + return; + } + } + USB_HILOGE(MODULE_USB_SERVICE, "updatePort false"); +} + +void UsbPortManager::AddPort(UsbPort *port) +{ + USB_HILOGI(MODULE_USB_SERVICE, "addPort run"); + auto it = portMap.find(port->id); + if (it == portMap.end()) { + portMap.insert(PortMap::value_type(port->id, port)); + USB_HILOGI(MODULE_USB_SERVICE, "addPort seccess"); + return; + } else { + delete port; + port = nullptr; + } + USB_HILOGE(MODULE_USB_SERVICE, "addPort false"); +} + +void UsbPortManager::RemovePort(int32_t portId) +{ + USB_HILOGI(MODULE_USB_SERVICE, "removePort run"); + auto it = portMap.find(portId); + if (it != portMap.end()) { + portMap.erase(it); + delete it->second; + USB_HILOGI(MODULE_USB_SERVICE, "removePort seccess"); + return; + } + USB_HILOGE(MODULE_USB_SERVICE, "removePort false"); +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_right_manager.cpp b/services/native/src/usb_right_manager.cpp new file mode 100644 index 00000000..b474acd3 --- /dev/null +++ b/services/native/src/usb_right_manager.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { +void UsbRightManager::Init() {} + +int32_t UsbRightManager::HasRight(std::string deviceName, int pid) +{ + auto itMap = rightMap.find(deviceName); + if (itMap == rightMap.end()) { + USB_HILOGE(MODULE_USB_SERVICE, "hasRight empty false 1"); + return ERR_INVALID_VALUE; + } else { + PidList pidList = itMap->second; + auto itVevtor = std::find(pidList.begin(), pidList.end(), pid); + if (itVevtor == pidList.end()) { + USB_HILOGE(MODULE_USB_SERVICE, "hasRight pid false 2"); + return ERR_INVALID_VALUE; + } + } + USB_HILOGI(MODULE_USB_SERVICE, "Request Right Success 3"); + return ERR_OK; +} + +int32_t UsbRightManager::RequestRight(std::string deviceName, int pid) +{ + if (HasRight(deviceName, pid) == 0) { + USB_HILOGE(MODULE_USB_SERVICE, "device has Right "); + return ERR_OK; + } + AddDeviceRight(deviceName, pid); + if (HasRight(deviceName, pid) == 0) { + USB_HILOGI(MODULE_USB_SERVICE, "requestRight Success"); + return ERR_OK; + } + USB_HILOGE(MODULE_USB_SERVICE, "requestRight False "); + return ERR_INVALID_VALUE; +} + +void UsbRightManager::AddDeviceRight(std::string deviceName, int pid) +{ + auto itMap = rightMap.find(deviceName); + if (itMap != rightMap.end()) { + auto v = itMap->second; + auto itVevtor = std::find(v.begin(), v.end(), pid); + if (itVevtor != v.end()) { + USB_HILOGE(MODULE_USB_SERVICE, "addDeviceRight false 1"); + return; + } + itMap->second.push_back(pid); + USB_HILOGI(MODULE_USB_SERVICE, "addDeviceRight success 2"); + } + PidList pidList; + pidList.push_back(pid); + rightMap.insert(RightMap::value_type(deviceName, pidList)); + USB_HILOGI(MODULE_USB_SERVICE, "addDeviceRight success 3"); +} + +void UsbRightManager::RemoveDeviceRight(std::string deviceName) +{ + auto it = rightMap.find("deviceName"); + if (it != rightMap.end()) { + rightMap.erase(it); + USB_HILOGI(MODULE_USB_SERVICE, "removeDeviceRight success 1"); + } +} +} // namespace USB +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/usb_serial_reader.cpp b/services/native/src/usb_serial_reader.cpp new file mode 100644 index 00000000..28ae42ea --- /dev/null +++ b/services/native/src/usb_serial_reader.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "usb_serial_reader.h" + +namespace OHOS { +namespace USB { + +UsbSerialReader::UsbSerialReader(SystemAbility *systemAbility, UsbRightManager *rightManager, std::string serialNumber) +{ + systemAbility_ = systemAbility; + rightManager_ = rightManager; + serialNumber_ = serialNumber; +} + +UsbSerialReader::~UsbSerialReader() {} + +} // namespace USB + +} // namespace OHOS diff --git a/services/native/src/usb_server_event_handler.cpp b/services/native/src/usb_server_event_handler.cpp new file mode 100644 index 00000000..c8900cc0 --- /dev/null +++ b/services/native/src/usb_server_event_handler.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "usb_server_event_handler.h" +#include "usb_service.h" +//#include "usb_common.h" + +namespace OHOS { +namespace USB { +UsbServerEventHandler::UsbServerEventHandler(const std::shared_ptr &runner, + const wptr &service) + : AppExecFwk::EventHandler(runner), service_(service) +{ + // USB_HILOGE(MODULE_USB_SERVICE, "UsbServerEventHandler::UsbServerEventHandler instance created."); +} + +void UsbServerEventHandler::ProcessEvent([[maybe_unused]] const AppExecFwk::InnerEvent::Pointer &event) {} +std::string deviceAddress; +int deviceClass = 0; +int deviceSubclass = 0; +unsigned char *descriptors = (unsigned char *)"000"; +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_service.cpp b/services/native/src/usb_service.cpp new file mode 100644 index 00000000..8862b69a --- /dev/null +++ b/services/native/src/usb_service.cpp @@ -0,0 +1,556 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_service.h" +#include +#include +#include +#include +#include +#include +#include "file_ex.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_descriptor_parser.h" +#include "usb_port_manager.h" +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { + +namespace { +const std::string USB_SERVICE_NAME = "UsbService"; +constexpr int32_t COMMEVENT_REGISTER_RETRY_TIMES = 10; +constexpr int32_t COMMEVENT_REGISTER_WAIT_DELAY_US = 20000; +const int32_t USB_MAX_DESCRIPTOR_SIZE = 256; +} // namespace + +auto pms = DelayedSpSingleton::GetInstance(); +const bool G_REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSpSingleton::GetInstance().GetRefPtr()); + +UsbService::UsbService() : SystemAbility(USB_MANAGER_USB_SERVICE_ID, true) +{ + usbHostManger_ = new UsbHostManager(nullptr); + usbRightManager = new UsbRightManager(); + usbPortManager = new UsbPortManager(); + usbFunctionManager = new UsbFunctionManager(); +} +UsbService::~UsbService() +{ + delete usbHostManger_; + delete usbRightManager; + delete usbPortManager; +} + +int32_t UsbService::OnFoundDevice(FoundDevice &info) +{ + return 0; +} + +void UsbService::OnStart() +{ + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s:%{public}d usb_service OnStart enter", __func__, __LINE__); + if (ready_) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart is ready, nothing to do"); + return; + } + if (!(Init())) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart call init fail"); + return; + } + if (!(InitUsbd())) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart call initUsbd fail"); + return; + } + usbPortManager->Init(); + ready_ = true; + USB_HILOGE(MODULE_USB_SERVICE, "OnStart and add system ability success"); +} + +bool UsbService::Init() +{ + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s:%{public}d usb_service Init enter", __func__, __LINE__); + if (!eventRunner_) { + eventRunner_ = AppExecFwk::EventRunner::Create(USB_SERVICE_NAME); + if (eventRunner_ == nullptr) { + USB_HILOGE(MODULE_USB_SERVICE, "Init failed due to create EventRunner"); + return false; + } + } + if (!handler_) { + handler_ = std::make_shared(eventRunner_, pms); + if (handler_ == nullptr) { + USB_HILOGE(MODULE_USB_SERVICE, "Init failed due to create handler error"); + return false; + } + if (!Publish(pms)) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart register to system ability manager failed."); + return false; + } + } + while (commEventRetryTimes_ <= COMMEVENT_REGISTER_RETRY_TIMES) { + if (!IsCommonEventServiceAbilityExist()) { + ++commEventRetryTimes_; + usleep(COMMEVENT_REGISTER_WAIT_DELAY_US); + } else { + commEventRetryTimes_ = 0; + break; + } + } + USB_HILOGE(MODULE_USB_SERVICE, "Init success"); + return true; +} + +bool UsbService::InitUsbd() +{ + usbdSubscriber_ = new UsbServiceSubscriber(); + ErrCode ret = UsbdClient::BindUsbdSubscriber(usbdSubscriber_); + USB_HILOGE(MODULE_USB_SERVICE, "fumang entry InitUsbd ret: %{public}d", ret); + return SUCCEEDED(ret); +} + +void UsbService::OnStop() +{ + USB_HILOGE(MODULE_USB_SERVICE, "fumang entry stop service %{public}d", ready_); + if (!ready_) { + return; + } + eventRunner_.reset(); + handler_.reset(); + ready_ = false; + UsbdClient::UnbindUsbdSubscriber(); +} + +bool UsbService::IsCommonEventServiceAbilityExist() +{ + sptr sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!sm) { + USB_HILOGE(MODULE_USB_SERVICE, + "IsCommonEventServiceAbilityExist Get ISystemAbilityManager " + "failed, no SystemAbilityManager"); + return false; + } + sptr remote = sm->CheckSystemAbility(COMMON_EVENT_SERVICE_ABILITY_ID); + if (!remote) { + USB_HILOGE(MODULE_USB_SERVICE, "No CesServiceAbility"); + return false; + } + return true; +} +int32_t UsbService::OpenDevice(uint8_t busNum, uint8_t devAddr) +{ + return UsbdClient::OpenDevice(busNum, devAddr); +} +int32_t UsbService::HasRight(std::string deviceName) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager HasRight"); + pid_t pid = GetCallingPid(); + USB_HILOGI(MODULE_USB_SERVICE, "RequestRight pid = %{public}d", pid); + return usbRightManager->HasRight(deviceName, pid); +} + +int32_t UsbService::RequestRight(std::string deviceName) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager RequestRight"); + pid_t pid = GetCallingPid(); + USB_HILOGI(MODULE_USB_SERVICE, "RequestRight pid = %{public}d", pid); + return usbRightManager->RequestRight(deviceName, pid); +} + +int32_t UsbService::GetDevices(std::vector &deviceList) +{ + std::map devices; + usbHostManger_->getDevices(devices); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s list size %{public}d", __func__, devices.size()); + for (auto it = devices.begin(); it != devices.end(); ++it) { + deviceList.push_back(*it->second); + } + return ERR_OK; +} + +int32_t UsbService::GetCurrentFunctions(int32_t &funcs) +{ + return UsbdClient::GetCurrentFunctions(funcs); +} + +int32_t UsbService::SetCurrentFunctions(int32_t funcs) +{ + USB_HILOGI(MODULE_USB_SERVICE, "func = %{public}d", funcs); + return UsbdClient::SetCurrentFunctions(funcs); +} + +int32_t UsbService::UsbFunctionsFromString(std::string funcs) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsFromString"); + return UsbFunctionManager::FromStringFunctions(funcs); +} + +std::string UsbService::UsbFunctionsToString(int32_t funcs) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsToString"); + return UsbFunctionManager::ToStringFunctions(funcs); +} + +int32_t UsbService::GetPorts(std::vector &ports) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getPorts"); + return usbPortManager->GetPorts(ports); +} + +int32_t UsbService::GetSupportedModes(int32_t portId, int32_t &supportedModes) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getSupportedModes"); + return usbPortManager->GetSupportedModes(portId, supportedModes); +} + +int32_t UsbService::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbd getPorts"); + return UsbdClient::SetPortRole(portId, powerRole, dataRole); +} + +int32_t UsbService::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + return UsbdClient::ClaimInterface(busNum, devAddr, interface); +} +int32_t UsbService::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + return UsbdClient::ReleaseInterface(busNum, devAddr, interface); +} +int32_t UsbService::BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((length > 0) && (!buffer)) { + return ret; + } + struct TransferParams params = {interface, endpoint, buffer, length, timeout}; + ret = UsbdClient::BulkTransferRead(busNum, devAddr, params); + return ret; +} +int32_t UsbService::BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((length > 0) && (!buffer)) { + return ret; + } + struct TransferParams params = {interface, endpoint, (uint8_t *)buffer, length, timeout}; + ret = UsbdClient::BulkTransferWrite(busNum, devAddr, params); + return ret; +} +int32_t UsbService::ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((length > 0) && (!buffer)) { + return ret; + } + struct CtrlTransferParamsParams params = {requestType, request, value, index, buffer, length, timeout}; + ret = UsbdClient::ControlTransfer(busNum, devAddr, params); + return ret; +} +int32_t UsbService::SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) +{ + return UsbdClient::SetConfig(busNum, devAddr, configIndex); +} +int32_t UsbService::GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) +{ + return UsbdClient::GetConfig(busNum, devAddr, configIndex); +} +int32_t UsbService::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) +{ + return UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); +} +int32_t UsbService::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) +{ + if ((length > 0) && (!desc)) { + return ERR_INVALID_VALUE; + } + return UsbdClient::GetRawDescriptor(busNum, devAddr, desc, length); +} +int32_t UsbService::RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientData, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((clientLength > 0) && (!clientData)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + struct RequestParams params = {(void *)clientData, clientLength, (uint8_t *)buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, ifId, endpointId, params); + return ret; +} +int32_t UsbService::RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((clientLength > 0) && (!clientData)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + struct RequestParams params = {clientData, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, timeout, params); + return ret; +} + +int32_t UsbService::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) +{ + return UsbdClient::RequestCancel(busNum, devAddr, interfaceid, endpointId); +} + +int32_t UsbService::Close(uint8_t busNum, uint8_t devAddr) +{ + return UsbdClient::CloseDevice(busNum, devAddr); +} + +static std::string GetDevStringValFromIdx(uint8_t busNum, uint8_t devAddr, uint8_t idx) +{ + int ret = ERR_OK; + uint32_t length = USB_MAX_DESCRIPTOR_SIZE; + uint8_t *buffer = new uint8_t[length]; + std::string string = " "; + struct DescriptorParams params = {idx, buffer, length}; + + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d getString idx:%{public}d", __func__, __LINE__, idx); + if (idx == 0) { + delete[] buffer; + return string; + } + + ret = UsbdClient::GetStringDescriptor(busNum, devAddr, params); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d get string[%{public}d] failed ret:%{public}d", __func__, + __LINE__, idx, ret); + delete[] buffer; + return string; + } + if ((length < 2) || (buffer[1] != 0x03)) { + USB_HILOGW(MODULE_USB_SERVICE, + "%{public}s:%{public}d type or length error, type:0x%{public}02x(0x03) len:%{public}d", __func__, + __LINE__, buffer[1], length); + delete[] buffer; + return string; + } + uint16_t tbuf[length + 1]; + for (uint32_t i = 0; i < length; ++i) { + tbuf[i] = buffer[i + 2]; + } + std::wstring wstr((wchar_t *)(tbuf), (length - 2) / 2); + string = std::string(wstr.begin(), wstr.end()); + + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d getString idx:%{public}d String:%{public}s length:%{public}d", + __func__, __LINE__, idx, string.c_str(), length); + delete[] buffer; + buffer = NULL; + return string; +} + +static std::string BcdToString(uint8_t *bcd, uint32_t bcdLen) +{ + std::string tstr; + for (uint32_t i = 0; i < bcdLen; ++i) { + tstr += std::to_string((bcd[i] & 0xf0) >> 4); + tstr += std::to_string((bcd[i] & 0x0f)); + } + return tstr; +} + +static int32_t FillDevStrings(UsbDevice *dev) +{ + uint8_t busNum; + uint8_t devAddr; + if (dev == NULL) { + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d dev is NULL", __func__, __LINE__); + return ERR_INVALID_VALUE; + } + + busNum = dev->GetBusNum(); + devAddr = dev->GetDevAddr(); + uint16_t bcdDevice = dev->GetbcdDevice(); + dev->SetVersion(BcdToString((uint8_t *)&bcdDevice, 2)); + dev->SetManufacturerName(GetDevStringValFromIdx(busNum, devAddr, dev->GetiManufacturer())); + dev->SetProductName(GetDevStringValFromIdx(busNum, devAddr, dev->GetiProduct())); + dev->SetmSerial(GetDevStringValFromIdx(busNum, devAddr, dev->GetiSerialNumber())); + USB_HILOGW(MODULE_USB_SERVICE, + "%{public}s:%{public}d iSerial:%{public}d mSerial:%{public}s Manufactur:%{public}s product:%{public}s " + "version:%{public}s", + __func__, __LINE__, dev->GetiSerialNumber(), dev->GetmSerial().c_str(), + dev->GetManufacturerName().c_str(), dev->GetProductName().c_str(), dev->GetVersion().c_str()); + + std::vector configs; + configs = dev->GetConfigs(); + for (auto it = configs.begin(); it != configs.end(); ++it) { + it->SetName(GetDevStringValFromIdx(busNum, devAddr, it->GetiConfiguration())); + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d Config:%{public}d %{public}s", __func__, __LINE__, + it->GetiConfiguration(), it->GetName().c_str()); + std::vector interfaces = it->GetInterfaces(); + for (auto itIF = interfaces.begin(); itIF != interfaces.end(); ++itIF) { + itIF->SetName(GetDevStringValFromIdx(busNum, devAddr, itIF->GetiInterface())); + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d interface:%{public}d %{public}s", __func__, __LINE__, + itIF->GetiInterface(), itIF->GetName().c_str()); + } + it->SetInterfaces(interfaces); + } + dev->SetConfigs(configs); + + return ERR_OK; +} + +int32_t UsbService::GetDeviceInfo(uint8_t busNum, uint8_t devAddr, UsbDevice *dev) +{ + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d busNum:%{public}d devAddr:%{public}d", __func__, __LINE__, + busNum, devAddr); + + if (!dev) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d dev is NULL busNum:%{public}d devAddr:%{public}d", + __func__, __LINE__, busNum, devAddr); + return ERR_INVALID_VALUE; + } + int32_t ret = ERR_OK; + uint32_t length = USB_MAX_DESCRIPTOR_SIZE; + uint8_t *buffer = new uint8_t[length]; + ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d fumang UsbdClient::OpenDevice ret=%{public}d", __func__, + __LINE__, ret); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang UsbdClient::OpenDevice failed ret=%{public}d", __func__, ret); + delete[] buffer; + return ret; + } + + ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + if (ret != ERR_OK) { + UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s:%{public}d UsbdClient::GetDeviceDescriptor failed ret=%{public}d busNum:%{public}d " + "devAddr:%{public}d", + __func__, __LINE__, ret, busNum, devAddr); + delete[] buffer; + return ret; + } + dev->SetBusNum(busNum); + dev->SetDevAddr(devAddr); + dev->SetName(std::to_string(busNum) + "-" + std::to_string(devAddr)); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang GetDeviceDescriptor length=%{public}d", __func__, length); + ret = UsbDescriptorParser::ParseDeviceDescriptor(buffer, length, *dev); + if (ret != ERR_OK) { + UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s ParseDeviceDescriptor failed ret=%{public}d", __func__, ret); + delete[] buffer; + return ret; + } + + std::vector configs; + for (uint8_t i = 0; i < dev->GetDescConfigCount(); ++i) { + uint32_t cursor = 0; + length = USB_MAX_DESCRIPTOR_SIZE; + struct DescriptorParams params = {i, buffer, length}; + ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, params); + if (ret != ERR_OK) { + UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang UsbdClient::GetConfigDescriptor failed ret=%{public}d", + __func__, ret); + delete[] buffer; + return ret; + } + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang GetConfigDescriptor length=%{public}d", __func__, length); + uint32_t configCursor = 0; + USBConfig config; + ret = UsbDescriptorParser::ParseConfigDescriptor(buffer + cursor, length - cursor, configCursor, config); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s ParseConfigDescriptor[%{public}d] ret:%{public}d", __func__, i, ret); + cursor += configCursor; + configs.push_back(config); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang Descriptor=%{public}s", __func__, config.ToString().c_str()); + } + dev->SetConfigs(configs); + ret = FillDevStrings(dev); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d FillDevStrings ret=%{public}d", __func__, __LINE__, ret); + + UsbdClient::CloseDevice(busNum, devAddr); + delete[] buffer; + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang Descriptor=%{public}s", __func__, dev->ToString().c_str()); + + return ERR_OK; +} + +bool UsbService::AddDevice(uint8_t busNum, uint8_t devAddr) +{ + int32_t ret = ERR_OK; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d busNum:%{public}d devAddr:%{public}d", __func__, __LINE__, busNum, + devAddr); + UsbDevice *devInfo = new UsbDevice(); + memset(devInfo, 0, sizeof(UsbDevice)); + ret = GetDeviceInfo(busNum, devAddr, devInfo); + if (ret == ERR_OK) { + usbHostManger_->AddDevice(devInfo); + return true; + } + delete devInfo; + return false; +} +bool UsbService::DelDevice(uint8_t busNum, uint8_t devAddr) +{ + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d fumang entry", __func__, __LINE__); + int32_t ret = Close(busNum, devAddr); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d Close device failed width ret = %{public}d", __func__, __LINE__, + ret); + } + return usbHostManger_->DelDevice(busNum, devAddr); +} + +void UsbService::UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) +{ + usbPortManager->UpdatePort(portId, powerRole, dataRole, mode); +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_service_subscriber.cpp b/services/native/src/usb_service_subscriber.cpp new file mode 100644 index 00000000..c586c0ec --- /dev/null +++ b/services/native/src/usb_service_subscriber.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_service_subscriber.h" + +#include +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "delayed_sp_singleton.h" +#include "ohos/aafwk/content/want.h" +#include "string_ex.h" +#include "usb_common.h" +#include "usb_service.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace USB { + +UsbServiceSubscriber::UsbServiceSubscriber() {} + +int32_t UsbServiceSubscriber::PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) +{ + auto pms = DelayedSpSingleton::GetInstance(); + Want want; + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED); + pms->UpdateUsbPort(portId, powerRole, dataRole, mode); + CommonEventData data; + data.SetWant(want); + CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(true); + bool isSuccess = CommonEventManager::PublishCommonEvent(data, publishInfo); + if (!isSuccess) { + USB_HILOGE(MODULE_USB_SERVICE, "failed to publish PortChangedEvent"); + } + return isSuccess; +} + +int32_t UsbServiceSubscriber::DeviceEvent(const UsbInfo &info) +{ + struct timeval start; + gettimeofday(&start, NULL); + int status = info.getDevInfoStatus(); + int32_t ret = ERR_OK; + Want want; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d status:%{public}d bus:%{public}d dev:%{public}d", __func__, __LINE__, + status, info.getDevInfoBusNum(), info.getDevInfoDevNum()); + switch (status) { + case ACT_DEVUP: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED); + break; + case ACT_DEVDOWN: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED); + break; + case ACT_UPDEVICE: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_ACCESSORY_ATTACHED); + break; + case ACT_DOWNDEVICE: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_ACCESSORY_DETACHED); + break; + default: + return ret; + } + CommonEventData data; + data.SetWant(want); + CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(true); + bool isSuccess = CommonEventManager::PublishCommonEvent(data, publishInfo); + if (!isSuccess) { + USB_HILOGE(MODULE_USB_SERVICE, "failed to publish USB_CHANGED event"); + ret = ERR_NO_INIT; + } + struct timeval end; + gettimeofday(&end, NULL); + USB_HILOGD(MODULE_USB_SERVICE, "end call subscriber usb device tached event, takes : %{public}ld ms", + (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000); + + if ((ACT_UPDEVICE == status) || (ACT_DOWNDEVICE == status)) { + return ret; + } + int busNum = info.getDevInfoBusNum(); + int devAddr = info.getDevInfoDevNum(); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d status:%{public}d bus:%{public}d dev:%{public}d", __func__, __LINE__, + status, busNum, devAddr); + auto pms = DelayedSpSingleton::GetInstance(); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d status:%{public}d pms:%{public}s", __func__, __LINE__, status, + pms == nullptr ? "NULL" : "OK"); + if (status == ACT_DEVUP) { + USB_HILOGE(MODULE_USB_SERVICE, "usb attached"); + pms->AddDevice(busNum, devAddr); + } else { + USB_HILOGE(MODULE_USB_SERVICE, "usb detached"); + pms->DelDevice(busNum, devAddr); + } + + return ret; +} + +int32_t UsbServiceSubscriber::Update(const UsbInfo &info) +{ + return ERR_NO_INIT; +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/test/BUILD.gn b/services/native/test/BUILD.gn new file mode 100644 index 00000000..377eedea --- /dev/null +++ b/services/native/test/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +#################################group######################################### +group("usb_service_unittest") { + testonly = true + deps = [ "unittest/common:unittest", ] + +} +############################################################################### \ No newline at end of file diff --git a/services/native/test/unittest/common/BUILD.gn b/services/native/test/unittest/common/BUILD.gn new file mode 100644 index 00000000..39844e91 --- /dev/null +++ b/services/native/test/unittest/common/BUILD.gn @@ -0,0 +1,166 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +module_output_path = "usb_manager_native/usb_service_test" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//base/usb/usb_manager/interfaces/innerkits/native/include", + ] +} + +##############################unittest##########################################= + +ohos_unittest("test_usbport") { + module_out_path = module_output_path + sources = [ + "src/usb_port_service_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_usbpipe") { + module_out_path = module_output_path + sources = [ + "src/usb_device_pipe_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_usbrequest") { + module_out_path = module_output_path + sources = [ + "src/usb_request_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_usbcore") { + module_out_path = module_output_path + sources = [ + "src/usb_core_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +############################################################################### +group("unittest") { + testonly = true + deps = [ + ":test_usbport", + ":test_usbpipe", + ":test_usbrequest", + ":test_usbcore" + ] +} +############################################################################### diff --git a/services/native/test/unittest/common/include/usb_core_test.h b/services/native/test/unittest/common/include/usb_core_test.h new file mode 100644 index 00000000..1d2b1c53 --- /dev/null +++ b/services/native/test/unittest/common/include/usb_core_test.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_CORE_TEST_H +#define USB_CORE_TEST_H + +#include + +class UsbCoreTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif \ No newline at end of file diff --git a/services/native/test/unittest/common/include/usb_device_pipe_test.h b/services/native/test/unittest/common/include/usb_device_pipe_test.h new file mode 100644 index 00000000..38e3c61e --- /dev/null +++ b/services/native/test/unittest/common/include/usb_device_pipe_test.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_UsbDevicePipeTest_TEST_H +#define USB_UsbDevicePipeTest_TEST_H + +#include + +class UsbDevicePipeTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); +}; +#endif \ No newline at end of file diff --git a/services/native/test/unittest/common/include/usb_request_test.h b/services/native/test/unittest/common/include/usb_request_test.h new file mode 100644 index 00000000..168a7160 --- /dev/null +++ b/services/native/test/unittest/common/include/usb_request_test.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_UsbRequestTest_TEST_H +#define USB_UsbRequestTest_TEST_H + +#include + +class UsbRequestTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif diff --git a/services/native/test/unittest/common/src/usb_core_test.cpp b/services/native/test/unittest/common/src/usb_core_test.cpp new file mode 100644 index 00000000..bc558595 --- /dev/null +++ b/services/native/test/unittest/common/src/usb_core_test.cpp @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_core_test.h" +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" +#include "usb_service.h" +#include "usb_srv_client.h" + +using namespace testing::ext; +using namespace OHOS::USB; +using namespace OHOS; +using namespace std; + +void UsbCoreTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbCoreTest-----------"); +} + +void UsbCoreTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbCoreTest-----------"); +} + +void UsbCoreTest::SetUp(void) {} + +void UsbCoreTest::TearDown(void) {} + +/** + * @tc.name: GetCurrentFunctions003 + * @tc.desc: Test functions to GetCurrentFunctions() + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, GetCurrentFunctions003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : GetCurrentFunctions003 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t funcs = 0; + funcs = instance.GetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::funcs=%{public}d", funcs); + ASSERT_TRUE(funcs == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : GetCurrentFunctions003 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions005 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions005 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions005 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions006 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions006 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(2); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions006 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions007 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions007 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(3); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions007 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions008 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions008 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(4); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions008 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions009 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionService009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions009 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(8); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions009 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsFromString010 + * @tc.desc: Test functions to UsbFunctionsFromString(string funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsFromString010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString010 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t funcCode = instance.UsbFunctionsFromString(UsbFunctionManager::FUNCTION_NAME_HDC); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::functionsFromString=%{public}d", funcCode); + ASSERT_TRUE(funcCode); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString010 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString011 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString011, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString011 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_NONE); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(funcName.empty()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString011 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString012 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString012, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString012 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_HDC); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString012 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString013 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString013, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString013 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_ACM); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString013 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString014 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString014, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString014 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_ECM); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString014 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString015 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString015, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString015 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(-1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString015 : SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight018 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 正向测试:代码正常运行,返回结果为0 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight018, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight018: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_60"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight018 HasRight=%{public}d", result); + ASSERT_TRUE(result != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight018: SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight019 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 反向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight019, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight019: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_60"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight019 HasRight=%{public}d", result); + ASSERT_TRUE(result != 0); + result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight019 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight019 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight019: SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight020 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 反向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight020, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight020: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_60"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight020 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + deviceName = "device_61"; + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight020 HasRight=%{public}d", result); + ASSERT_TRUE(result == -1); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight020: SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight021 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 反向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight021, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight021: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_62"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight021 HasRight=%{public}d", result); + ASSERT_TRUE(result == -1); + result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight021 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight021 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight021: SetConfig-----------"); +} + +/** + * @tc.name: Usbrequestright022 + * @tc.desc: Test functions of requestright + * @tc.desc: int32_t requestright(std::string deviceName) + * @tc.desc: 正向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, Usbrequestright022, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestright022: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_61"; + int32_t result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright022 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright022 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestright022: SetConfig-----------"); +} +/** + * @tc.name: Usbrequestright023 + * @tc.desc: Test functions of requestright + * @tc.desc: int32_t requestright(std::string deviceName) + * @tc.desc: 正向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, Usbrequestright023, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestright023: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_62"; + int32_t result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright023 RequestRight=%{public}d", result); + ASSERT_TRUE(result == -1); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright023 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestright023: SetConfig-----------"); +} + +/** + * @tc.name: Usbrequestright024 + * @tc.desc: Test functions of requestright + * @tc.desc: int32_t requestright(std::string deviceName) + * @tc.desc: 反向测试:代码报错,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, Usbrequestright024, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestright024: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_63"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright024 HasRight=%{public}d", result); + ASSERT_TRUE(result == -1); + result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright024 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright024 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestright024: SetConfig-----------"); +} \ No newline at end of file diff --git a/services/native/test/unittest/common/src/usb_device_pipe_test.cpp b/services/native/test/unittest/common/src/usb_device_pipe_test.cpp new file mode 100644 index 00000000..31e5c0ac --- /dev/null +++ b/services/native/test/unittest/common/src/usb_device_pipe_test.cpp @@ -0,0 +1,1778 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_device_pipe_test.h" +#include +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_service.h" +#include "usb_srv_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +void UsbDevicePipeTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbDevicePipeTest-----------"); +} + +void UsbDevicePipeTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbDevicePipeTest-----------"); +} + +void UsbDevicePipeTest::SetUp(void) {} + +void UsbDevicePipeTest::TearDown(void) {} + +void UsbDevicePipeTest::PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << 二进制数据流[" << length << "字节] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_INNERKIT, "%{public}s", oss.str().c_str()); +} + +/** + * @tc.name: getDevices001 + * @tc.desc: Test functions to getDevices(std::vector &deviceList); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, getDevices001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : getDevices001 : getDevices-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : getDevices001 : getDevices-----------"); +} + +/** + * @tc.name: UsbOpenDevice001 + * @tc.desc: Test functions of OpenDevice + * @tc.desc: int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip) + * @tc.desc: 正向测试:代码正常运行,返回结果为0 + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbOpenDevice001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbOpenDevice001: OpenDevice-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::vector deviceList; + auto ret = UsbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbOpenDevice001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbOpenDevice001 %{public}d size=%{public}d", __LINE__, + deviceList.size()); + USBDevicePipe pipe; + ret = UsbSrvClient.OpenDevice(deviceList[0], pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbOpenDevice001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbOpenDevice001: OpenDevice-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer001 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer001 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 8; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 8, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer001 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer002 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer002 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 8; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 8, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer002 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer003 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer003 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 8; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 8, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer003 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer004 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer004 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 8; + uint8_t buffer[255] = {}; + memset(buffer, 0, 255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 6, 0x100, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer004 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer005 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer005 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 8; + uint8_t buffer[255] = {}; + memset(buffer, 0, 255); + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 6, 0x100, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer005 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer006 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer006 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 8; + uint8_t buffer[255] = {}; + memset(buffer, 0, 255); + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 6, 0x100, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer006 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer007 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer007 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0X0A, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer007 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer008 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer008 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0X0A, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer008 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer009 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer009 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0X0A, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer009 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer010 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer010 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer010 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer011 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer011, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer011 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer011 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer012 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer012, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer012 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer012 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer0013 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer0013, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer0013 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {0}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer0013 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer0014 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer0014, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer0014 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {0}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer0014 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer0015 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer0015, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer0015 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {0}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer0015 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer016 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer016, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer016 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 16; + uint8_t buffer[255] = {0}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer016 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer017 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer017, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer017 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 16; + uint8_t buffer[255] = {0}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer017 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer018 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer018, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer018 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 16; + uint8_t buffer[255] = {0}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer018 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer019 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer019, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer019 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0X0C, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer019 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer020 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer020, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer020 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0X0C, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer020 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer021 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer021, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer021 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0X0C, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer021 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbClaimInterface001 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface001 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbClaimInterface001 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbClaimInterface002 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface002 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbClaimInterface002 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbClaimInterface003 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface003 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().at(1); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface003 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbClaimInterface003 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbClaimInterface004 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface004 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().at(1); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, false); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface004 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface004 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbReleaseInterface001 + * @tc.desc: Test functions to ReleaseInterface(const UsbInterface &interface); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbReleaseInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbReleaseInterface001 : ReleaseInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(0); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbReleaseInterface001 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbReleaseInterface001 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbReleaseInterface002 + * @tc.desc: Test functions to ReleaseInterface(const UsbInterface &interface); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbReleaseInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbReleaseInterface002 : ReleaseInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().at(1); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbReleaseInterface002 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbReleaseInterface002 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbBulkTransfer001 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer001 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbDevicePipeTest::PrintBuffer("BulkTransferRead", buffer, len); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer001 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer002 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer002 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, -5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer002 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer003 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer003 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + pipe.SetBusNum(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer003 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer004 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer004 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + memset(buffer, 0, len); + pipe.SetDevAddr(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d len=%{public}d", __LINE__, len); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer004 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer005 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer005 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + point.SetInterfaceId(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer005 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer006 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer006 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + point.SetAddr(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer006 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer007 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer007 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer007"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer007 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer008 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer008 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer008"; + uint32_t len = 255; + pipe.SetDevAddr(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer008 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer009 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer009 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer009"; + uint32_t len = 255; + pipe.SetBusNum(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer009 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer010 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer010 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer010"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, -5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer010 : BulkTransfer-----------"); +} + +/** + * @tc.name: SetConfiguration001 + * @tc.desc: Test functions to SetConfiguration(const USBConfig &config); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, SetConfiguration001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetConfiguration001 : SetConfiguration-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + USBConfig config = device.GetConfigs().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.SetConfiguration(pipe, config); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d SetConfiguration=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::SetConfiguration001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetConfiguration001 : SetConfiguration-----------"); +} + +/** + * @tc.name: SetConfiguration002 + * @tc.desc: Test functions to SetConfiguration(const USBConfig &config); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, SetConfiguration002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetConfiguration002 : SetConfiguration-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + USBConfig config = device.GetConfigs().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetBusNum(255); + ret = UsbSrvClient.SetConfiguration(pipe, config); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d SetConfiguration=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::SetConfiguration002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetConfiguration002 : SetConfiguration-----------"); +} + +/** + * @tc.name: SetConfiguration003 + * @tc.desc: Test functions to SetConfiguration(const USBConfig &config); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, SetConfiguration003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetConfiguration003 : SetConfiguration-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + USBConfig config = device.GetConfigs().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetDevAddr(255); + ret = UsbSrvClient.SetConfiguration(pipe, config); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d SetConfiguration=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::SetConfiguration003 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetConfiguration003 : SetConfiguration-----------"); +} + +/** + * @tc.name: Close001 + * @tc.desc: Test functions to Close(); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Close001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Close001 : Close-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close001 %{public}d size=%{public}d", __LINE__, devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close001 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close001 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Close001 : Close-----------"); +} + +/** + * @tc.name: Close002 + * @tc.desc: Test functions to Close(); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Close002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Close002 : Close-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close002 %{public}d size=%{public}d", __LINE__, devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close002 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetBusNum(255); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close002 %{public}d close=%{public}d", __LINE__, ret); + ASSERT_TRUE(!ret); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close002 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Close002 : Close-----------"); +} + +/** + * @tc.name: Close003 + * @tc.desc: Test functions to Close(); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Close003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Close003 : Close-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close003 %{public}d size=%{public}d", __LINE__, devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close003 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetDevAddr(255); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close003 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(!ret); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close003 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Close003 : Close-----------"); +} \ No newline at end of file diff --git a/services/native/test/unittest/common/src/usb_port_service_test.cpp b/services/native/test/unittest/common/src/usb_port_service_test.cpp new file mode 100644 index 00000000..4b014207 --- /dev/null +++ b/services/native/test/unittest/common/src/usb_port_service_test.cpp @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 +#include +#include +#include + +#include "usb_service.h" +#include "usb_srv_client.h" + +using namespace testing::ext; +using namespace OHOS::USB; +using namespace OHOS; + +class UsbPortServiceTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void UsbPortServiceTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbPortServiceTest-----------"); +} + +void UsbPortServiceTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbPortServiceTest-----------"); +} + +void UsbPortServiceTest::SetUp(void) {} + +void UsbPortServiceTest::TearDown(void) {} + +/** + * @tc.name: UsbPortServiceTest01 + * @tc.desc: Test functions to GetPorts + * @tc.desc: int32_t GetPorts(std::vector &usbports); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest01, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest01 : GetPorts-----------"); + auto &usbSrvClient = UsbSrvClient::GetInstance(); + std::vector portlist; + auto ports = usbSrvClient.GetPorts(portlist); + USB_HILOGD(MODULE_USB_SERVICE, "Get UsbPort size=%{public}d", ports); + ASSERT_TRUE(ports == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest01 : GetPorts-----------"); +} + +/** + * @tc.name: UsbPortServiceTest02 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t GetSupportedModes(int32_t portId, int32_t &result); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest02, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest02 : GetSupportedModes-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + int32_t result = 0; + auto modes = UsbSrvClient.GetSupportedModes(0, result); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", modes); + ASSERT_TRUE(modes != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest02 : GetSupportedModes-----------"); +} + +/** + * @tc.name: UsbPortServiceTest03 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t GetSupportedModes(int32_t portId, int32_t &result); + * @tc.desc: 反向测试:portid错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest03, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest03 : GetSupportedModes-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + int32_t result = 0; + auto modes = UsbSrvClient.GetSupportedModes(-1, result); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", modes); + ASSERT_TRUE(modes != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest03 : GetSupportedModes-----------"); +} + +/** + * @tc.name: UsbPortServiceTest04 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t GetSupportedModes(int32_t portId, int32_t &result); + * @tc.desc: 反向测试:portid错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest04, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest04 : GetSupportedModes-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + int32_t result = 0; + auto modes = UsbSrvClient.GetSupportedModes(0xFFFFFFFF, result); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", modes); + ASSERT_TRUE(modes != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest04 : GetSupportedModes-----------"); +} + +/** + * @tc.name: UsbPortServiceTest05 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest05, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest05 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(1, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest05 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbPortServiceTest06 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 反向测试:portid错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest06, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest06 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(-1, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest06 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbPortServiceTest07 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 反向测试:powerRole错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest07, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest07 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(1, -1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest07 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbPortServiceTest08 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 反向测试:dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest08, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest08 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(1, 1, -1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest08 : SetPortRole-----------"); +} diff --git a/services/native/test/unittest/common/src/usb_request_test.cpp b/services/native/test/unittest/common/src/usb_request_test.cpp new file mode 100644 index 00000000..5d1d981a --- /dev/null +++ b/services/native/test/unittest/common/src/usb_request_test.cpp @@ -0,0 +1,712 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_request_test.h" +#include +#include +#include +#include +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iusb_srv.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device_pipe.h" +#include "usb_request.h" +#include "usb_service.h" +#include "usb_srv_client.h" +using namespace testing::ext; +using namespace OHOS::USB; +using namespace OHOS; +using namespace std; + +void UsbRequestTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdRequestTest-----------"); +} + +void UsbRequestTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdRequestTest-----------"); +} + +void UsbRequestTest::SetUp(void) {} + +void UsbRequestTest::TearDown(void) {} +/** + * @tc.name: UsbRequestInitialize001 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize001 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "request read"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize001 %{public}d Initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize001 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize002 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize002 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request write"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize002 %{public}d Initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize002 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize003 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize003 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize003 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize003 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request read"; + request.SetClientData((void *)tag, 11); + pip.SetBusNum(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize003 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize003 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize003 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize004 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize004 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize004 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize004 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request read"; + request.SetClientData((void *)tag, 11); + pip.SetDevAddr(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize004 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize004 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize004 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize005 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize005 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize005 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize005 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request write"; + request.SetClientData((void *)tag, 11); + pip.SetBusNum(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize005 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize005 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize005 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize006 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize006 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize006 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize006 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request write"; + request.SetClientData((void *)tag, 11); + pip.SetDevAddr(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize006 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize006 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize006 : Initialize-----------"); +} + +/** + * @tc.name: UsbrequestQueue001 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbrequestQueue001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbrequestQueue001 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = "request queue read001"; + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbrequestQueue001 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbrequestQueue002 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbrequestQueue002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbrequestQueue002 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = "request queue write 002"; + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbrequestQueue002 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbrequestQueue002 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbrequestQueue002 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbrequestQueue003 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequest008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequest008 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d ret=%{public}d size:%{public}d", __LINE__, + ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice devi = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(devi, pip); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbRequestTest:UsbRequest008 %{public}d ret=%{public}d pip.BusNum=%{public}d pip.DevAddr=%{public}d ", + __LINE__, ret, pip.GetBusNum(), pip.GetDevAddr()); + ASSERT_TRUE(ret == ERR_OK); + std::vector configs = devi.GetConfigs(); + USBConfig conf = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d size=%{public}d config:%{public}s ", + __LINE__, configs.size(), conf.ToString().c_str()); + USBConfig config = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d ret=%{public}d ", __LINE__, ret); + UsbRequest request; + UsbInterface &interface = config.GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d GetDirection=%{public}d ", __LINE__, + point.GetDirection()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d GetInterfaceId=%{public}d ", __LINE__, + point.GetInterfaceId()); + UsbSrvClient.ReleaseInterface(pip, interface); + UsbSrvClient.ClaimInterface(pip, interface, true); + uint32_t len = 1; + uint8_t buffer[1] = {0X12}; + UsbSrvClient.BulkTransfer(pip, point, buffer, len, 5); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequest008 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequest008 : RequestQueue-----------"); +} + +/** + * @tc.name: Usbrequest009 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequest009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequest009 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d ret=%{public}d size:%{public}d", __LINE__, + ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice devi = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(devi, pip); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbRequestTest:UsbRequest009 %{public}d ret=%{public}d pip.BusNum=%{public}d pip.DevAddr=%{public}d ", + __LINE__, ret, pip.GetBusNum(), pip.GetDevAddr()); + ASSERT_TRUE(ret == ERR_OK); + std::vector configs = devi.GetConfigs(); + USBConfig conf = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d size=%{public}d config:%{public}s ", + __LINE__, configs.size(), conf.ToString().c_str()); + USBConfig config = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d ret=%{public}d ", __LINE__, ret); + UsbRequest request; + UsbInterface &interface = config.GetInterfaces().at(0); + USBEndpoint point = interface.GetEndpoints().at(0); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d GetDirection=%{public}d ", __LINE__, + point.GetDirection()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d GetInterfaceId=%{public}d ", __LINE__, + point.GetInterfaceId()); + UsbSrvClient.ReleaseInterface(pip, interface); + UsbSrvClient.ClaimInterface(pip, interface, true); + uint32_t len = 255; + uint8_t buffer[255] = {}; + UsbSrvClient.ControlTransfer(pip, 0b10000010, 0, 0, 0, buffer, len, 50); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequest009 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequest009 : RequestQueue-----------"); +} + +/** + * @tc.name: Usbrequestfree001 + * @tc.desc: Test functions of free() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestfree001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestfree001 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d OpenDevice=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree001 %{public}d ReleaseInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request free 001"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Free(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d free=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestfree001 : RequestQueue-----------"); +} + +/** + * @tc.name: Usbrequestfree002 + * @tc.desc: Test functions of free() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestfree002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestfree002 : Requestfree-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + UsbRequest request; + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d ReleaseInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request free 002"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree002 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Free(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree002 %{public}d free=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestfree002 : Requestfree-----------"); +} + +/** + * @tc.name: Usbrequestabort001 + * @tc.desc: Test functions of abort() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestabort001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestabort001 : Requestabort-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "hello world request013"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "request abort 001"; + uint8_t len = 255; + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Abort(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d Abort=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestabort001 : Requestabort-----------"); +} + +/** + * @tc.name: Usbrequestabort002 + * @tc.desc: Test functions of abort() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestabort002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestabort002 : Requestabort-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d GetDirection=%{public}d ", __LINE__, + point.GetDirection()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d GetInterfaceId=%{public}d ", __LINE__, + point.GetInterfaceId()); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "hello world request014"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "request abort 002"; + uint8_t len = 255; + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Abort(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d abort=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestabort002 : Requestabort-----------"); +} diff --git a/services/zidl/include/usb_server_proxy.h b/services/zidl/include/usb_server_proxy.h new file mode 100644 index 00000000..1a22b2c8 --- /dev/null +++ b/services/zidl/include/usb_server_proxy.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_USB_SERVER_PROXY_H +#define USBMGR_USB_SERVER_PROXY_H + +#include +#include +#include "iremote_proxy.h" +#include "iusb_srv.h" +#include "nocopyable.h" +#include "usb_device.h" + +namespace OHOS { +namespace USB { + +class UsbServerProxy : public IRemoteProxy { +public: + explicit UsbServerProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~UsbServerProxy() = default; + DISALLOW_COPY_AND_MOVE(UsbServerProxy); + + virtual int32_t GetDevices(std::vector &deviceList) override; + virtual int32_t OpenDevice(uint8_t busNum, uint8_t devAddr) override; + virtual int32_t HasRight(std::string deviceName) override; + virtual int32_t RequestRight(std::string deviceName) override; + virtual int32_t GetCurrentFunctions(int32_t &funcs) override; + virtual int32_t SetCurrentFunctions(int32_t funcs) override; + virtual int32_t UsbFunctionsFromString(std::string funcs) override; + virtual std::string UsbFunctionsToString(int32_t funcs) override; + virtual int32_t GetPorts(std::vector &ports) override; + virtual int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes) override; + virtual int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) override; + + virtual int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + virtual int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + virtual int32_t BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + virtual int32_t BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) override; + virtual int32_t ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + virtual int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) override; + virtual int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) override; + virtual int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) override; + virtual int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) override; + virtual int32_t RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointIndex, + const void *clientObj, + uint32_t objLength, + const uint8_t *buffer, + uint32_t length) override; + virtual int32_t RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) override; + virtual int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) override; + virtual int32_t Close(uint8_t busNum, uint8_t devAddr) override; + +private: + static inline BrokerDelegator delegator_; + void ParseUsbPort(MessageParcel &reply, std::vector &result); + int32_t SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr); + int32_t SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length); + int32_t GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length); + int32_t GetDeviceListMessageParcel(MessageParcel &data, std::vector &deviceList); + int32_t GetDeviceMessageParcel(MessageParcel &data, UsbDevice &devInfo); + int32_t GetDeviceConfigsMessageParcel(MessageParcel &data, std::vector &configs); + int32_t GetDeviceInterfacesMessageParcel(MessageParcel &data, std::vector &interfaces); + int32_t GetDeviceEndpointsMessageParcel(MessageParcel &data, std::vector &eps); +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVER_PROXY_H diff --git a/services/zidl/include/usb_server_stub.h b/services/zidl/include/usb_server_stub.h new file mode 100644 index 00000000..8b192a57 --- /dev/null +++ b/services/zidl/include/usb_server_stub.h @@ -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. + */ + +#ifndef USBMGR_USB_SERVER_STUB_H +#define USBMGR_USB_SERVER_STUB_H + +#include +#include "iremote_stub.h" +#include "iusb_srv.h" +#include "nocopyable.h" +#include "usb_device.h" + +namespace OHOS { +namespace USB { + +class UsbServerStub : public IRemoteStub { +public: + DISALLOW_COPY_AND_MOVE(UsbServerStub); + + UsbServerStub() = default; + virtual ~UsbServerStub() = default; + + virtual int32_t OnFoundDevice(FoundDevice &info) = 0; + + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + const FoundDevice *ParserOpenDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + int32_t DoGetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoUsbFunctionsFromString(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoUsbFunctionsToString(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + int32_t DoOpenDevice(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoHasRight(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestRight(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetPorts(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetSupportedModes(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetPortRole(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoClaimInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoReleaseInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoBulkTransferRead(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoBulkTransferWrite(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoControlTransfer(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetRawDescriptor(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestQueue(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestWait(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestCancel(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + int32_t DoClose(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetDevices(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + void WriteUsbPort(MessageParcel &reply, const UsbPort *port); + + int32_t GetDeviceMessage(MessageParcel &data, uint8_t &busNum, uint8_t &devAddr); + int32_t SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length); + int32_t GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length); + + int32_t SetDeviceListMessageParcel(std::vector &deviceList, MessageParcel &data); + int32_t SetDeviceMessageParcel(UsbDevice &devInfo, MessageParcel &data); + int32_t SetDeviceConfigsMessageParcel(std::vector &configs, MessageParcel &data); + int32_t SetDeviceInterfacesMessageParcel(std::vector &interfaces, MessageParcel &data); + int32_t SetDeviceEndpointsMessageParcel(std::vector &eps, MessageParcel &data); +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVER_STUB_H diff --git a/services/zidl/iusb_server.zidl b/services/zidl/iusb_server.zidl new file mode 100644 index 00000000..c0dc2568 --- /dev/null +++ b/services/zidl/iusb_server.zidl @@ -0,0 +1,19 @@ +/* + * Copyright 2021 Huawei Device Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface OHOS.Usb.IUsbServer { + /* the function about UsbService */ +} diff --git a/services/zidl/src/usb_srv_proxy.cpp b/services/zidl/src/usb_srv_proxy.cpp new file mode 100644 index 00000000..bb854db9 --- /dev/null +++ b/services/zidl/src/usb_srv_proxy.cpp @@ -0,0 +1,887 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ipc_types.h" +#include "message_parcel.h" +#include "securec.h" +#include "usb_common.h" +#include "usb_request.h" +#include "usb_server_proxy.h" + +namespace OHOS { +namespace USB { + +void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " < binary data [" << length << "bytes] > :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " -> " << buffer << std::endl; + USB_HILOGD(MODULE_USBD, "%{public}s", oss.str().c_str()); +} + +int32_t UsbServerProxy::SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr) +{ + WRITE_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerProxy::SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length) +{ + if (!data.WriteUint32(length)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && !data.WriteBuffer(buffer, length)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbServerProxy::GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length) +{ + uint32_t dataSize; + if (!data.ReadUint32(dataSize)) { + return ERR_INVALID_VALUE; + } + if (dataSize == 0) { + length = 0; + return ERR_OK; + } + if (!buffer) { + length = 0; + return ERR_INVALID_VALUE; + } + const uint8_t *readData = data.ReadBuffer(dataSize); + if (readData == nullptr) { + return ERR_INVALID_VALUE; + } + memcpy_s(buffer, length, readData, dataSize); + length = dataSize < length ? dataSize : length; + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d", __func__, length); + return ERR_OK; +} + +int32_t UsbServerProxy::GetDevices(std::vector &deviceList) +{ + int32_t ret; + sptr remote = Remote(); + if (remote == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s remote is failed", __func__); + return ERR_INVALID_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_INVALID_VALUE; + } + + ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_DEVICES), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s failed code: %{public}d", __func__, ret); + return ret; + } + ret = GetDeviceListMessageParcel(reply, deviceList); + return ret; +} + +int32_t UsbServerProxy::GetDeviceListMessageParcel(MessageParcel &data, std::vector &deviceList) +{ + int32_t count; + data.ReadInt32(count); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s device size : %{public}d", __func__, count); + + for (int32_t i = 0; i < count; ++i) { + UsbDevice devInfo; + GetDeviceMessageParcel(data, devInfo); + deviceList.push_back(devInfo); + } + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceMessageParcel(MessageParcel &data, UsbDevice &devInfo) +{ + int32_t tmp; + uint8_t tui8; + uint16_t tui16; + std::string tstr; + data.ReadInt32(tmp); + devInfo.SetBusNum(tmp); + data.ReadInt32(tmp); + devInfo.SetDevAddr(tmp); + + data.ReadInt32(tmp); + devInfo.SetVendorId(tmp); + data.ReadInt32(tmp); + devInfo.SetProductId(tmp); + data.ReadInt32(tmp); + devInfo.SetClass(tmp); + data.ReadInt32(tmp); + devInfo.SetSubclass(tmp); + data.ReadInt32(tmp); + devInfo.SetProtocol(tmp); + data.ReadUint8(tui8); + devInfo.SetiManufacturer(tui8); + data.ReadUint8(tui8); + devInfo.SetiProduct(tui8); + data.ReadUint8(tui8); + devInfo.SetiSerialNumber(tui8); + data.ReadUint8(tui8); + devInfo.SetbMaxPacketSize0(tui8); + data.ReadUint16(tui16); + devInfo.SetbcdUSB(tui16); + data.ReadUint16(tui16); + devInfo.SetbcdDevice(tui16); + data.ReadString(tstr); + devInfo.SetName(tstr); + data.ReadString(tstr); + devInfo.SetManufacturerName(tstr); + data.ReadString(tstr); + devInfo.SetProductName(tstr); + data.ReadString(tstr); + devInfo.SetVersion(tstr); + data.ReadString(tstr); + devInfo.SetmSerial(tstr); + + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:%{public}d devName:%{public}s Bus:%{public}d dev:%{public}d ", __func__, + __LINE__, devInfo.GetName().c_str(), devInfo.GetBusNum(), devInfo.GetDevAddr()); + std::vector configs; + GetDeviceConfigsMessageParcel(data, configs); + devInfo.SetConfigs(configs); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s ToString : %{public}s", __func__, devInfo.ToString().c_str()); + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceConfigsMessageParcel(MessageParcel &data, std::vector &configs) +{ + int32_t tmp, configCount; + uint8_t tui8; + std::string tstr; + data.ReadInt32(tmp); + configCount = tmp; + for (int i = 0; i < configCount; ++i) { + USBConfig config; + data.ReadInt32(tmp); + config.SetId(tmp); + data.ReadInt32(tmp); + config.SetAttribute(tmp); + data.ReadInt32(tmp); + config.SetMaxPower(tmp); + + data.ReadUint8(tui8); + config.SetiConfiguration(tui8); + data.ReadString(tstr); + config.SetName(tstr); + + std::vector interfaces; + GetDeviceInterfacesMessageParcel(data, interfaces); + config.SetInterfaces(interfaces); + configs.push_back(config); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, config.ToString().c_str()); + } + + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceInterfacesMessageParcel(MessageParcel &data, std::vector &interfaces) +{ + int32_t tmp, interfaceCount; + uint8_t tui8; + std::string tstr; + data.ReadInt32(tmp); + interfaceCount = tmp; + for (int i = 0; i < interfaceCount; ++i) { + UsbInterface interface; + data.ReadInt32(tmp); + interface.SetId(tmp); + data.ReadInt32(tmp); + interface.SetClass(tmp); + data.ReadInt32(tmp); + interface.SetSubClass(tmp); + data.ReadInt32(tmp); + interface.SetAlternateSetting(tmp); + data.ReadInt32(tmp); + interface.SetProtocol(tmp); + + data.ReadUint8(tui8); + interface.SetiInterface(tui8); + data.ReadString(tstr); + interface.SetName(tstr); + + std::vector eps; + GetDeviceEndpointsMessageParcel(data, eps); + for (size_t j = 0; j < eps.size(); ++j) { + eps[j].SetInterfaceId(interface.GetId()); + } + interface.SetEndpoints(eps); + interfaces.push_back(interface); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, interface.ToString().c_str()); + } + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceEndpointsMessageParcel(MessageParcel &data, std::vector &eps) +{ + int32_t tmp, epCount; + data.ReadInt32(tmp); + epCount = tmp; + for (int i = 0; i < epCount; ++i) { + USBEndpoint ep; + data.ReadInt32(tmp); + ep.SetAddr(tmp); + data.ReadInt32(tmp); + ep.SetAttr(tmp); + data.ReadInt32(tmp); + ep.SetInterval(tmp); + data.ReadInt32(tmp); + ep.SetMaxPacketSize(tmp); + eps.push_back(ep); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, ep.ToString().c_str()); + } + return ERR_OK; +} + +int32_t UsbServerProxy::OpenDevice(uint8_t busNum, uint8_t devAddr) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_OPEN_DEVICE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %{public}d", + __func__, ret); + return ret; + } + return ret; +} + +int32_t UsbServerProxy::HasRight(std::string deviceName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + WRITE_PARCEL_WITH_RET(data, String, deviceName, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_HAS_RIGHT), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + int32_t result = 0; + READ_PARCEL_WITH_RET(reply, Int32, result, E_READ_PARCEL_ERROR); + return result; +} + +int32_t UsbServerProxy::RequestRight(std::string deviceName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + WRITE_PARCEL_WITH_RET(data, String, deviceName, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_RIGHT), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + int32_t result = 0; + READ_PARCEL_WITH_RET(reply, Int32, result, E_READ_PARCEL_ERROR); + return result; +} + +int32_t UsbServerProxy::GetCurrentFunctions(int32_t &funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, INVALID_USB_INT_VALUE); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_CURRENT_FUNCTIONS), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + + READ_PARCEL_WITH_RET(reply, Int32, funcs, INVALID_USB_INT_VALUE); + return ret; +} + +int32_t UsbServerProxy::SetCurrentFunctions(int32_t funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + + data.WriteInt32(funcs); + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_CURRENT_FUNCTIONS), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + return ret; +} + +int32_t UsbServerProxy::UsbFunctionsFromString(std::string funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, INVALID_USB_INT_VALUE); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + + data.WriteString(funcs); + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_FROM_STRING), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + + int32_t result = 0; + READ_PARCEL_WITH_RET(reply, Int32, result, INVALID_USB_INT_VALUE); + return result; +} + +std::string UsbServerProxy::UsbFunctionsToString(int32_t funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, INVALID_STRING_VALUE); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_STRING_VALUE; + } + + data.WriteInt32(funcs); + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_TO_STRING), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_STRING_VALUE; + } + + std::string result; + READ_PARCEL_WITH_RET(reply, String, result, result); + return result; +} + +int32_t UsbServerProxy::GetPorts(std::vector &result) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_PORTS), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + ret = reply.ReadInt32(); + USB_HILOGI(MODULE_USB_INNERKIT, "GetPorts ret %{public}d", ret); + if (ret != 0) { + return ret; + } + uint32_t size = reply.ReadInt32(); + USB_HILOGI(MODULE_USB_INNERKIT, "GetPorts size %{public}d", size); + for (uint32_t i = 0; i < size; ++i) { + USB_HILOGI(MODULE_USB_INNERKIT, "ParseUsbPort : %{public}d", i); + ParseUsbPort(reply, result); + } + return ret; +} + +void UsbServerProxy::ParseUsbPort(MessageParcel &reply, std::vector &ports) +{ + UsbPort *port = new UsbPort(); + UsbPortStatus *status = new UsbPortStatus(); + port->id = reply.ReadInt32(); + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::port->id %{public}d", port->id); + port->supportedModes = reply.ReadInt32(); + port->usbPortStatus = status; + status->currentMode = reply.ReadInt32(); + status->currentPowerRole = reply.ReadInt32(); + status->currentDataRole = reply.ReadInt32(); + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::port->usbPortStatus->currentMode %{public}d", + port->usbPortStatus->currentMode); + ports.push_back(port); + return; +} + +int32_t UsbServerProxy::GetSupportedModes(int32_t portId, int32_t &supportedModes) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + data.WriteInt32(portId); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_SUPPORTED_MODES), data, reply, option); + if (ret) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + ret = reply.ReadInt32(); + supportedModes = reply.ReadInt32(); + return ret; +} + +int32_t UsbServerProxy::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + data.WriteInt32(portId); + data.WriteInt32(powerRole); + data.WriteInt32(dataRole); + int32_t ret = Remote()->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_PORT_ROLE), data, reply, option); + if (ret) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t UsbServerProxy::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_CLAIM_INTERFACE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %{public}d", + __func__, ret); + return ret; + } + return ret; +} +int32_t UsbServerProxy::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_RELEASE_INTERFACE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + // int32_t ret = ERR_OK; + // READ_PARCEL_WITH_RET(reply, Int32, ret, E_READ_PARCEL_ERROR); + return ret; +} +int32_t UsbServerProxy::BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!buffer || (length == 0)) { + USB_HILOGW(MODULE_USBD, "%{public}s buffer is null or length is zero, length = %{public}d", __func__, length); + return ERR_INVALID_VALUE; + } + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_READ), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + ret = GetBufferMessage(reply, buffer, length); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s get buffer is failed, error code: %d", __func__, + ret); + return ret; + } + USB_HILOGW(MODULE_USBD, "%{public}s Set buffer message. length = %{public}d", __func__, length); + return ret; +} +int32_t UsbServerProxy::BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + PrintBuffer("UsbServerProxy::BulkTransferWrite", (const uint8_t *)buffer, length); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + data.WriteUint8(interface); + data.WriteUint8(endpoint); + data.WriteUint32(timeout); + SetBufferMessage(data, buffer, length); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_WRITE), data, reply, option); + return ret; +} + +int32_t UsbServerProxy::ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, requestType, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, request, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, value, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, index, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + bool bWrite = ((requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT); + if (bWrite) { + data.WriteBuffer(buffer, length); + } + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_CONTROL_TRANSFER), data, reply, option); + if (ret != ERR_OK) { + return ret; + } + if (!bWrite) { + GetBufferMessage(reply, buffer, length); + PrintBuffer("UsbServerProxy::ControlTransfer", buffer, length); + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d", __func__, length); + } + return ERR_OK; +} +int32_t UsbServerProxy::SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, configIndex, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_ACTIVE_CONFIG), data, reply, option); + return ret; +} +int32_t UsbServerProxy::GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_ACTIVE_CONFIG), data, reply, option); + if (ret != ERR_OK) { + return ret; + } + READ_PARCEL_WITH_RET(reply, Uint8, configIndex, E_WRITE_PARCEL_ERROR); + return ret; +} +int32_t UsbServerProxy::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, altIndex, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_INTERFACE), data, reply, option); + return ret; +} +int32_t UsbServerProxy::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_DESCRIPTOR), data, reply, option); + if (ret == ERR_OK) { + GetBufferMessage(reply, buffer, length); + } + return ret; +} + +int32_t UsbServerProxy::RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientObj, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, ifId, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpointId, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, clientObj, clientLength); + SetBufferMessage(data, buffer, length); + // PrintBuffer("UsbServerProxy::RequestQueue buffer", buffer, length); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_QUEUE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s queue failed!", __func__); + return ret; + } + return ret; +} + +int32_t UsbServerProxy::RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_WAIT), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s:%{public}d queue failed! ret:%{public}d", __func__, + __LINE__, ret); + return ret; + } + + ret = GetBufferMessage(reply, clientData, clientLength); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s:%{public}d get clientData failed! ret:%{public}d", + __func__, __LINE__, ret); + clientLength = 0; + length = 0; + return ret; + } + ret = GetBufferMessage(reply, buffer, length); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s:%{public}d get buffer failed! ret:%{public}d", __func__, + __LINE__, ret); + return ret; + } + PrintBuffer("UsbServerProxy::RequestWait buffer", buffer, length); + return ret; +} + +int32_t UsbServerProxy::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) +{ + int32_t ret; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpointId, E_WRITE_PARCEL_ERROR); + ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_CANCEL), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s request cancel failed!", __func__); + } + + return ret; +} + +int32_t UsbServerProxy::Close(uint8_t busNum, uint8_t devAddr) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_CLOSE_DEVICE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s queue failed!", __func__); + return ret; + } + + return ERR_OK; +} + +} // namespace USB +} // namespace OHOS diff --git a/services/zidl/src/usb_srv_stub.cpp b/services/zidl/src/usb_srv_stub.cpp new file mode 100644 index 00000000..b5ac468d --- /dev/null +++ b/services/zidl/src/usb_srv_stub.cpp @@ -0,0 +1,663 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "message_parcel.h" +#include "securec.h" +#include "usb_common.h" +#include "usb_server_proxy.h" +#include "usb_server_stub.h" + +namespace OHOS { +namespace USB { + +const uint32_t MAX_REQUEST_BUFFER_SIZE = 1024; + +void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << BINARY DATA [" << length << "bytes] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_SERVICE, "%{public}s", oss.str().c_str()); +} + +int32_t UsbServerStub::GetDeviceMessage(MessageParcel &data, uint8_t &busNum, uint8_t &devAddr) +{ + if (!data.ReadUint8(busNum)) { + return ERR_INVALID_VALUE; + } + if (!data.ReadUint8(devAddr)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbServerStub::SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length) +{ + if (!data.WriteUint32(length)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && !data.WriteBuffer(buffer, length)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbServerStub::GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length) +{ + uint32_t dataSize; + if (!data.ReadUint32(dataSize)) { + return ERR_INVALID_VALUE; + } + if (dataSize == 0) { + length = 0; + return ERR_OK; + } + if (!buffer) { + length = 0; + return ERR_INVALID_VALUE; + } + const uint8_t *readData = data.ReadBuffer(dataSize); + if (readData == nullptr) { + return ERR_INVALID_VALUE; + } + memcpy_s(buffer, length, readData, dataSize); + length = dataSize < length ? dataSize : length; + return ERR_OK; +} +const FoundDevice *UsbServerStub::ParserOpenDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + + return nullptr; +} + +int UsbServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + USB_HILOGD(MODULE_USB_SERVICE, "UsbServerStub::OnRemoteRequest, cmd = %{public}d, flags = %{public}d", code, + option.GetFlags()); + std::u16string descriptor = UsbServerStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + USB_HILOGE(MODULE_SERVICE, "UsbServerStub::OnRemoteRequest failed, descriptor is not matched!"); + return E_GET_USB_SERVICE_FAILED; + } + + switch (code) { + case static_cast(IUsbSrv::USB_FUN_OPEN_DEVICE): { + return DoOpenDevice(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_HAS_RIGHT): { + return DoHasRight(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_RIGHT): { + return DoRequestRight(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_PORTS): { + return DoGetPorts(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_SUPPORTED_MODES): { + return DoGetSupportedModes(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_PORT_ROLE): { + return DoSetPortRole(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_CLAIM_INTERFACE): { + return DoClaimInterface(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_RELEASE_INTERFACE): { + return DoReleaseInterface(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_READ): { + return DoBulkTransferRead(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_WRITE): { + return DoBulkTransferWrite(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_CONTROL_TRANSFER): { + return DoControlTransfer(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_DEVICES): { + return DoGetDevices(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_CURRENT_FUNCTIONS): { + return DoGetCurrentFunctions(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_CURRENT_FUNCTIONS): { + return DoSetCurrentFunctions(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_FROM_STRING): { + return DoUsbFunctionsFromString(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_TO_STRING): { + return DoUsbFunctionsToString(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_CLOSE_DEVICE): { + return DoClose(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_QUEUE): { + return DoRequestQueue(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_WAIT): { + return DoRequestWait(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_INTERFACE): { + return DoSetInterface(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_ACTIVE_CONFIG): { + return DoSetActiveConfig(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_CANCEL): { + return DoRequestCancel(data, reply, option); + } + + /* + case static_cast(IUsbServer::USB_NOTICE_ADD_DEVICE): { + const OpenDeviceInfo *info = ParserOpenDeviceInfo(data, + reply, option); return NoticeAddDevice(info); + } + break; + */ + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + + return ERR_OK; +} + +int32_t UsbServerStub::DoGetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t funcs; + int32_t ret = GetCurrentFunctions(funcs); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Int32, funcs, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoSetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t funcs; + data.ReadInt32(funcs); + bool ret = SetCurrentFunctions(funcs); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Bool, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoUsbFunctionsFromString(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::string funcs; + data.ReadString(funcs); + int32_t ret = UsbFunctionsFromString(funcs); + WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoUsbFunctionsToString(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t funcs; + data.ReadInt32(funcs); + std::string ret = UsbFunctionsToString(funcs); + WRITE_PARCEL_WITH_RET(reply, String, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoOpenDevice(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_READ_PARCEL_ERROR); + // int32_t fd; + int32_t ret = OpenDevice(busNum, devAddr); + if (ret != ERR_OK) { + return ret; + } + + // WRITE_PARCEL_WITH_RET(reply, Int32, fd, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoHasRight(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::string deviceName = ""; + READ_PARCEL_WITH_RET(data, String, deviceName, E_READ_PARCEL_ERROR); + int32_t ret = HasRight(deviceName); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoRequestRight(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::string deviceName = ""; + READ_PARCEL_WITH_RET(data, String, deviceName, E_READ_PARCEL_ERROR); + int32_t ret = RequestRight(deviceName); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoGetPorts(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::vector ports; + int ret = GetPorts(ports); + USB_HILOGI(MODULE_SERVICE, "UsbServerStub::GetPorts ret %{public}d ", ret); + reply.WriteInt32(ret); + if (ret != ERR_OK) { + return ret; + } + unsigned int size = ports.size(); + USB_HILOGI(MODULE_SERVICE, "UsbServerStub::GetPorts size %{public}d ", size); + reply.WriteInt32(size); + for (unsigned int i = 0; i < size; ++i) { + WriteUsbPort(reply, ports[i]); + } + return ERR_OK; +} + +void UsbServerStub::WriteUsbPort(MessageParcel &reply, const UsbPort *port) +{ + reply.WriteInt32(port->id); + reply.WriteInt32(port->supportedModes); + reply.WriteInt32(port->usbPortStatus->currentMode); + reply.WriteInt32(port->usbPortStatus->currentPowerRole); + reply.WriteInt32(port->usbPortStatus->currentDataRole); + USB_HILOGI(MODULE_SERVICE, "UsbServerStub::GetPorts supportedModes %{public}d ", port->supportedModes); + return; +} + +int32_t UsbServerStub::DoGetSupportedModes(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t supportedModes = 0; + int32_t portId = 0; + portId = data.ReadInt32(); + int32_t ret = GetSupportedModes(portId, supportedModes); + if (ret != ERR_OK) { + return ret; + } + reply.WriteInt32(ret); + reply.WriteInt32(supportedModes); + return ERR_OK; +} + +int32_t UsbServerStub::DoSetPortRole(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + portId = data.ReadInt32(); + powerRole = data.ReadInt32(); + dataRole = data.ReadInt32(); + int32_t ret = SetPortRole(portId, powerRole, dataRole); + if (ret != ERR_OK) { + return ret; + } + reply.WriteInt32(ret); + return ERR_OK; +} + +int32_t UsbServerStub::DoClaimInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t interface; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_READ_PARCEL_ERROR); + return ClaimInterface(busNum, devAddr, interface); +} +int32_t UsbServerStub::DoReleaseInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t interface; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_READ_PARCEL_ERROR); + return ReleaseInterface(busNum, devAddr, interface); +} + +int32_t UsbServerStub::DoBulkTransferRead(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, interface, endpoint; + int32_t timeout = 0; + uint32_t length; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + uint8_t *buffer = new uint8_t[length]; + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + int32_t ret = BulkTransferRead(busNum, devAddr, interface, endpoint, buffer, length, timeout); + if (ret != ERR_OK) { + delete[] buffer; + return ret; + } + SetBufferMessage(reply, buffer, length); + USB_HILOGW(MODULE_USBD, "%{public}s Set buffer message. length = %{public}d", __func__, length); + delete[] buffer; + return ERR_OK; +} + +int32_t UsbServerStub::DoBulkTransferWrite(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, interface, endpoint; + int32_t timeout = 0; + uint32_t length = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + const uint8_t *buffer = data.ReadBuffer(length); + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + PrintBuffer("UsbServerStub::DoBulkTransferWrite", (const uint8_t *)buffer, length); + int32_t ret = BulkTransferWrite(busNum, devAddr, interface, endpoint, buffer, length, timeout); + return ret; +} + +int32_t UsbServerStub::DoControlTransfer(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + int32_t requestType, request, value, index, timeout; + uint32_t length; + uint8_t *buffer = nullptr; + + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, requestType, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, request, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, value, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, index, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + + buffer = new uint8_t[length]; + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + // 写数据 + bool bWrite = ((requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT); + if (bWrite) { + const uint8_t *dataBuffer = data.ReadBuffer(length); + memcpy_s(buffer, length, dataBuffer, length); + } + int32_t ret = ControlTransfer(busNum, devAddr, requestType, request, value, index, buffer, length, timeout); + if (ret != ERR_OK) { + delete[] buffer; + return ret; + } + // 读数据 + if (!bWrite && buffer != nullptr) { + SetBufferMessage(reply, buffer, length); + USB_HILOGW(MODULE_USBD, "%{public}s Set buffer message. length = %{public}d", __func__, length); + PrintBuffer("UsbServerStub::DoControlTransfer", buffer, length); + } + + delete[] buffer; + return ERR_OK; +} + +int32_t UsbServerStub::DoSetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, config = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, config, E_WRITE_PARCEL_ERROR); + return SetActiveConfig(busNum, devAddr, config); +} + +int32_t UsbServerStub::DoGetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, config = 0; + int32_t ret; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + ret = GetActiveConfig(busNum, devAddr, config); + if (ret == ERR_OK) { + reply.WriteUint8(config); + } + return ret; +} + +int32_t UsbServerStub::DoSetInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, interfaceId, altIndex = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interfaceId, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, altIndex, E_WRITE_PARCEL_ERROR); + return SetInterface(busNum, devAddr, interfaceId, altIndex); +} + +int32_t UsbServerStub::DoGetRawDescriptor(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t ret = ERR_OK; + uint8_t busNum = 0, devAddr = 0; + uint32_t length = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + uint8_t *buffer = new uint8_t[length]; + ret = GetRawDescriptor(busNum, devAddr, buffer, length); + if (ret == ERR_OK) { + SetBufferMessage(reply, buffer, length); + } + delete[] buffer; + return ret; +} + +int32_t UsbServerStub::DoRequestQueue(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, ifId = 0, endpoint; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, ifId, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + uint32_t clientLength = 0; + READ_PARCEL_WITH_RET(data, Uint32, clientLength, E_WRITE_PARCEL_ERROR); + const uint8_t *clientObj = data.ReadBuffer(clientLength); + uint32_t length; + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + const uint8_t *buffer = data.ReadBuffer(length); + // PrintBuffer("UsbServerStub::DoRequestQueue buffer", buffer, length); + return RequestQueue(busNum, devAddr, ifId, endpoint, (void *)clientObj, clientLength, (uint8_t *)buffer, length); +} + +int32_t UsbServerStub::DoRequestWait(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t *clientObj = nullptr, *buffer = nullptr; + uint32_t clientLength, length = 0; + int32_t timeout; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + clientLength = MAX_REQUEST_BUFFER_SIZE; + clientObj = new uint8_t[clientLength]; + length = MAX_REQUEST_BUFFER_SIZE; + buffer = new uint8_t[length]; + int32_t ret = RequestWait(busNum, devAddr, timeout, (void *)clientObj, clientLength, buffer, length); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s:%{public}d failed ret:%{public}d", __func__, __LINE__, ret); + delete[] clientObj; + delete[] buffer; + return ret; + } + + // PrintBuffer("UsbServerStub::DoRequestWait buffer", buffer, length); + SetBufferMessage(reply, clientObj, clientLength); + SetBufferMessage(reply, buffer, length); + delete[] clientObj; + delete[] buffer; + return ERR_OK; +} + +int32_t UsbServerStub::DoRequestCancel(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t interfaceId, endpointId; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interfaceId, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpointId, E_WRITE_PARCEL_ERROR); + int32_t ret = RequestCancel(busNum, devAddr, interfaceId, endpointId); + return ret; +} + +int32_t UsbServerStub::DoClose(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + int32_t ret = Close(busNum, devAddr); + return ret; +} + +int32_t UsbServerStub::DoGetDevices(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t ret = -1; + std::vector deviceList; + ret = GetDevices(deviceList); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_SERVICE, "%{public}s: failed ret = %{public}d", __func__, ret); + return ret; + } + USB_HILOGE(MODULE_SERVICE, "%{public}s: list size = %{public}d", __func__, deviceList.size()); + // ret = SetDevicesMapToMessageParcel(devices, data); + ret = SetDeviceListMessageParcel(deviceList, reply); + return ret; +} + +int32_t UsbServerStub::SetDeviceListMessageParcel(std::vector &deviceList, MessageParcel &data) +{ + int32_t deviceCount = (int32_t)deviceList.size(); + data.WriteInt32(deviceCount); + for (int32_t i = 0; i < deviceCount; ++i) { + UsbDevice &devInfo = deviceList[i]; + SetDeviceMessageParcel(devInfo, data); + } + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceMessageParcel(UsbDevice &devInfo, MessageParcel &data) +{ + data.WriteInt32(devInfo.GetBusNum()); + data.WriteInt32(devInfo.GetDevAddr()); + + data.WriteInt32(devInfo.GetVendorId()); + data.WriteInt32(devInfo.GetProductId()); + data.WriteInt32(devInfo.GetClass()); + data.WriteInt32(devInfo.GetSubclass()); + data.WriteInt32(devInfo.GetProtocol()); + data.WriteUint8(devInfo.GetiManufacturer()); + data.WriteUint8(devInfo.GetiProduct()); + data.WriteUint8(devInfo.GetiSerialNumber()); + data.WriteUint8(devInfo.GetbMaxPacketSize0()); + data.WriteUint16(devInfo.GetbcdUSB()); + data.WriteUint16(devInfo.GetbcdDevice()); + data.WriteString(devInfo.GetName()); + data.WriteString(devInfo.GetManufacturerName()); + data.WriteString(devInfo.GetProductName()); + data.WriteString(devInfo.GetVersion()); + data.WriteString(devInfo.GetmSerial()); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:%{public}d devName:%{public}s Bus:%{public}d dev:%{public}d ", __func__, + __LINE__, devInfo.GetName().c_str(), devInfo.GetBusNum(), devInfo.GetDevAddr()); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:%{public}d devInfo:%{public}s", __func__, __LINE__, + devInfo.ToString().c_str()); + data.WriteInt32(devInfo.GetConfigCount()); + SetDeviceConfigsMessageParcel(devInfo.GetConfigs(), data); + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceConfigsMessageParcel(std::vector &configs, MessageParcel &data) +{ + for (auto it = configs.begin(); it != configs.end(); ++it) { + USBConfig config = *it; + data.WriteInt32(config.GetId()); + data.WriteInt32(config.GetAttributes()); + data.WriteInt32(config.GetMaxPower()); + + data.WriteUint8(config.GetiConfiguration()); + data.WriteString(config.GetName()); + + data.WriteInt32(config.GetInterfaceCount()); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, config.ToString().c_str()); + SetDeviceInterfacesMessageParcel(config.GetInterfaces(), data); + } + + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceInterfacesMessageParcel(std::vector &interfaces, MessageParcel &data) +{ + for (auto it = interfaces.begin(); it != interfaces.end(); ++it) { + UsbInterface interface = *it; + data.WriteInt32(interface.GetId()); + data.WriteInt32(interface.GetClass()); + data.WriteInt32(interface.GetSubClass()); + data.WriteInt32(interface.GetAlternateSetting()); + data.WriteInt32(interface.GetProtocol()); + + data.WriteUint8(interface.GetiInterface()); + data.WriteString(interface.GetName()); + + data.WriteInt32(interface.GetEndpointCount()); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, interface.ToString().c_str()); + SetDeviceEndpointsMessageParcel(interface.GetEndpoints(), data); + } + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceEndpointsMessageParcel(std::vector &eps, MessageParcel &data) +{ + for (auto it = eps.begin(); it != eps.end(); ++it) { + USBEndpoint ep = *it; + data.WriteInt32(ep.GetAddress()); + data.WriteInt32(ep.GetAttributes()); + data.WriteInt32(ep.GetInterval()); + data.WriteInt32(ep.GetMaxPacketSize()); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, ep.ToString().c_str()); + } + return ERR_OK; +} + +} // namespace USB +} // namespace OHOS diff --git a/test/native/BUILD.gn b/test/native/BUILD.gn new file mode 100644 index 00000000..7284925b --- /dev/null +++ b/test/native/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("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +group("usbmgr_native_test") { + testonly = true + deps = [ "unittest:unittest" ] +} diff --git a/test/native/unittest/BUILD.gn b/test/native/unittest/BUILD.gn new file mode 100644 index 00000000..fe13f76b --- /dev/null +++ b/test/native/unittest/BUILD.gn @@ -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. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +module_output_path = "${usb_manager_native_part_name}/usb_manager_native" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "${usb_manager_path}/hdi/api/include", + "${usb_manager_path}/hdi/client/include", + ] +} + +deps_ex = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ipc:ipc_core", + "hiviewdfx_hilog_native:libhilog", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", +] + + +##############################unittest########################################## +ohos_unittest("test_usb_mgr_service") { + module_out_path = module_output_path + + sources = [ "src/usb_service_test.cpp" ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "//base/usb/usb_manager/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = deps_ex +} + +group("unittest") { + testonly = true + deps = [ + ":test_usb_mgr_service", + ] +} + + + diff --git a/test/native/unittest/include/usb_service_test.h b/test/native/unittest/include/usb_service_test.h new file mode 100644 index 00000000..9055be77 --- /dev/null +++ b/test/native/unittest/include/usb_service_test.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_SERVICE_TEST_H +#define USB_SERVICE_TEST_H + +#include +#include + +class UsbServiceTest : public testing::Test { +public: + void HasRight(std::string deviceName) {} +}; +#endif // USB_SERVICE_TEST_H diff --git a/test/native/unittest/src/usb_service_test.cpp b/test/native/unittest/src/usb_service_test.cpp new file mode 100644 index 00000000..a00375a6 --- /dev/null +++ b/test/native/unittest/src/usb_service_test.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_service_test.h" + +#include +#include + +#include "usb_service.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +/** + * @tc.name: DisplayMgrService01 + * @tc.desc: Test DisplayMgrService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService01, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService01 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; +} + +/** + * @tc.name: UsbService02 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService02, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService02 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() == 0) << "UsbService02 Devices count is 0"; + + cout << "Please insert a USB device\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs1 = proxy_->GetDevices(); + EXPECT_TRUE(devs1.size() != 0) << "UsbService02 Devices count is not 0"; + + cout << "Please unplug the USB device\nPress any key to continue..." << endl; + // system("pause"); + // int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs2 = proxy_->GetDevices(); + EXPECT_TRUE(devs2.size() == 0) << "UsbService02 Devices count is 0"; +} + +/** + * @tc.name: UsbService03 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService03, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService03 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a normal USB device\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService03 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasMidi() == false) << "HasMidi is false"; + EXPECT_TRUE(iter->second->GetHasAudioCapture() == false) << "HasAudioCapture is false"; + EXPECT_TRUE(iter->second->GetHasAudioPlayback() == false) << "HasAudioPlayback is false"; + EXPECT_TRUE(iter->second->GetHasVideoCapture() == false) << "HasVideoCapture is false"; + EXPECT_TRUE(iter->second->GetHasVideoPlayback() == false) << "HasVideoPlayBack is false"; +} + +/** + * @tc.name: UsbService04 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService04, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService04 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a Midi USB device\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService04 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasMidi() == true) << "HasMidi is true"; +} + +/** + * @tc.name: UsbService05 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService05, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService05 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with no AudioPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService05 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasAudioCapture() == true) << "HasAudioCapture is true"; + EXPECT_TRUE(iter->second->GetHasAudioPlayback() == false) << "HasAudioPlayback is false"; +} + +/** + * @tc.name: UsbService06 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService06, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService06 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with AudioPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService06 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasAudioCapture() == true) << "HasAudioCapture is true"; + EXPECT_TRUE(iter->second->GetHasAudioPlayback() == true) << "HasAudioPlayback is true"; +} + +/** + * @tc.name: UsbService07 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService07, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService07 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with no VideoPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService07 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasVideoCapture() == true) << "HasVideoCapture is true"; + EXPECT_TRUE(iter->second->GetHasVideoPlayback() == false) << "HasVideoPlayBack is false"; +} + +/** + * @tc.name: UsbService08 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService08, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService08 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with VideoPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService08 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasVideoCapture() == true) << "HasVideoCapture is true"; + EXPECT_TRUE(iter->second->GetHasVideoPlayback() == true) << "HasVideoPlayBack is true"; +} diff --git a/usbmgr.gni b/usbmgr.gni new file mode 100644 index 00000000..b00cad92 --- /dev/null +++ b/usbmgr.gni @@ -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. + +import("//build/ohos.gni") + +usb_manager_path = "//base/usb/usb_manager" +usb_manager_native_part_name = "usb_manager_native" +utils_path = "${usb_manager_path}/utils" diff --git a/utils/BUILD.gn b/utils/BUILD.gn new file mode 100644 index 00000000..2d3f04e6 --- /dev/null +++ b/utils/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("utils_config") { + include_dirs = [ + "native/include", + "//utils/native/base/include", + ] +} diff --git a/utils/native/include/delayed_sp_singleton.h b/utils/native/include/delayed_sp_singleton.h new file mode 100644 index 00000000..7946c41b --- /dev/null +++ b/utils/native/include/delayed_sp_singleton.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DELAYED_SP_SINGLETON_H +#define DELAYED_SP_SINGLETON_H + +#include +#include +#include +#include "nocopyable.h" + +namespace OHOS { +namespace USB { +template class DelayedSpSingleton : public NoCopyable { +public: + static sptr GetInstance(); + static void DestroyInstance(); + +private: + static sptr instance_; + static std::mutex mutex_; +}; + +template sptr DelayedSpSingleton::instance_ = nullptr; + +template std::mutex DelayedSpSingleton::mutex_; + +template sptr DelayedSpSingleton::GetInstance() +{ + if (!instance_) { + std::lock_guard lock(mutex_); + if (instance_ == nullptr) { + instance_ = new T(); + } + } + + return instance_; +} + +template void DelayedSpSingleton::DestroyInstance() +{ + std::lock_guard lock(mutex_); + if (instance_) { + instance_.clear(); + instance_ = nullptr; + } +} +} // namespace USB +} // namespace OHOS +#endif // DELAYED_SP_SINGLETON_H diff --git a/utils/native/include/hilog_wrapper.h b/utils/native/include/hilog_wrapper.h new file mode 100644 index 00000000..aca7bea4 --- /dev/null +++ b/utils/native/include/hilog_wrapper.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HILOG_WRAPPER_H +#define HILOG_WRAPPER_H + +#define CONFIG_HILOG +#ifdef CONFIG_HILOG +#include "hilog/log.h" +namespace OHOS { +namespace USB { +#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) +#define __FORMATED(fmt, ...) "[%{public}s] %{public}s# " fmt, __FILENAME__, __FUNCTION__, ##__VA_ARGS__ + +#ifdef USB_HILOGF +#undef USB_HILOGF +#endif + +#ifdef USB_HILOGE +#undef USB_HILOGE +#endif + +#ifdef USB_HILOGW +#undef USB_HILOGW +#endif + +#ifdef USB_HILOGI +#undef USB_HILOGI +#endif + +#ifdef USB_HILOGD +#undef USB_HILOGD +#endif + +// param of log interface, such as USB_HILOGF. +enum UsbMgrSubModule { + MODULE_INNERKIT = 0, + MODULE_SERVICE, + MODULE_JAVAKIT, // java kit used, define to avoid repeat used domain + MODULE_JNI, + MODULE_USB_INNERKIT, // below used by usb service + MODULE_USB_SERVICE, + MODULE_USBD, + MODULE_COMMON, + MODULE_JS_NAPI, + USBMGR_MODULE_BUTT, +}; + +// 0xD002900: subsystem:Usb module:Usb, reserved 8 bit. +static constexpr unsigned int BASE_USB_DOMAIN_ID = 0xD002900; + +enum UsbMgrDomainId { + USBMGR_INNERKIT_DOMAIN = BASE_USB_DOMAIN_ID + MODULE_INNERKIT, + USBMGR_SERVICE_DOMAIN, + USBMGR_JAVAKIT_DOMAIN, // 0xD002902 + USB_INNERKIT_DOMAIN, + USB_SERVICE_DOMAIN, + USBD_DOMAIN, + COMMON_DOMAIN, + USB_JS_NAPI, + USB_BUTT, +}; + +static constexpr OHOS::HiviewDFX::HiLogLabel USB_MGR_LABEL[USBMGR_MODULE_BUTT] = { + {LOG_CORE, USBMGR_INNERKIT_DOMAIN, "UsbMgrClient"}, + {LOG_CORE, USBMGR_SERVICE_DOMAIN, "UsbMgrService"}, + {LOG_CORE, USBMGR_JAVAKIT_DOMAIN, "UsbMgrJavaService"}, + {LOG_CORE, USBMGR_INNERKIT_DOMAIN, "UsbMgrJni"}, + {LOG_CORE, USB_INNERKIT_DOMAIN, "UsbSrvClient"}, + {LOG_CORE, USB_SERVICE_DOMAIN, "UsbService"}, + {LOG_CORE, USBD_DOMAIN, "Usbd"}, + {LOG_CORE, COMMON_DOMAIN, "UsbMgrCommon"}, + {LOG_CORE, USB_JS_NAPI, "UsbMgrJSNAPI"}, +}; + +// In order to improve performance, do not check the module range, module should less than USBMGR_MODULE_BUTT. +#define USB_HILOGF(module, ...) (void)OHOS::HiviewDFX::HiLog::Fatal(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGE(module, ...) (void)OHOS::HiviewDFX::HiLog::Error(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGW(module, ...) (void)OHOS::HiviewDFX::HiLog::Warn(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGI(module, ...) (void)OHOS::HiviewDFX::HiLog::Info(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGD(module, ...) (void)OHOS::HiviewDFX::HiLog::Debug(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) + +} // namespace USB +} // namespace OHOS + +#else + +#define USB_HILOGF(...) +#define USB_HILOGE(...) +#define USB_HILOGW(...) +#define USB_HILOGI(...) +#define USB_HILOGD(...) + +#endif // CONFIG_HILOG + +#endif // HILOG_WRAPPER_H diff --git a/utils/native/include/usb_common.h b/utils/native/include/usb_common.h new file mode 100644 index 00000000..8e935533 --- /dev/null +++ b/utils/native/include/usb_common.h @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_COMMON_H +#define USB_COMMON_H + +#include +#include + +#include "hilog_wrapper.h" +#include "usb_errors.h" + +namespace OHOS { +namespace USB { +/** + * Invalid usb int value + */ +constexpr int32_t INVALID_USB_INT_VALUE = -1; + +/** + * Bitmask used for extracting the USBEndpoint type from it's address + */ +constexpr int32_t USB_ENDPOINT_XFERTYPE_MASK = 0x03; + +/** + * Control USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_CONTROL = 0; + +/** + * Isochronous USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_ISOC = 1; + +/** + * Bulk USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_BULK = 2; + +/** + * Interrupt USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_INT = 3; + +/** + * Bitmask used for extracting the USBEndpoint number from it's address + */ +constexpr int32_t USB_ENDPOINT_NUMBER_MASK = 0x0f; + +/** + * Bitmask used for extracting the USBEndpoint direction from it's address + */ +constexpr int32_t USB_ENDPOINT_DIR_MASK = 0x80; + +/** + * Used to signify direction of data for USBEndpoint is OUT, host to device + */ +constexpr int32_t USB_ENDPOINT_DIR_OUT = 0; + +/** + * Used to signify direction of data for USBEndpoint is IN, device to host + */ +constexpr int32_t USB_ENDPOINT_DIR_IN = 0x80; + +/** + * Bitmask for self power in the USBConfig + */ +constexpr int32_t USB_CFG_SELF_POWERED = 0x80; + +/** + * Bitmask for remote wakeup in the USBConfig + */ +constexpr int32_t USB_CFG_REMOTE_WAKEUP = 0x20; + +#define INVALID_STRING_VALUE ("") +#define RETURN_IF_WITH_RET(cond, retval) \ + if (cond) { \ + return (retval); \ + } +#define RETURN_IF(cond) \ + if (cond) { \ + return; \ + } +#define RETURN_IF_WITH_LOG(cond, loginfo) \ + do { \ + if (cond) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s " #loginfo " ", __func__); \ + return; \ + } \ + } while (0) + +#define READ_PARCEL_NO_RET(parcel, type, out) \ + do { \ + if (!(parcel).Read##type(out)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s read " #out " failed", __func__); \ + return; \ + } \ + } while (0) + +#define WRITE_PARCEL_NO_RET(parcel, type, data) \ + do { \ + if (!(parcel).Write##type(data)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s write " #data " failed", __func__); \ + return; \ + } \ + } while (0) + +#define READ_PARCEL_WITH_RET(parcel, type, out, retval) \ + do { \ + if (!(parcel).Read##type(out)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s read " #out " failed", __func__); \ + return (retval); \ + } \ + } while (0) + +#define WRITE_PARCEL_WITH_RET(parcel, type, data, retval) \ + do { \ + if (!(parcel).Write##type(data)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s write " #data " failed", __func__); \ + return (retval); \ + } \ + } while (0) + +template constexpr auto ToUnderlying(E e) noexcept +{ + return static_cast>(e); +} +} // namespace USB +} // namespace OHOS + +#endif // USB_COMMON_H diff --git a/utils/native/include/usb_errors.h b/utils/native/include/usb_errors.h new file mode 100644 index 00000000..84d4a7d6 --- /dev/null +++ b/utils/native/include/usb_errors.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 USB_ERRORS_H +#define USB_ERRORS_H + +#include + +namespace OHOS { +namespace USB { +enum { + /** + * Module type: Usb Manager Service + */ + USB_MODULE_TYPE_SERVICE = 0, + /** + * Module type: Usb Manager Kit + */ + USB_MODULE_TYPE_KIT = 1 +}; + +// offset of usbmgr error, only be used in this file. +constexpr ErrCode USBFWK_SERVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_USB, USB_MODULE_TYPE_SERVICE); + +enum { + E_WRITE_PARCEL_ERROR = USBFWK_SERVICE_ERR_OFFSET, + E_READ_PARCEL_ERROR, + E_GET_SYSTEM_ABILITY_MANAGER_FAILED, + E_GET_USB_SERVICE_FAILED, + E_ADD_DEATH_RECIPIENT_FAILED, + E_INNER_ERR +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_ERRORS_H -- Gitee From 1311719d55272c1335cd432f0ee612554886734d Mon Sep 17 00:00:00 2001 From: 18392181980 Date: Thu, 21 Oct 2021 15:57:05 +0800 Subject: [PATCH 2/2] usb_service_commit_1021 Signed-off-by: 18392181980 --- LICENSE | 177 ++ hdi/BUILD.gn | 21 + hdi/api/include/usbd_api.h | 240 ++ hdi/client/BUILD.gn | 49 + hdi/client/include/readme.md | 27 + hdi/client/include/usbd_client.h | 99 + hdi/client/include/usbd_subscriber.h | 41 + hdi/client/src/usbd_client.cpp | 615 +++++ hdi/client/src/usbd_subscriber.cpp | 110 + hdi/service/BUILD.gn | 84 + hdi/service/include/usbd.h | 99 + hdi/service/include/usbd_dispatcher.h | 22 + hdi/service/include/usbd_function.h | 23 + hdi/service/include/usbd_parser.h | 37 + hdi/service/include/usbd_port.h | 24 + hdi/service/include/usbd_publisher.h | 36 + hdi/service/src/usbd.c | 326 +++ hdi/service/src/usbd_dispatcher.c | 2087 +++++++++++++++++ hdi/service/src/usbd_function.c | 206 ++ hdi/service/src/usbd_port.c | 149 ++ hdi/service/src/usbd_publisher.c | 91 + hdi/test/BUILD.gn | 22 + hdi/test/unittest/common/BUILD.gn | 294 +++ .../common/include/usbd_config_test.h | 27 + .../common/include/usbd_descriptor_test.h | 27 + .../common/include/usbd_device_test.h | 27 + .../common/include/usbd_function_test.h | 27 + .../common/include/usbd_interface_test.h | 27 + .../unittest/common/include/usbd_port_test.h | 27 + .../common/include/usbd_request_test.h | 27 + .../common/include/usbd_transfer_test.h | 27 + .../unittest/common/src/usbd_config_test.cpp | 308 +++ .../common/src/usbd_descriptor_test.cpp | 680 ++++++ .../unittest/common/src/usbd_device_test.cpp | 230 ++ .../common/src/usbd_function_test.cpp | 227 ++ .../common/src/usbd_interface_test.cpp | 643 +++++ .../unittest/common/src/usbd_port_test.cpp | 188 ++ .../unittest/common/src/usbd_request_test.cpp | 1091 +++++++++ .../common/src/usbd_transfer_test.cpp | 824 +++++++ interfaces/innerkits/BUILD.gn | 55 + .../innerkits/native/include/iusb_srv.h | 125 + .../innerkits/native/include/usb_config.h | 150 ++ .../innerkits/native/include/usb_device.h | 289 +++ .../native/include/usb_device_pipe.h | 57 + .../innerkits/native/include/usb_endpoint.h | 130 + .../innerkits/native/include/usb_info.h | 87 + .../innerkits/native/include/usb_interface.h | 153 ++ .../innerkits/native/include/usb_port.h | 76 + .../native/include/usb_port_status.h | 53 + .../innerkits/native/include/usb_request.h | 102 + .../innerkits/native/include/usb_srv_client.h | 111 + .../innerkits/native/src/usb_device.cpp | 22 + .../innerkits/native/src/usb_device_pipe.cpp | 103 + .../innerkits/native/src/usb_request.cpp | 51 + .../innerkits/native/src/usb_srv_client.cpp | 401 ++++ interfaces/kits/java/BUILD.gn | 54 + .../ohos/usb/IUSBDevicePipeController.java | 42 + .../java/ohos/usb/IUSBRequestController.java | 28 + .../java/ohos/usb/IUsbCoreController.java | 43 + interfaces/kits/java/ohos/usb/USBConfig.java | 143 ++ interfaces/kits/java/ohos/usb/USBCore.java | 191 ++ interfaces/kits/java/ohos/usb/USBDevice.java | 290 +++ .../kits/java/ohos/usb/USBDevicePipe.java | 263 +++ .../ohos/usb/USBDevicePipeController.java | 142 ++ .../kits/java/ohos/usb/USBEndpoint.java | 151 ++ .../kits/java/ohos/usb/USBInterface.java | 172 ++ .../kits/java/ohos/usb/USBLoggerFactory.java | 46 + interfaces/kits/java/ohos/usb/USBPort.java | 4 + interfaces/kits/java/ohos/usb/USBRequest.java | 131 ++ .../kits/java/ohos/usb/UsbCoreController.java | 142 ++ .../java/ohos/usb/UsbCoreControllerProxy.java | 414 ++++ .../usb/UsbDevicePipeControllerProxy.java | 173 ++ .../kits/java/ohos/usb/UsbKitsUtils.java | 7 + .../kits/java/ohos/usb/UsbPortStatus.java | 4 + .../java/ohos/usb/UsbRequestController.java | 142 ++ .../ohos/usb/UsbRequestControllerProxy.java | 134 ++ .../kits/java/ohos/usb/package-info.java | 24 + interfaces/kits/js/@ohos.usb.d.ts | 789 +++++++ interfaces/kits/js/napi/BUILD.gn | 48 + interfaces/kits/js/napi/usb_async_context.h | 75 + interfaces/kits/js/napi/usb_info.cpp | 1459 ++++++++++++ interfaces/kits/js/test/CheckEmptyUtils.js | 68 + interfaces/kits/js/test/DateAndTimeUtil.js | 114 + interfaces/kits/js/test/EventConstants.js | 66 + interfaces/kits/js/test/ListUsb.test.js | 25 + interfaces/kits/js/test/UsbCoreJsunit.test.js | 254 ++ .../kits/js/test/UsbDevicePipeJsunit.test.js | 358 +++ .../kits/js/test/UsbFunctionsJsunit.test.js | 218 ++ interfaces/kits/js/test/UsbPortJsunit.test.js | 141 ++ interfaces/kits/js/test/usb_unit.test.js | 495 ++++ ohos.build | 32 + sa_profile/4201.xml | 24 + sa_profile/BUILD.gn | 19 + services/BUILD.gn | 69 + .../native/include/usb_descriptor_parser.h | 37 + .../native/include/usb_function_manager.h | 55 + services/native/include/usb_host_manager.h | 45 + services/native/include/usb_port_manager.h | 51 + services/native/include/usb_right_manager.h | 43 + services/native/include/usb_serial_reader.h | 41 + .../native/include/usb_server_event_handler.h | 40 + services/native/include/usb_service.h | 148 ++ .../native/include/usb_service_subscriber.h | 36 + services/native/src/usb_descriptor_parser.cpp | 247 ++ services/native/src/usb_function_manager.cpp | 114 + services/native/src/usb_host_manager.cpp | 75 + services/native/src/usb_port_manager.cpp | 134 ++ services/native/src/usb_right_manager.cpp | 83 + services/native/src/usb_serial_reader.cpp | 32 + .../native/src/usb_server_event_handler.cpp | 35 + services/native/src/usb_service.cpp | 556 +++++ .../native/src/usb_service_subscriber.cpp | 119 + services/native/test/BUILD.gn | 22 + services/native/test/unittest/common/BUILD.gn | 166 ++ .../unittest/common/include/usb_core_test.h | 28 + .../common/include/usb_device_pipe_test.h | 29 + .../common/include/usb_request_test.h | 28 + .../unittest/common/src/usb_core_test.cpp | 381 +++ .../common/src/usb_device_pipe_test.cpp | 1778 ++++++++++++++ .../common/src/usb_port_service_test.cpp | 200 ++ .../unittest/common/src/usb_request_test.cpp | 712 ++++++ services/zidl/include/usb_server_proxy.h | 110 + services/zidl/include/usb_server_stub.h | 85 + services/zidl/iusb_server.zidl | 19 + services/zidl/src/usb_srv_proxy.cpp | 887 +++++++ services/zidl/src/usb_srv_stub.cpp | 663 ++++++ test/native/BUILD.gn | 20 + test/native/unittest/BUILD.gn | 72 + .../unittest/include/usb_service_test.h | 26 + test/native/unittest/src/usb_service_test.cpp | 224 ++ usbmgr.gni | 18 + utils/BUILD.gn | 21 + utils/native/include/delayed_sp_singleton.h | 62 + utils/native/include/hilog_wrapper.h | 108 + utils/native/include/usb_common.h | 143 ++ utils/native/include/usb_errors.h | 48 + 136 files changed, 25986 insertions(+) create mode 100644 LICENSE create mode 100644 hdi/BUILD.gn create mode 100644 hdi/api/include/usbd_api.h create mode 100644 hdi/client/BUILD.gn create mode 100644 hdi/client/include/readme.md create mode 100644 hdi/client/include/usbd_client.h create mode 100644 hdi/client/include/usbd_subscriber.h create mode 100644 hdi/client/src/usbd_client.cpp create mode 100644 hdi/client/src/usbd_subscriber.cpp create mode 100644 hdi/service/BUILD.gn create mode 100644 hdi/service/include/usbd.h create mode 100644 hdi/service/include/usbd_dispatcher.h create mode 100644 hdi/service/include/usbd_function.h create mode 100644 hdi/service/include/usbd_parser.h create mode 100644 hdi/service/include/usbd_port.h create mode 100644 hdi/service/include/usbd_publisher.h create mode 100644 hdi/service/src/usbd.c create mode 100644 hdi/service/src/usbd_dispatcher.c create mode 100644 hdi/service/src/usbd_function.c create mode 100644 hdi/service/src/usbd_port.c create mode 100644 hdi/service/src/usbd_publisher.c create mode 100644 hdi/test/BUILD.gn create mode 100644 hdi/test/unittest/common/BUILD.gn create mode 100644 hdi/test/unittest/common/include/usbd_config_test.h create mode 100644 hdi/test/unittest/common/include/usbd_descriptor_test.h create mode 100644 hdi/test/unittest/common/include/usbd_device_test.h create mode 100644 hdi/test/unittest/common/include/usbd_function_test.h create mode 100644 hdi/test/unittest/common/include/usbd_interface_test.h create mode 100644 hdi/test/unittest/common/include/usbd_port_test.h create mode 100644 hdi/test/unittest/common/include/usbd_request_test.h create mode 100644 hdi/test/unittest/common/include/usbd_transfer_test.h create mode 100644 hdi/test/unittest/common/src/usbd_config_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_descriptor_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_device_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_function_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_interface_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_port_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_request_test.cpp create mode 100644 hdi/test/unittest/common/src/usbd_transfer_test.cpp create mode 100644 interfaces/innerkits/BUILD.gn create mode 100644 interfaces/innerkits/native/include/iusb_srv.h create mode 100644 interfaces/innerkits/native/include/usb_config.h create mode 100644 interfaces/innerkits/native/include/usb_device.h create mode 100644 interfaces/innerkits/native/include/usb_device_pipe.h create mode 100644 interfaces/innerkits/native/include/usb_endpoint.h create mode 100644 interfaces/innerkits/native/include/usb_info.h create mode 100644 interfaces/innerkits/native/include/usb_interface.h create mode 100644 interfaces/innerkits/native/include/usb_port.h create mode 100644 interfaces/innerkits/native/include/usb_port_status.h create mode 100644 interfaces/innerkits/native/include/usb_request.h create mode 100644 interfaces/innerkits/native/include/usb_srv_client.h create mode 100644 interfaces/innerkits/native/src/usb_device.cpp create mode 100644 interfaces/innerkits/native/src/usb_device_pipe.cpp create mode 100644 interfaces/innerkits/native/src/usb_request.cpp create mode 100644 interfaces/innerkits/native/src/usb_srv_client.cpp create mode 100644 interfaces/kits/java/BUILD.gn create mode 100644 interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java create mode 100644 interfaces/kits/java/ohos/usb/IUSBRequestController.java create mode 100644 interfaces/kits/java/ohos/usb/IUsbCoreController.java create mode 100644 interfaces/kits/java/ohos/usb/USBConfig.java create mode 100644 interfaces/kits/java/ohos/usb/USBCore.java create mode 100644 interfaces/kits/java/ohos/usb/USBDevice.java create mode 100644 interfaces/kits/java/ohos/usb/USBDevicePipe.java create mode 100644 interfaces/kits/java/ohos/usb/USBDevicePipeController.java create mode 100644 interfaces/kits/java/ohos/usb/USBEndpoint.java create mode 100644 interfaces/kits/java/ohos/usb/USBInterface.java create mode 100644 interfaces/kits/java/ohos/usb/USBLoggerFactory.java create mode 100644 interfaces/kits/java/ohos/usb/USBPort.java create mode 100644 interfaces/kits/java/ohos/usb/USBRequest.java create mode 100644 interfaces/kits/java/ohos/usb/UsbCoreController.java create mode 100644 interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java create mode 100644 interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java create mode 100644 interfaces/kits/java/ohos/usb/UsbKitsUtils.java create mode 100644 interfaces/kits/java/ohos/usb/UsbPortStatus.java create mode 100644 interfaces/kits/java/ohos/usb/UsbRequestController.java create mode 100644 interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java create mode 100644 interfaces/kits/java/ohos/usb/package-info.java create mode 100644 interfaces/kits/js/@ohos.usb.d.ts create mode 100644 interfaces/kits/js/napi/BUILD.gn create mode 100644 interfaces/kits/js/napi/usb_async_context.h create mode 100644 interfaces/kits/js/napi/usb_info.cpp create mode 100644 interfaces/kits/js/test/CheckEmptyUtils.js create mode 100644 interfaces/kits/js/test/DateAndTimeUtil.js create mode 100644 interfaces/kits/js/test/EventConstants.js create mode 100644 interfaces/kits/js/test/ListUsb.test.js create mode 100644 interfaces/kits/js/test/UsbCoreJsunit.test.js create mode 100644 interfaces/kits/js/test/UsbDevicePipeJsunit.test.js create mode 100644 interfaces/kits/js/test/UsbFunctionsJsunit.test.js create mode 100644 interfaces/kits/js/test/UsbPortJsunit.test.js create mode 100644 interfaces/kits/js/test/usb_unit.test.js create mode 100644 ohos.build create mode 100644 sa_profile/4201.xml create mode 100644 sa_profile/BUILD.gn create mode 100644 services/BUILD.gn create mode 100644 services/native/include/usb_descriptor_parser.h create mode 100644 services/native/include/usb_function_manager.h create mode 100644 services/native/include/usb_host_manager.h create mode 100644 services/native/include/usb_port_manager.h create mode 100644 services/native/include/usb_right_manager.h create mode 100644 services/native/include/usb_serial_reader.h create mode 100644 services/native/include/usb_server_event_handler.h create mode 100644 services/native/include/usb_service.h create mode 100644 services/native/include/usb_service_subscriber.h create mode 100644 services/native/src/usb_descriptor_parser.cpp create mode 100644 services/native/src/usb_function_manager.cpp create mode 100644 services/native/src/usb_host_manager.cpp create mode 100644 services/native/src/usb_port_manager.cpp create mode 100644 services/native/src/usb_right_manager.cpp create mode 100644 services/native/src/usb_serial_reader.cpp create mode 100644 services/native/src/usb_server_event_handler.cpp create mode 100644 services/native/src/usb_service.cpp create mode 100644 services/native/src/usb_service_subscriber.cpp create mode 100644 services/native/test/BUILD.gn create mode 100644 services/native/test/unittest/common/BUILD.gn create mode 100644 services/native/test/unittest/common/include/usb_core_test.h create mode 100644 services/native/test/unittest/common/include/usb_device_pipe_test.h create mode 100644 services/native/test/unittest/common/include/usb_request_test.h create mode 100644 services/native/test/unittest/common/src/usb_core_test.cpp create mode 100644 services/native/test/unittest/common/src/usb_device_pipe_test.cpp create mode 100644 services/native/test/unittest/common/src/usb_port_service_test.cpp create mode 100644 services/native/test/unittest/common/src/usb_request_test.cpp create mode 100644 services/zidl/include/usb_server_proxy.h create mode 100644 services/zidl/include/usb_server_stub.h create mode 100644 services/zidl/iusb_server.zidl create mode 100644 services/zidl/src/usb_srv_proxy.cpp create mode 100644 services/zidl/src/usb_srv_stub.cpp create mode 100644 test/native/BUILD.gn create mode 100644 test/native/unittest/BUILD.gn create mode 100644 test/native/unittest/include/usb_service_test.h create mode 100644 test/native/unittest/src/usb_service_test.cpp create mode 100644 usbmgr.gni create mode 100644 utils/BUILD.gn create mode 100644 utils/native/include/delayed_sp_singleton.h create mode 100644 utils/native/include/hilog_wrapper.h create mode 100644 utils/native/include/usb_common.h create mode 100644 utils/native/include/usb_errors.h diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..4947287f --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/hdi/BUILD.gn b/hdi/BUILD.gn new file mode 100644 index 00000000..e2b675c4 --- /dev/null +++ b/hdi/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos.gni") + +group("hdi_group") { + deps = [ + "client:usbd_client", + "service:usbd" + ] +} diff --git a/hdi/api/include/usbd_api.h b/hdi/api/include/usbd_api.h new file mode 100644 index 00000000..541b5bca --- /dev/null +++ b/hdi/api/include/usbd_api.h @@ -0,0 +1,240 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_API_H +#define USBD_API_H + +#include +#include + +#define USB_MAX_INTERFACES 32 +typedef void (*UsbdRequestCallback)(void *requestArg); + +enum UsbdDeviceAction { + ACT_DEVUP = 0, + ACT_DEVDOWN, + ACT_UPDEVICE, + ACT_DOWNDEVICE, +}; + +enum UsbdCmd { + CMD_BIND_USB_SUBSCRIBER = 0, + CMD_UNBIND_USB_SUBSCRIBER, + CMD_NOTIFY_DEVICE_DOWN, + CMD_NOTIFY_DEVICE_FOUND, + CMD_NOTIFY_PORT_CHANGED, + CMD_CLASS_CTRL_SYNC, + CMD_FUN_ADD_FUNCTION, + CMD_FUN_ADD_INTERFACE, + CMD_FUN_CLAIM_INTERFACE, + CMD_FUN_CLOSE_DEVICE, + CMD_FUN_CONNECT_DEVICE, + CMD_FUN_DELETE_INTERFACE, + CMD_FUN_GET_CONFIG, + CMD_FUN_GET_CURRENT_FUNCTIONS, + CMD_FUN_GET_DESCRIPTOR, + CMD_FUN_GET_DEVICE_DESCRIPTOR, + CMD_FUN_GET_CONFIG_DESCRIPTOR, + CMD_FUN_GET_STRING_DESCRIPTOR, + CMD_FUN_GET_INTERFACE_DESCRIPTOR, + CMD_FUN_GET_ENDPOINT_DESCRIPTOR, + CMD_FUN_HANDLE_REQUEST, + CMD_FUN_OPEN_DEVICE, + CMD_FUN_RELEASE_INTERFACE, + CMD_FUN_REMOVE_FUNCTION, + CMD_FUN_REMOVE_INTERFACE, + CMD_FUN_SEND_BULK_READ_ASYNC, + CMD_FUN_SEND_BULK_READ_SYNC, + CMD_FUN_SEND_BULK_WRITE_ASYNC, + CMD_FUN_SEND_BULK_WRITE_SYNC, + CMD_FUN_SEND_CTRL_READ_ASYNC, + CMD_FUN_SEND_CTRL_READ_SYNC, + CMD_FUN_SEND_CTRL_REQUEST_ASYNC, + CMD_FUN_SEND_CTRL_REQUEST_SYNC, + CMD_FUN_SEND_CTRL_WRITE_ASYNC, + CMD_FUN_SEND_CTRL_WRITE_SYNC, + CMD_FUN_SEND_INTERRUPT_READ_ASYNC, + CMD_FUN_SEND_INTERRUPT_READ_SYNC, + CMD_FUN_SEND_INTERRUPT_WRITE_ASYNC, + CMD_FUN_SEND_INTERRUPT_WRITE_SYNC, + CMD_FUN_SEND_ISO_READ_ASYNC, + CMD_FUN_SEND_ISO_READ_SYNC, + CMD_FUN_SEND_ISO_WRITE_ASYNC, + CMD_FUN_SEND_ISO_WRITE_SYNC, + CMD_FUN_SET_CONFIG, + CMD_FUN_SET_CURRENT_FUNCTIONS, + CMD_FUN_SET_INTERFACE, + CMD_ADD_INTERFACE, + CMD_REMOVE_INTERFACE, + CMD_GET_CHARGE_STATE, + CMD_GET_DEVICES, + CMD_HAS_RIGHT, + CMD_READ_DATA_SYNC, + CMD_READ_PARM, + CMD_SET_BAUDRATE, + CMD_SET_ROLE, + CMD_QUERY_PORT, + CMD_STD_CTRL_GET_CONFIGURATION, + CMD_STD_CTRL_GET_DESCRIPTOR_ASYNC, + CMD_STD_CTRL_GET_DESCRIPTOR_CMD, + CMD_STD_CTRL_GET_INTERFACE, + CMD_STD_CTRL_GET_STATUS_CMD, + CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT, + CMD_FUN_REQUEST_QUEUE, + CMD_FUN_REQUEST_WAIT, + CMD_FUN_REQUEST_CANCEL +}; + +struct UsbdDevice { + uint8_t busNum; + uint8_t devAddr; + uint8_t interface; + uint8_t endPoint; +}; +struct UsbdPeripheral { + uint8_t busNum; + uint8_t devAddr; + uint8_t iSerialNumber; +}; +struct UsbdPort { + uint8_t modes; + uint8_t roles; +}; +struct UsbdRequestDataSync { + uint8_t endPoint; + int32_t *requested; + uint8_t *data; + int32_t length; + uint32_t timeout; +}; +struct UsbdRequestDataAsync { + unsigned char endPoint; + unsigned char *buffer; + int length; + int numIsoPackets; + UsbdRequestCallback callback; + void *userData; + unsigned int timeout; +}; +struct UsbdControlRequestSetupData { + uint8_t requestType; + uint8_t requestCmd; + uint16_t value; + uint16_t index; + uint8_t *data; + uint16_t length; + uint32_t timeout; +}; +struct UsbdDescriptorParam { + uint8_t descType; + uint8_t descIndex; + int length; +}; +struct UsbdDescriptorHeader { + uint8_t bLength; + uint8_t bDescriptorType; +} __attribute__((packed)); + +struct UsbdDeviceDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize0; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; +} __attribute__((packed)); + +struct UsbdConfigDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t bMaxPower; +} __attribute__((packed)); + +struct UsbdInterfaceDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; + uint8_t bInterfaceSubClass; + uint8_t bInterfaceProtocol; + uint8_t iInterface; +} __attribute__((packed)); + +struct UsbdEndpointDescriptor { + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint16_t wMaxPacketSize; + uint8_t bInterval; +} __attribute__((packed)); + +struct UsbNotifyServiceInfo { + uint32_t length; + + int32_t devNum; + int32_t busNum; + + int32_t interfaceLength; + uint8_t interfaceNumber[USB_MAX_INTERFACES]; +} __attribute__((packed)); + +enum PortRoleType { DATA_ROLE, POWER_ROLE, MODE }; + +enum PortPowerRole { SOURCE, SINK }; + +enum PortMode { HOST, DEVICE, OTG }; + +struct PortInfo { + int32_t portId; + int32_t powerRole; + int32_t dataRole; + int32_t mode; +}; + +// Keep it same as the inner kit usb_info.h +struct UsbdInfo { + int32_t capacity_; + int32_t voltage_; + int32_t temperature_; + int32_t healthState_; + int32_t pluggedType_; + int32_t pluggedMaxCurrent_; + int32_t pluggedMaxVoltage_; + int32_t chargeState_; + int32_t chargeCounter_; + int8_t present_; + const char *technology_; +}; + +struct UsbdRequest { +}; + +#endif // USBD_API_H diff --git a/hdi/client/BUILD.gn b/hdi/client/BUILD.gn new file mode 100644 index 00000000..382e5657 --- /dev/null +++ b/hdi/client/BUILD.gn @@ -0,0 +1,49 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") + +config("usbd_client_public_config") { + include_dirs = [ + "include", + "${usb_manager_path}/hdi/api/include", + "${usb_manager_path}/interfaces/innerkits/native/include", + ] +} + +ohos_shared_library("usbd_client") { + sources = [ + "src/usbd_client.cpp", + "src/usbd_subscriber.cpp", + ] + + configs = [ "${utils_path}:utils_config" ] + + public_configs = [ ":usbd_client_public_config" ] + + deps = [ + "${hdf_uhdf_path}/hdi:libhdi", + "${hdf_uhdf_path}/host:libhdf_host", + "${hdf_uhdf_path}/osal:libhdf_utils", + "//utils/native/base:utils", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + part_name = "usb_manager_native" +} diff --git a/hdi/client/include/readme.md b/hdi/client/include/readme.md new file mode 100644 index 00000000..1d811a1e --- /dev/null +++ b/hdi/client/include/readme.md @@ -0,0 +1,27 @@ +**USB HDI API 接口** + +| C++接口申明 | C++接口描述 | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| int32_t OpenDevice(uint8_t busNum, uint8_t devAddr); | 打开设备,建立连接 | +| int32_t CloseDevice(uint8_t busNum, uint8_t devAddr); | 关闭设备,释放与设备相关的所有系统资源 | +| int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length); | 获取设备描述符 | +| int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); | 获取设备的配置描述符 | +| int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); | 获取设备的字符串描述符 | +| int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex); | 设置设备当前使用的配置,通过配置值进行指定 | +| int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex); | 获取当前生效的配置值 | +| int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface); | 打开接口,并申明独占接口,必须在数据传输前执行 | +| int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface); | 关闭接口,释放接口的占用,在停止数据传输后执行 | +| int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface, uint8_t altIndex); | 设置指定接口的备选设置,用于在具有相同ID但不同备用设置的两个接口之间进行选择 | +| int32_t BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行批量数据读取, 返回读取的数据和长度,端点方向必须为数据读取 | +| int32_t BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行批量数据写入, 返回读取的数据和长度,端点方向必须为数据写入 | +| int32_t ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams ¶ms); | 对此设备执行端点零的控制事务,传输方向由请求类型决定。 如果requestType& USB_ENDPOINT_DIR_MASK是USB_DIR_OUT ,则传输是写入,如果是USB_DIR_IN ,则传输是读取。 | +| int32_t InterruptTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行中断数据读取, 返回读取的数据和长度,端点方向必须为数据读取 | +| int32_t InterruptTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行中断数据写入, 返回读取的数据和长度,端点方向必须为数据写入 | +| int32_t IsoTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行等时数据读取, 返回读取的数据和长度,端点方向必须为数据读取 | +| int32_t IsoTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); | 在给定端点上执行等时数据写入, 返回读取的数据和长度,端点方向必须为数据写入 | +| int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct RequestParams ¶ms); | 将指定的端点进行异步数据发送或者接收请求,数据传输方向由端点方向决定 | +| int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); | 等待RequestQueue异步请求的操作结果 | +| int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interface, uint8_t endpoint); | 取消待处理的数据请求 | +| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | 设置端口工作模式(从设备) | +| int32_t GetCurrentFunctions(uint8_t busNum, uint8_t devAddr, int32_t *funcs) | 获取从设备支持的功能列表(按位域表示)(从设备) | +| int32_t SetCurrentFunctions(uint8_t busNum, uint8_t devAddr, int32_t funcs) | 设置从设备支持的功能列表(按位域表示)(从设备) | \ No newline at end of file diff --git a/hdi/client/include/usbd_client.h b/hdi/client/include/usbd_client.h new file mode 100644 index 00000000..d4a2320c --- /dev/null +++ b/hdi/client/include/usbd_client.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_CLIENT_H +#define USBD_CLIENT_H + +#include "usbd_subscriber.h" + +namespace OHOS { +namespace USB { +struct DescriptorParams { + uint8_t DescId; + uint8_t *buffer; + uint32_t &length; +}; + +struct TransferParams { + uint8_t interfaceid; + uint8_t endpointid; + uint8_t *buffer; + uint32_t &length; + int32_t timeout; +}; + +struct CtrlTransferParamsParams { + int32_t requestType; + int32_t request; + int32_t value; + int32_t index; + uint8_t *buffer; + uint32_t &length; + int32_t timeout; +}; + +struct RequestParams { + void *clientData; + uint32_t &clientLength; + uint8_t *buffer; + uint32_t &length; +}; + +class UsbdClient { +public: + /* usb主设备接口 */ + static int32_t OpenDevice(uint8_t busNum, uint8_t devAddr); + static int32_t CloseDevice(uint8_t busNum, uint8_t devAddr); + static int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length); + static int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length); + static int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex); + static int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex); + static int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid); + static int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid); + static int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex); + static int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + static int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + static int32_t BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams ¶ms); + static int32_t InterruptTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t InterruptTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t IsoTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t IsoTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + static int32_t + RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct RequestParams ¶ms); + static int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + static int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid); + + /* usb从设备接口 */ + static int32_t GetCurrentFunctions(int32_t &funcs); + static int32_t SetCurrentFunctions(int32_t funcs); + static int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); + static int32_t QueryPort(int32_t &portId, int32_t &powerRole, int32_t &dataRole, int32_t &mode); + + static ErrCode BindUsbdSubscriber(const sptr &subscriber); + static ErrCode UnbindUsbdSubscriber(); + +private: + static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); + static int32_t SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr); + static int32_t SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length); + static int32_t GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length); + static sptr GetUsbdService(); + static ErrCode DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply); +}; +} // namespace USB +} // namespace OHOS +#endif // USBD_CLIENT_H diff --git a/hdi/client/include/usbd_subscriber.h b/hdi/client/include/usbd_subscriber.h new file mode 100644 index 00000000..eab1e2b9 --- /dev/null +++ b/hdi/client/include/usbd_subscriber.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 USBD_SUBSCRIBER_H +#define USBD_SUBSCRIBER_H + +#include "ipc_object_stub.h" +#include "usb_info.h" +#include "usbd_api.h" + +namespace OHOS { +namespace USB { +class UsbdSubscriber : public IPCObjectStub { +public: + explicit UsbdSubscriber() : IPCObjectStub(u"ohos.usb.IUsbManagerSubscriber"){}; + virtual ~UsbdSubscriber() = default; + virtual int32_t DeviceEvent(const UsbInfo &info) = 0; + virtual int32_t PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) = 0; + virtual int32_t Update(const UsbInfo &info) = 0; + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + static FoundDevice &ParserFoundDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option); + static int32_t ParserUsbInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, UsbInfo &info); + static int32_t ParserPortInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, PortInfo &info); +}; +} // namespace USB +} // namespace OHOS +#endif // USBD_SUBSCRIBER_H diff --git a/hdi/client/src/usbd_client.cpp b/hdi/client/src/usbd_client.cpp new file mode 100644 index 00000000..94d08c1d --- /dev/null +++ b/hdi/client/src/usbd_client.cpp @@ -0,0 +1,615 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_client.h" +#include +#include "hilog_wrapper.h" +#include "iservmgr_hdi.h" +#include "message_parcel.h" +#include "securec.h" +#include "usb_common.h" +#include "usbd_api.h" + +namespace OHOS { +namespace USB { +using OHOS::HDI::ServiceManager::V1_0::IServiceManager; + +namespace { +const std::string USBD_SERVICE = "usbd"; +} + +void UsbdClient::PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << 二进制数据流[" << length << "字节] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_SERVICE, "%{public}s", oss.str().c_str()); +} + +sptr UsbdClient::GetUsbdService() +{ + auto serviceManager = IServiceManager::Get(); + if (serviceManager == nullptr) { + USB_HILOGW(MODULE_USBD, "service manager is nullptr"); + return nullptr; + } + auto UsbdService = serviceManager->GetService(USBD_SERVICE.c_str()); + if (UsbdService == nullptr) { + USB_HILOGW(MODULE_USBD, "Usbd service is nullptr"); + return nullptr; + } + return UsbdService; +} + +ErrCode UsbdClient::BindUsbdSubscriber(const sptr &subscriber) +{ + USB_HILOGD(MODULE_USBD, "BindUsbdSubscriber enter"); + if (subscriber == nullptr) { + USB_HILOGW(MODULE_USBD, "subscriber is nullptr"); + return ERR_INVALID_VALUE; + } + + MessageParcel data; + MessageParcel reply; + data.WriteRemoteObject(subscriber); + return DoDispatch(CMD_BIND_USB_SUBSCRIBER, data, reply); +} + +ErrCode UsbdClient::UnbindUsbdSubscriber() +{ + USB_HILOGD(MODULE_USBD, "UnbindUsbdSubscriber enter"); + MessageParcel data; + MessageParcel reply; + return DoDispatch(CMD_UNBIND_USB_SUBSCRIBER, data, reply); +} + +int32_t UsbdClient::OpenDevice(uint8_t busNum, uint8_t devAddr) +{ + MessageParcel data; + MessageParcel reply; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d OpenDevice bus:%{public}d dev:%{public}d", __func__, __LINE__, + busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + ErrCode ret = DoDispatch(CMD_FUN_OPEN_DEVICE, data, reply); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d OpenDevice ret:%{public}d bus:%{public}d dev:%{public}d", __func__, + __LINE__, ret, busNum, devAddr); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d CMD_FUN_OPEN_DEVICE failed, return %{public}d", __func__, + __LINE__, ret); + return ERR_INVALID_VALUE; + } + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d OpenDevice bus:%{public}d dev:%{public}d ", __func__, __LINE__, + busNum, devAddr); + return ERR_OK; +} + +int32_t UsbdClient::GetCurrentFunctions(int32_t &funcs) +{ + USB_HILOGD(MODULE_USBD, "GetCurrentFunctions enter"); + MessageParcel data; + MessageParcel reply; + ErrCode ret = DoDispatch(CMD_FUN_GET_CURRENT_FUNCTIONS, data, reply); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_FUN_GET_CURRENT_FUNCTIONS failed, return INVALID_USB_INT_VALUE"); + return ret; + } + READ_PARCEL_WITH_RET(reply, Int32, funcs, E_READ_PARCEL_ERROR); + USB_HILOGD(MODULE_USBD, "GetCurrentFunctions funcs %{public}d", funcs); + return ERR_OK; +} + +int32_t UsbdClient::SetCurrentFunctions(int32_t funcs) +{ + USB_HILOGD(MODULE_USBD, "SetCurrentFunctions enter"); + MessageParcel data; + MessageParcel reply; + WRITE_PARCEL_WITH_RET(data, Int32, funcs, E_WRITE_PARCEL_ERROR); + USB_HILOGD(MODULE_USBD, "SetCurrentFunctions funcs %{public}d", funcs); + ErrCode ret = DoDispatch(CMD_FUN_SET_CURRENT_FUNCTIONS, data, reply); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_FUN_SET_CURRENT_FUNCTIONS failed"); + return ret; + } + return ERR_OK; +} + +int32_t UsbdClient::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + USB_HILOGD(MODULE_USBD, "UsbdClient::SetPortRole enter"); + MessageParcel data; + MessageParcel reply; + + WRITE_PARCEL_WITH_RET(data, Int32, portId, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, powerRole, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, dataRole, E_WRITE_PARCEL_ERROR); + + ErrCode ret = DoDispatch(CMD_SET_ROLE, data, reply); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_SET_ROLE failed, return INVALID_STRING_VALUE"); + return ret; + } + return ERR_OK; +} + +int32_t UsbdClient::QueryPort(int32_t &portId, int32_t &powerRole, int32_t &dataRole, int32_t &mode) +{ + USB_HILOGD(MODULE_USBD, "UsbdClient::queryPort enter"); + MessageParcel data; + MessageParcel reply; + ErrCode ret = DoDispatch(CMD_QUERY_PORT, data, reply); + READ_PARCEL_WITH_RET(reply, Int32, portId, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(reply, Int32, powerRole, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(reply, Int32, dataRole, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(reply, Int32, mode, E_READ_PARCEL_ERROR); + if (FAILED(ret)) { + USB_HILOGW(MODULE_USBD, "CMD_QUERY_PORT failed, return INVALID_STRING_VALUE"); + return ret; + } + USB_HILOGE(MODULE_USBD, "portId:%{public}d powerRole:%{public}d dataRole:%{public}d mode:%{public}d ", portId, + powerRole, dataRole, mode); + return ERR_OK; +} + +ErrCode UsbdClient::DoDispatch(uint32_t cmd, MessageParcel &data, MessageParcel &reply) +{ + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d cmd:%{public}d", __func__, __LINE__, cmd); + auto Usbd = GetUsbdService(); + if (Usbd == nullptr) { + USB_HILOGE(MODULE_USBD, "fumang get usbd service failed."); + return ERR_NO_INIT; + } + MessageOption option; + auto ret = Usbd->SendRequest(cmd, data, reply, option); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d SendRequest end cmd:%{public}d ", __func__, __LINE__, cmd); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USBD, "failed to send request, cmd: %{public}d, ret: %{public}d", cmd, ret); + return ret; + } + USB_HILOGD(MODULE_USBD, "fumang success to dispatch cmd: %{public}d", cmd); + return ERR_OK; +} + +int32_t UsbdClient::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) +{ + int32_t ret = ERR_OK; + if (desc == NULL || length == 0) { + return ERR_INVALID_VALUE; + } + MessageParcel data; + MessageParcel reply; + if ((!desc) || (length < 1)) { + return ERR_INVALID_VALUE; + } + UsbdClient::SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_CONFIG_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + uint32_t descLength = 0; + reply.ReadUint32(descLength); + if (descLength > length) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ERR_OVERFLOW; + } + const uint8_t *readData = reply.ReadBuffer(descLength); + memcpy_s(desc, length, readData, descLength); + return ret; +} + +int32_t UsbdClient::GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + if ((!buffer) || (length < 1)) { + return ERR_INVALID_VALUE; + } + UsbdClient::SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_DEVICE_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + GetBufferMessage(reply, buffer, length); + struct UsbdDeviceDescriptor *devDesc = (struct UsbdDeviceDescriptor *)buffer; + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang bLength=%{public}d, \ + bDescriptorType=%{public}d, \ + bcdUSB=%{public}d, \ + bDeviceClass=%{public}d, \ + bDeviceSubClass=%{public}d, \ + bDeviceProtocol=%{public}d, \ + bMaxPacketSize0=%{public}d, \ + idVendor=%{public}d, \ + idProduct=%{public}d, \ + bcdDevice=%{public}d, \ + iManufacturer=%{public}d, \ + iProduct=%{public}d, \ + iSerialNumber=%{public}d, \ + bNumConfigurations=%{public}d len:%{public}d", + __func__, devDesc->bLength, devDesc->bDescriptorType, devDesc->bcdUSB, devDesc->bDeviceClass, + devDesc->bDeviceSubClass, devDesc->bDeviceProtocol, devDesc->bMaxPacketSize0, devDesc->idVendor, + devDesc->idProduct, devDesc->bcdDevice, devDesc->iManufacturer, devDesc->iProduct, + devDesc->iSerialNumber, devDesc->bNumConfigurations, length); + + return ret; +} + +int32_t UsbdClient::GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d cfgId:%{public}d length:%{public}d ", __func__, __LINE__, + params.DescId, params.length); + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.DescId, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_STRING_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + GetBufferMessage(reply, params.buffer, params.length); + PrintBuffer("UsbdClient::GetStringDescriptor", params.buffer, params.length); + return ret; +} + +int32_t UsbdClient::GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d cfgId:%{public}d length:%{public}d ", __func__, __LINE__, + params.DescId, params.length); + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.DescId, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_CONFIG_DESCRIPTOR, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + GetBufferMessage(reply, params.buffer, params.length); + PrintBuffer("UsbdClient::GetConfigDescriptor", params.buffer, params.length); + return ret; +} + +int32_t UsbdClient::SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, configIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SET_CONFIG, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_GET_CONFIG, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + READ_PARCEL_WITH_RET(data, Uint8, configIndex, E_READ_PARCEL_ERROR); + return ret; +} + +int32_t UsbdClient::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_CLAIM_INTERFACE, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_RELEASE_INTERFACE, data, reply); + if (ERR_OK != ret) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceIndex, uint8_t altIndex) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceIndex, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, altIndex, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SET_INTERFACE, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + return ERR_OK; +} + +int32_t UsbdClient::BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_BULK_READ_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + return GetBufferMessage(reply, params.buffer, params.length); +} + +int32_t UsbdClient::BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.buffer, params.length); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_BULK_WRITE_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, params.requestType, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.request, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.value, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.index, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + bool bWrite = (params.requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT; + if (bWrite) { + SetBufferMessage(data, params.buffer, params.length); + } + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_CTRL_REQUEST_SYNC, data, reply); + if (ret != ERR_OK) { + return ret; + } + if (!bWrite) { + GetBufferMessage(reply, params.buffer, params.length); + PrintBuffer("UsbdClient::ControlTransfer", (const uint8_t *)params.buffer, params.length); + } + return ret; +} + +int32_t UsbdClient::InterruptTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_INTERRUPT_READ_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + return GetBufferMessage(reply, params.buffer, params.length); +} + +int32_t UsbdClient::InterruptTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.buffer, params.length); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_INTERRUPT_WRITE_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::IsoTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_ISO_READ_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + return ret; + } + + return GetBufferMessage(reply, params.buffer, params.length); +} + +int32_t UsbdClient::IsoTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, params.interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, params.endpointid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, params.timeout, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.buffer, params.length); + ret = UsbdClient::DoDispatch(CMD_FUN_SEND_ISO_WRITE_SYNC, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::CloseDevice(uint8_t busNum, uint8_t devAddr) +{ + int32_t ret = ERR_OK; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + ret = UsbdClient::DoDispatch(CMD_FUN_CLOSE_DEVICE, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s failed", __func__); + } + return ret; +} + +int32_t UsbdClient::RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpoint, + struct RequestParams ¶ms) +{ + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, ifId, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, params.clientData, params.clientLength); + SetBufferMessage(data, params.buffer, params.length); + return UsbdClient::DoDispatch(CMD_FUN_REQUEST_QUEUE, data, reply); +} + +int32_t UsbdClient::RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms) +{ + int32_t ret; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_REQUEST_WAIT, data, reply); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d failed ret:%{public}d", __func__, __LINE__, ret); + return ret; + } + GetBufferMessage(reply, params.clientData, params.clientLength); + GetBufferMessage(reply, params.buffer, params.length); + return ERR_OK; +} + +int32_t UsbdClient::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) +{ + int32_t ret; + MessageParcel data; + MessageParcel reply; + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpointid, E_WRITE_PARCEL_ERROR); + ret = UsbdClient::DoDispatch(CMD_FUN_REQUEST_CANCEL, data, reply); + if (ret != ERR_OK) { + return ret; + } + + return ERR_OK; +} + +int32_t UsbdClient::SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length) +{ + if (!data.WriteUint32(length)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && !data.WriteBuffer(buffer, length)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbdClient::GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length) +{ + uint32_t dataSize; + if (!data.ReadUint32(dataSize)) { + return ERR_INVALID_VALUE; + } + if (dataSize == 0) { + length = 0; + return ERR_OK; + } + if (!buffer) { + length = 0; + return ERR_INVALID_VALUE; + } + if (length < dataSize) { + USB_HILOGW(MODULE_USBD, "%{public}s failed buffer overflow", __func__); + return ERR_NO_MEMORY; + } + const uint8_t *readData = data.ReadBuffer(dataSize); // +1 避免0大小的空buffer + if (readData == nullptr) { + return ERR_INVALID_VALUE; + } + memcpy_s(buffer, length, readData, dataSize); + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d, dataSize = %{public}d", __func__, + length, dataSize); + length = dataSize; + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d", __func__, length); + return ERR_OK; +} + +int32_t UsbdClient::SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr) +{ + WRITE_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} +} // namespace USB +} // namespace OHOS diff --git a/hdi/client/src/usbd_subscriber.cpp b/hdi/client/src/usbd_subscriber.cpp new file mode 100644 index 00000000..8cd448c8 --- /dev/null +++ b/hdi/client/src/usbd_subscriber.cpp @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_subscriber.h" +#include "usb_common.h" + +namespace OHOS { +namespace USB { +FoundDevice &UsbdSubscriber::ParserFoundDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + static FoundDevice t; + return t; +} +int UsbdSubscriber::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t ret = ERR_OK; + UsbInfo info; + PortInfo pinfo; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT entry code:%{public}d", __func__, + __LINE__, code); + switch (code) { + case CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT: + USB_HILOGW(MODULE_USBD, "%{public}s CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT entry", __func__); + ParserUsbInfo(data, reply, option, info); + USB_HILOGD(MODULE_USBD, + "%{public}s CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT Read devInfo " + "status=%{public}d,busNum=%{public}d,devAddr=%{public}d", + __func__, info.getDevInfoStatus(), info.getDevInfoBusNum(), info.getDevInfoDevNum()); + ret = DeviceEvent(info); + break; + case CMD_NOTIFY_PORT_CHANGED: + USB_HILOGW(MODULE_USBD, "%{public}s CMD_NOTIFY_PORT_CHANGED entry", __func__); + ParserPortInfo(data, reply, option, pinfo); + ret = PortChangedEvent(pinfo.portId, pinfo.powerRole, pinfo.dataRole, pinfo.mode); + break; + default: + USB_HILOGW(MODULE_USBD, "no specific cmd for code: %{public}d", code); + ret = ERR_INVALID_OPERATION; + break; + } + return ret; +} + +int32_t UsbdSubscriber::ParserUsbInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, UsbInfo &info) +{ + int32_t status; + int32_t busNum; + int32_t devNum; + + if (!data.ReadInt32(status)) { + USB_HILOGW(MODULE_USBD, "Read devInfo status error"); + } + if (!data.ReadInt32(busNum)) { + USB_HILOGW(MODULE_USBD, "Read devInfo busNum error"); + } + if (!data.ReadInt32(devNum)) { + USB_HILOGW(MODULE_USBD, "Read devInfo devNum error"); + } + info.setDevInfoStatus(status); + info.setDevInfoBusNum(busNum); + info.setDevInfoDevNum(devNum); + + USB_HILOGD(MODULE_USBD, "%{public}s Read devInfo status=%{public}d,busNum=%{public}d,devAddr=%{public}d", __func__, + status, busNum, devNum); + return 1; +} + +int32_t UsbdSubscriber::ParserPortInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option, PortInfo &info) +{ + int32_t portId; + int32_t powerRole; + int32_t dataRole; + int32_t mode; + + if (!data.ReadInt32(portId)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo id error"); + return 0; + } + if (!data.ReadInt32(powerRole)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo powerRole error"); + return 0; + } + if (!data.ReadInt32(dataRole)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo dataRole error"); + return 0; + } + if (!data.ReadInt32(mode)) { + USB_HILOGW(MODULE_USBD, "Read PortInfo mode error"); + return 0; + } + info.portId = portId; + info.powerRole = powerRole; + info.dataRole = dataRole; + info.mode = mode; + return 1; +} +} // namespace USB +} // namespace OHOS diff --git a/hdi/service/BUILD.gn b/hdi/service/BUILD.gn new file mode 100644 index 00000000..80ed6424 --- /dev/null +++ b/hdi/service/BUILD.gn @@ -0,0 +1,84 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/ohos.gni") +import("//drivers/adapter/uhdf2/uhdf.gni") + +config("usbd_private_config") { + include_dirs = [ + ] +} + +config("usbd_public_config") { + include_dirs = [ + "include", + "${usb_manager_path}/hdi/api/include", + "//drivers/adapter/uhdf2/include/hdi", + "//drivers/framework/include/utils", + "//drivers/adapter/uhdf2/shared/include", + "//base/notification/ces_standard/cesfwk/kits/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//drivers/framework/include/core", + "//drivers/peripheral/usb/ddk/common/include", + "//drivers/peripheral/usb/ddk/host/include", + "//drivers/peripheral/usb/interfaces/ddk/common", + "//drivers/peripheral/usb/interfaces/ddk/host", + "//drivers/peripheral/usb/interfaces/ddk/device", + "//drivers/peripheral/usb/gadget/function/include", + "//drivers/framework/core/shared/include", + "//drivers/framework/core/adapter/syscall/include", + "//drivers/framework/model/usb/include", + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/log", + ] +} + +ohos_shared_library("usbd") { + sources = [ + "src/usbd.c", + "src/usbd_dispatcher.c", + "src/usbd_publisher.c", + "src/usbd_function.c", + "src/usbd_port.c" + ] + + configs = [ + "${utils_path}:utils_config", + ":usbd_private_config", + ] + + public_configs = [ ":usbd_public_config" ] + + deps = [ + "${hdf_uhdf_path}/host:libhdf_host", + "${hdf_uhdf_path}/ipc:libhdf_ipc_adapter", + "${hdf_uhdf_path}/osal:libhdf_utils", + "//utils/native/base:utils", + "${hdf_uhdf_path}/hdi:libhdi", + "//drivers/peripheral/usb:libusb_ddk", + "//drivers/adapter/uhdf2/config:uhdf_hcs_pkg", + "//drivers/adapter/uhdf2/host:libhdf_host", + "//drivers/peripheral/usb/ddk:libusb_core", + "//base/startup/init_lite/services/param:param_client", + "//third_party/bounds_checking_function:libsec_static", + "//third_party/cJSON:cjson_static", + ] + + external_deps = [ "hiviewdfx_hilog_native:libhilog" ] + + part_name = "usb_manager_native" + + subsystem_name = "hdf" +} diff --git a/hdi/service/include/usbd.h b/hdi/service/include/usbd.h new file mode 100644 index 00000000..bb2e7af3 --- /dev/null +++ b/hdi/service/include/usbd.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_H +#define USBD_H + +#include "data_fifo.h" +#include "hdf_base.h" +#include "hdf_device_desc.h" +#include "osal_atomic.h" +#include "osal_sem.h" +#include "usb_ddk.h" +#include "usb_interface.h" +#include "usb_session.h" +#include "usbd_api.h" +#include "usbd_publisher.h" + +#define USB_MAX_INTERFACES 32 +#define DIRECTION_MASK 0x1 +#define USB_CTRL_SET_TIMEOUT 5000 +#define USB_PIPE_DIR_OFFSET 7 + +struct UsbdService; +struct HostDevice { + struct HdfSListNode node; + struct UsbdService *service; + struct DataFifo readFifo; + struct HdfSList requestQueue; + struct OsalMutex requestLock; + uint8_t interfaceIndex[USB_MAX_INTERFACES]; + uint8_t interfaceCnt; + struct UsbInterface *iface[USB_MAX_INTERFACES]; + UsbInterfaceHandle *ctrDevHandle; + UsbInterfaceHandle *devHandle[USB_MAX_INTERFACES]; + struct OsalMutex writeLock; + struct OsalMutex readLock; + struct OsalMutex lock; + struct UsbRequest *ctrlReq; + struct UsbInterface *ctrIface; + struct UsbPipeInfo *ctrPipe; + uint8_t busNum; + uint8_t devAddr; + bool initFlag; +}; + +struct RequestMsg { + struct HdfSListNode node; + struct UsbRequest *request; + void *clientData; + uint32_t clientLength; +}; + +struct UsbControlParams { + uint8_t request; + UsbRequestTargetType target; + UsbControlRequestType reqType; + UsbRequestDirection directon; + uint16_t value; + uint16_t index; + void *data; + uint16_t size; +}; + +struct UsbDescriptorParams { + UsbInterfaceHandle *devHandle; + struct UsbRequest *request; + uint8_t type; + uint8_t index; + void *buf; + uint16_t size; +}; + +struct UsbdService { + struct IDeviceIoService service; + struct HdfDeviceObject *device; + struct UsbdSubscriber *subscriber; + struct UsbSession *session; + // struct HostDevice *port; + struct HdfSList devList; + struct OsalMutex lock; +}; + +struct UsbdSubscriber; +int32_t BindUsbSubscriber(struct UsbdService *service, struct UsbdSubscriber *subscriber); +int32_t UnbindUsbSubscriber(struct UsbdService *service); + +#endif // USBD_H diff --git a/hdi/service/include/usbd_dispatcher.h b/hdi/service/include/usbd_dispatcher.h new file mode 100644 index 00000000..bb5e7afa --- /dev/null +++ b/hdi/service/include/usbd_dispatcher.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBD_DISPATCHER_H +#define USBD_DISPATCHER_H + +#include "core/hdf_device_desc.h" + +int32_t UsbdServiceDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, struct HdfSBuf *reply); +#endif // USBD_DISPATCHER_H diff --git a/hdi/service/include/usbd_function.h b/hdi/service/include/usbd_function.h new file mode 100644 index 00000000..e571df50 --- /dev/null +++ b/hdi/service/include/usbd_function.h @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USBD_FUNCTION_H +#define USBD_FUNCTION_H +#include "usbd.h" + +int32_t UsbdSetFunction(int funcs); +int32_t UsbdGetFunction(); + +#endif diff --git a/hdi/service/include/usbd_parser.h b/hdi/service/include/usbd_parser.h new file mode 100644 index 00000000..06e29c92 --- /dev/null +++ b/hdi/service/include/usbd_parser.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 USBD_PARSER_H +#define USBD_PARSER_H + +#include "usbd_api.h" + +int32_t InitUsbdSysfs(void); +int32_t ParseCapacity(int32_t *capacity); +int32_t ParseVoltage(int32_t *voltage); +int32_t ParseTemperature(int32_t *temperature); +int32_t ParseHealthState(int32_t *healthState); +int32_t ParsePluggedType(int32_t *pluggedType); +int32_t ParseChargeState(int32_t *chargeState); +int32_t ParsePresent(int8_t *present); +int32_t ParseTechnology(char *technology, size_t size); +void ParseUeventToUsbdInfo(const char *msg, struct UsbdInfo *info); +int32_t SwitchRole(int32_t portId, int32_t powerRole, int32_t dataRole); +int changeRole(const char *portName, enum PortRoleType type, int32_t role); +int32_t readFile(const char *filename, char contents); +char *appendRoleNodeHelper(const char *portName, enum PortRoleType type); +char *convertRoletoString(enum PortRoleType type, int32_t role); + +#endif // USBD_PARSER_H diff --git a/hdi/service/include/usbd_port.h b/hdi/service/include/usbd_port.h new file mode 100644 index 00000000..f26da3ae --- /dev/null +++ b/hdi/service/include/usbd_port.h @@ -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. + */ + +#ifndef USBD_PORT_H +#define USBD_PORT_H + +#include "usbd.h" + +int SetPort(int portId, int powerRole, int dataRole, struct UsbdService *service); +int QueryPort(int *portId, int *powerRole, int *dataRole, int *mode, struct UsbdService *service); + +#endif diff --git a/hdi/service/include/usbd_publisher.h b/hdi/service/include/usbd_publisher.h new file mode 100644 index 00000000..b35cada8 --- /dev/null +++ b/hdi/service/include/usbd_publisher.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 USBD_PUBLISHER_H +#define USBD_PUBLISHER_H + +#include "usbd.h" +#include "usbd_api.h" + +struct UsbdSubscriber { + struct HdfRemoteService *remoteService; +}; + +void NotifyUsbPortSubscriber(const struct UsbdSubscriber *subscriber, + int32_t portId, + int32_t powerRole, + int32_t dataRole, + int32_t mode); +void NotifySubscriberDevice(const struct UsbdSubscriber *subscriber, + enum UsbdDeviceAction act, + int32_t busNum, + int32_t devNum); + +#endif // USBD_PUBLISHER_H diff --git a/hdi/service/src/usbd.c b/hdi/service/src/usbd.c new file mode 100644 index 00000000..c5dfe1c6 --- /dev/null +++ b/hdi/service/src/usbd.c @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd.h" +#include +#include "devmgr_service_if.h" +#include "hdf_base.h" +#include "hdf_io_service_if.h" +#include "hdf_log.h" +#include "hdf_syscall_adapter.h" +#include "hdf_usb_pnp_manage.h" +#include "osal_mem.h" +#include "osal_time.h" +#include "securec.h" +#include "usb_ddk_pnp_loader.h" +#include "usbd_dispatcher.h" +#include "usbd_function.h" +#include "usbd_parser.h" +#include "usbd_publisher.h" + +int32_t HdfDeviceRegisterEventListener(struct HdfIoService *target, struct HdfDevEventlistener *listener); + +static int32_t UsbdDriverBind(struct HdfDeviceObject *device); +static int32_t UsbdDriverInit(struct HdfDeviceObject *device); +static void UsbdDriverRelease(struct HdfDeviceObject *device); +int32_t UsbdRealseDevices(struct UsbdService *service); +int32_t HostDeviceCreate(struct HostDevice **port); + +static int UsbdEventHandle(struct UsbdService *inst); + +/* HdfDriverEntry implementations */ +static int32_t UsbdDriverBind(struct HdfDeviceObject *device) +{ + struct UsbdService *dev = NULL; + struct UsbPnpNotifyServiceInfo *info = NULL; + int32_t ret; + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + if (device == NULL) { + HDF_LOGE("%{public}s:%{public}d device is null", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + dev = (struct UsbdService *)OsalMemCalloc(sizeof(struct UsbdService)); + if (dev == NULL) { + HDF_LOGE("%{public}s: Alloc dev device failed", __func__); + return HDF_FAILURE; + } + memset(dev, 0, sizeof(struct UsbdService)); + if (OsalMutexInit(&dev->lock) != HDF_SUCCESS) { + HDF_LOGE(" init lock fail!"); + return HDF_FAILURE; + } + info = (struct UsbPnpNotifyServiceInfo *)device->priv; + if (info) { + struct HostDevice *port = NULL; + ret = HostDeviceCreate(&port); + if (ret == HDF_SUCCESS) { + port->busNum = info->busNum; + port->devAddr = info->busNum; + port->service = dev; + OsalMutexLock(&dev->lock); + HdfSListAdd(&dev->devList, &port->node); + OsalMutexUnlock(&dev->lock); + } + } + HDF_LOGE("%{public}s: fumang exit", __func__); + device->service = &(dev->service); + device->service->Dispatch = UsbdServiceDispatch; + dev->device = device; + UsbdEventHandle(dev); + return HDF_SUCCESS; +} + +static int32_t UsbdDriverInit(struct HdfDeviceObject *device) +{ + int32_t ret = HDF_SUCCESS; + HDF_LOGE("%{public}s:%{public}d fumang exit", __func__, __LINE__); + if (device == NULL) { + HDF_LOGE("%{public}s:%{public}d device is null", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + + HDF_LOGD("%{public}s:%{public}d init ok!", __func__, __LINE__); + return ret; +} + +static void UsbdDriverRelease(struct HdfDeviceObject *device) +{ + struct UsbdService *dev = NULL; + HDF_LOGE("%{public}s:%{public}d fumang exit", __func__, __LINE__); + if (device == NULL) { + HDF_LOGE("%{public}s: device is NULL", __func__); + return; + } + dev = (struct UsbdService *)device->service; + UsbdRealseDevices(dev); + HDF_LOGD("%{public}s:%{public}d exit", __func__, __LINE__); +} + +struct HdfDriverEntry g_usbdDriverEntry = { + .moduleVersion = 1, + .moduleName = "usbd", + .Bind = UsbdDriverBind, + .Init = UsbdDriverInit, + .Release = UsbdDriverRelease, +}; +HDF_INIT(g_usbdDriverEntry); + +static int UsbdAddDevicesOnStart(struct UsbdService *service); + +int32_t BindUsbSubscriber(struct UsbdService *service, struct UsbdSubscriber *subscriber) +{ + HDF_LOGE("%{public}s: fumang entry", __func__); + HDF_LOGE("%{public}s:%{public}d fumang entry service:%{public}p subscriber:%{public}p", __func__, __LINE__, service, + subscriber); + if (service == NULL) { + HDF_LOGW("%{public}s fumang service is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + service->subscriber = subscriber; + UsbdAddDevicesOnStart(service); + return HDF_SUCCESS; +} + +int32_t UnbindUsbSubscriber(struct UsbdService *service) +{ + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + if (service == NULL) { + HDF_LOGW("%{public}s service is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (service->subscriber != NULL) { + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + OsalMemFree(service->subscriber); + service->subscriber = NULL; + } + return HDF_SUCCESS; +} + +static int UsbdPnpLoaderEventReceived(void *priv, uint32_t id, struct HdfSBuf *data) +{ + int ret = HDF_SUCCESS; + bool flag = false; + uint32_t infoSize; + struct UsbPnpNotifyMatchInfoTable *infoTable = NULL; + struct UsbdService *super = (struct UsbdService *)priv; + + HDF_LOGI("%{public}s:%{public}d id:%{public}d service:%{public}s subscriber:%{public}s ", __func__, __LINE__, id, + super ? "OK" : "NULL", super ? (super->subscriber ? "OK" : "NULL") : "NULL"); + if (!super) { + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGI("%{public}s:%{public}d id:%{public}d service:%{public}p subscriber:%{public}p ", __func__, __LINE__, id, + super, super->subscriber); + if (USB_PNP_DRIVER_GADGET_ADD == id) { + NotifySubscriberDevice(super->subscriber, ACT_UPDEVICE, 0, 0); + return HDF_SUCCESS; + } else if (USB_PNP_DRIVER_GADGET_REMOVE == id) { + NotifySubscriberDevice(super->subscriber, ACT_DOWNDEVICE, 0, 0); + return HDF_SUCCESS; + } + flag = HdfSbufReadBuffer(data, (const void **)(&infoTable), &infoSize); + if ((flag == false) || (infoTable == NULL)) { + ret = HDF_ERR_INVALID_PARAM; + HDF_LOGE("%{public}s: fail to read infoTable in event data, flag=%{public}d, infoTable=%{public}p", __func__, + flag, infoTable); + return ret; + } + + HDF_LOGI( + "%{public}s:%{public}d id=%{public}d infoSize=%{public}d, usbDevAddr=0x%{public}x, devNum=%{public}d, \ + busNum=%{public}d, class:%{public}d infoTable=0x%{public}x-0x%{public}x success", + __func__, __LINE__, id, infoSize, infoTable->usbDevAddr, infoTable->devNum, infoTable->busNum, + infoTable->deviceInfo.deviceClass, infoTable->deviceInfo.vendorId, infoTable->deviceInfo.productId); + + if (0x09 == infoTable->deviceInfo.deviceClass) { + HDF_LOGI("%{public}s:%{public}d hub device ret:%{public}d", __func__, __LINE__, ret); + return ret; + } + switch (id) { + case USB_PNP_NOTIFY_ADD_DEVICE: + ret = HDF_SUCCESS; + if (0x09 != infoTable->deviceInfo.deviceClass) + NotifySubscriberDevice(super->subscriber, ACT_DEVUP, infoTable->busNum, infoTable->devNum); + break; + case USB_PNP_NOTIFY_REMOVE_DEVICE: + ret = HDF_SUCCESS; + if (0x09 != infoTable->deviceInfo.deviceClass) + NotifySubscriberDevice(super->subscriber, ACT_DEVDOWN, infoTable->busNum, infoTable->devNum); + break; + default: + ret = HDF_SUCCESS; + break; + } + + HDF_LOGI("%{public}s:%{public}d ret=%{public}d DONE", __func__, __LINE__, ret); + + return ret; +} + +static int UsbdEventHandle(struct UsbdService *inst) +{ + int status; + struct HdfIoService *usbPnpServ = HdfIoServiceBind(USB_PNP_NOTIFY_SERVICE_NAME); + static struct HdfDevEventlistener usbPnpListener = { + .callBack = UsbdPnpLoaderEventReceived, + }; + usbPnpListener.priv = (void *)(inst); + + if (usbPnpServ == NULL) { + HDF_LOGE("%{public}s: HdfIoServiceBind faile.", __func__); + return HDF_ERR_INVALID_OBJECT; + } + + status = HdfDeviceRegisterEventListener(usbPnpServ, &usbPnpListener); + if (status != HDF_SUCCESS) { + HDF_LOGE("HdfDeviceRegisterEventListener faile status=%{public}d", status); + return status; + } + + return HDF_SUCCESS; +} + +static int UsbdAddDevicesOnStart(struct UsbdService *service) +{ + int32_t ret = HDF_SUCCESS; + struct HdfIoService *usbPnpServ = HdfIoServiceBind(USB_PNP_NOTIFY_SERVICE_NAME); + struct HdfSBuf *data; + struct HdfSBuf *reply; + int32_t count = 0, size = 0; + + if (service == NULL) { + HDF_LOGE("%{public}s:%{public}d service is NULL.", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + + if (usbPnpServ == NULL) { + HDF_LOGE("%{public}s: HdfIoServiceBind faile serv:%{public}s.", __func__, USB_PNP_NOTIFY_SERVICE_NAME); + return HDF_ERR_INVALID_OBJECT; + } + + data = HdfSBufObtainDefaultSize(); + if (data == NULL) { + ret = HDF_DEV_ERR_NO_MEMORY; + HDF_LOGE("%{public}s: fail to obtain sbuf data", __func__); + return ret; + } + reply = HdfSBufObtainDefaultSize(); + if (reply == NULL) { + ret = HDF_DEV_ERR_NO_MEMORY; + HDF_LOGE("%{public}s: fail to obtain sbuf reply", __func__); + goto out; + } + + ret = usbPnpServ->dispatcher->Dispatch(&usbPnpServ->object, USB_PNP_DRIVER_GETDEVICES, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: fail to send serivice call, ret=%{public}d", __func__, ret); + goto out; + } + + while (1) { + int32_t busNum; + int32_t devNum; + uint8_t devClass; + uint8_t subClass; + uint8_t protocol; + uint8_t status; + if (!HdfSbufReadInt32(reply, &busNum)) { + HDF_LOGE("%{public}s: fail to get service call reply", __func__); + break; + } + if (!HdfSbufReadInt32(reply, &devNum)) { + HDF_LOGE("%{public}s: fail to get service call reply", __func__); + break; + } + if (!HdfSbufReadUint8(reply, &devClass)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + if (!HdfSbufReadUint8(reply, &subClass)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + if (!HdfSbufReadUint8(reply, &protocol)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + if (!HdfSbufReadUint8(reply, &status)) { + ret = HDF_ERR_INVALID_OBJECT; + HDF_LOGE("%{public}s:%{public}d fail to get service call reply", __func__, __LINE__); + break; + } + HDF_LOGI( + "%{public}s:%{public}d OnStart get device[%{public}d]:%{public}d:%{public}d status:%{pubic}d " + "class:%{public}d subClass:%{public}d protocol:%{pubic}d", + __func__, __LINE__, count, busNum, devNum, status, devClass, subClass, protocol); + if (devClass != 0x09) { + NotifySubscriberDevice(service->subscriber, ACT_DEVUP, busNum, devNum); + ++size; + } + ++count; + } + + HDF_LOGI("%{public}s:%{public}d onStart add devices:%{public}d size:%{public}d success", __func__, __LINE__, count, + size); + +out: + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + HdfIoServiceRecycle(usbPnpServ); + return ret; +} diff --git a/hdi/service/src/usbd_dispatcher.c b/hdi/service/src/usbd_dispatcher.c new file mode 100644 index 00000000..bccd59f8 --- /dev/null +++ b/hdi/service/src/usbd_dispatcher.c @@ -0,0 +1,2087 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_dispatcher.h" +#include +#include +#include "hdf_base.h" +#include "hdf_log.h" +#include "hdf_usb_pnp_manage.h" +#include "osal_mem.h" +#include "osal_sem.h" +#include "osal_time.h" +#include "securec.h" +#include "usb_interface_pool.h" +#include "usbd.h" +#include "usbd_function.h" +#include "usbd_parser.h" +#include "usbd_port.h" +#include "usbd_publisher.h" + +#define HDF_LOG_TAG usbd_dispatcher + +#define MAX_BUFF_SIZE 16384 +#define MAX_CONTROL_BUFF_SIZE 1024 +#define READ_BUF_SIZE 8192 + +#define USB_CTRL_SET_TIMEOUT 5000 +#define USB_PIPE_DIR_OFFSET 7 +#define CHARFORMAT 8 +#define USB_REUQEST_SLEEP_TIME 100 +#define USB_MAX_DESCRIPTOR_SIZE 256 + +#define OPEN_SLEPP_TIME 1000 +#define SUBMIT_SLEEP_TIME 500 + +static int32_t DispatchBindUsbSubscriber(struct UsbdService *service, struct HdfSBuf *data); +static int32_t DispatchUnbindUsbSubscriber(struct UsbdService *service); +static int32_t GetPipe(const struct HostDevice *dev, uint8_t interfaceId, uint8_t pipeId, struct UsbPipeInfo *pipe); +static int32_t UsbControlTransfer(struct HostDevice *dev, + int32_t requestCmd, + int32_t cmdType, + int32_t target, + int32_t direction, + int32_t value, + int32_t index, + int32_t timeout, + uint8_t *buffer, + uint32_t *length); + +int32_t HostDeviceCreate(struct HostDevice **port); +int32_t UsbdRealseDevices(struct UsbdService *service); +static struct HostDevice *FindDevFromService(struct UsbdService *service, uint8_t busNum, uint8_t devAddr); +static int32_t RemoveDevFromService(struct UsbdService *service, struct HostDevice *port); + +static int32_t UsbdInit(struct HostDevice *dev); +static void UsbdRelease(struct HostDevice *dev); + +void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + if (title == NULL || buffer == NULL || length == 0) { + return; + } + uint32_t logLength = strlen(title) + length * 3 + 50; + char *logBuffer = (char *)OsalMemAlloc(logLength); + if (logBuffer == NULL) { + return; + } + memset(logBuffer, 0, logLength); + sprintf_s(logBuffer, logLength, " %s << 二进制数据流,%u字节 >> :", title, length); + uint32_t pos = strlen(logBuffer); + for (uint32_t i = 0; i < length; ++i) { + sprintf_s(logBuffer + pos, logLength - pos, " %02x", buffer[i]); + pos += 3; + } + sprintf_s(logBuffer + pos, logLength - pos, " --> %s \n", buffer); + HDF_LOGE("%{public}s", logBuffer); + OsalMemFree(logBuffer); +} + +static int32_t ParseDeviceBuf(struct HdfSBuf *data, uint8_t *busNum, uint8_t *devAddr) +{ + if (data == NULL || busNum == NULL || devAddr == NULL) { + return HDF_ERR_INVALID_PARAM; + } + HdfSbufReadUint8(data, busNum); + HdfSbufReadUint8(data, devAddr); + return HDF_SUCCESS; +} + +static int32_t UsbdAllocFifo(struct DataFifo *fifo, uint32_t size) +{ + if (!DataFifoIsInitialized(fifo)) { + void *data = OsalMemAlloc(size); + if (data == NULL) { + HDF_LOGE("%{public}s:%{public}d allocate failed", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + DataFifoInit(fifo, size, data); + } + return HDF_SUCCESS; +} + +static void UsbdFreeFifo(struct DataFifo *fifo) +{ + if (fifo == NULL) { + HDF_LOGE("%{public}s:%{public}d fifo is NULL", __func__, __LINE__); + return; + } + + if (fifo->data != NULL) { + OsalMemFree(fifo->data); + fifo->data = NULL; + } + + DataFifoInit(fifo, 0, NULL); +} + +static struct RequestMsg *UsbdAllocRequestMsg(UsbInterfaceHandle *interfaceHandle, int32_t isoPackets, int32_t length) +{ + struct RequestMsg *reqMsg = NULL; + reqMsg = (struct RequestMsg *)OsalMemAlloc(sizeof(struct RequestMsg)); + if (reqMsg == NULL) { + HDF_LOGE("HDF_ERR_MALLOC_FAIL faild\n"); + return NULL; + } + memset(reqMsg, 0, sizeof(*reqMsg)); + reqMsg->request = UsbAllocRequest(interfaceHandle, 0, length); + if (reqMsg->request == NULL) { + HDF_LOGE("HDF_ERR_MALLOC_FAIL faild\n"); + OsalMemFree(reqMsg); + return NULL; + } + reqMsg->clientData = NULL; + reqMsg->clientLength = 0; + return reqMsg; +} + +static int32_t UsbdFreeRequestMsg(struct RequestMsg *reqMsg) +{ + if (reqMsg == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + if (reqMsg->request != NULL) { + UsbFreeRequest(reqMsg->request); + } + if (reqMsg->clientData) { + OsalMemFree(reqMsg->clientData); + } + reqMsg->clientData = NULL; + reqMsg->clientLength = 0; + OsalMemFree(reqMsg); + reqMsg = NULL; + + return HDF_SUCCESS; +} + +static void UsbdReadCallback(struct UsbRequest *req) +{ + uint8_t *data = NULL; + uint32_t dataSize = 0, readSize = 0; + struct UsbIfRequest *reqObj = (struct UsbIfRequest *)req; + HDF_LOGE("%{public}s:%{pulib}d entry", __func__, __LINE__); + if (req == NULL) { + HDF_LOGE("%{public}s:%{pulib}d req is NULL!", __func__, __LINE__); + return; + } + int status = req->compInfo.status; + dataSize = req->compInfo.actualLength; + struct HostDevice *dev = (struct HostDevice *)req->compInfo.userData; + if (dev == NULL) { + HDF_LOGE("%{public}s:%{pulib}d dev is NULL!", __func__, __LINE__); + goto exit; + } + + switch (status) { + case 0: + HDF_LOGD("Bulk status: %{public}d+size:%{public}u\n", status, dataSize); + if (dataSize > 0) { + data = req->compInfo.buffer; + OsalMutexLock(&dev->readLock); + if (DataFifoIsFull(&dev->readFifo)) { + HDF_LOGD("%{public}s:%{public}d", __func__, __LINE__); + DataFifoSkip(&dev->readFifo, dataSize); + } + readSize = DataFifoWrite(&dev->readFifo, data, dataSize); + if (readSize != dataSize) { + HDF_LOGW("%{public}s: write %{public}u less than expected %{public}zu", __func__, dataSize, + readSize); + } + + OsalMutexUnlock(&dev->readLock); + } + break; + default: + HDF_LOGE("%{public}s:%{public}d status=%{public}d", __func__, __LINE__, status); + break; + } + +exit: + OsalSemPost(&reqObj->hostRequest->sem); +} + +static void UsbdWriteCallback(struct UsbRequest *req) +{ + HDF_LOGE("%{public}s:%{pulib}d entry", __func__, __LINE__); + if (req == NULL) { + HDF_LOGE("%{public}s:%{pulib}d req is NULL!", __func__, __LINE__); + return; + } + struct HostDevice *dev = (struct HostDevice *)req->compInfo.userData; + if ((dev == NULL) || (dev == NULL)) { + HDF_LOGE("%{public}s:%{pulib}d dev or dev->port is NULL!", __func__, __LINE__); + return; + } + int status = req->compInfo.status; + HDF_LOGE("%{public}s:%{pulib}d statue is %d!", __func__, __LINE__, status); + switch (status) { + case 0: + break; + case -ECONNRESET: + case -ENOENT: + case -ESHUTDOWN: + break; + default: + break; + } + + return; +} + +static UsbInterfaceHandle *InterfaceIdToHandle(const struct HostDevice *dev, uint8_t id) +{ + UsbInterfaceHandle *devHandle = NULL; + + if (id == 0xFF) { + devHandle = dev->ctrDevHandle; + } else if (id < USB_MAX_INTERFACES) { + return dev->devHandle[id]; + } + return devHandle; +} + +static int32_t UsbControlSetUp(struct UsbControlParams *controlParams, struct UsbControlRequest *controlReq) +{ + if (controlParams == NULL || controlReq == NULL) { + return HDF_ERR_INVALID_PARAM; + } + + controlReq->target = controlParams->target; + controlReq->reqType = controlParams->reqType; + controlReq->directon = controlParams->directon; + controlReq->request = controlParams->request; + controlReq->value = CpuToLe16(controlParams->value); + controlReq->index = CpuToLe16(controlParams->index); + controlReq->buffer = controlParams->data; + controlReq->length = CpuToLe16(controlParams->size); + return HDF_SUCCESS; +} + +static struct UsbInterface *GetUsbInterfaceById(const struct HostDevice *dev, uint8_t interfaceIndex) +{ + struct UsbInterface *tmpIf = NULL; + + if (!dev || (dev->service == NULL)) { + HDF_LOGE("%{public}s:%{public}d idx:%{public}d service is null", __func__, __LINE__, interfaceIndex); + return NULL; + } + HDF_LOGE( + "%{public}s:%{public}d UsbClaimInterface start session:%{public}s bus:%{public}d dev:%{public}d " + "idex:%{public}d", + __func__, __LINE__, dev->service->session ? "OK" : "NULL", dev->busNum, dev->devAddr, interfaceIndex); + tmpIf = (struct UsbInterface *)UsbClaimInterface(dev->service->session, dev->busNum, dev->devAddr, interfaceIndex); + HDF_LOGE( + "%{public}s:%{public}d UsbClaimInterface end session:%{public}s bus:%{public}d dev:%{public}d idex:%{public}d", + __func__, __LINE__, dev->service->session ? "OK" : "NULL", dev->busNum, dev->devAddr, interfaceIndex); + if (tmpIf == NULL) { + HDF_LOGE("%{public}s:%{public}d failed busNum=%{public}d, devAddr=%{public}d, interface=%{public}d", __func__, + __LINE__, dev->busNum, dev->devAddr, interfaceIndex); + } + return tmpIf; +} + +static int32_t GetInterfacePipe(const struct HostDevice *dev, + struct UsbInterface *interface, + uint8_t pipeAddr, + struct UsbPipeInfo *pipe) +{ + int32_t ret = HDF_FAILURE; + struct UsbInterfaceInfo *info = NULL; + UsbInterfaceHandle *interfaceHandle = NULL; + struct UsbPipeInfo pipeTmp; + memset(&pipeTmp, 0, sizeof(pipeTmp)); + if (dev == NULL || interface == NULL || pipe == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid parmas", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + info = &interface->info; + if (info == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid interface", __func__, __LINE__); + return HDF_FAILURE; + } + + interfaceHandle = InterfaceIdToHandle(dev, info->interfaceIndex); + if (interfaceHandle == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid interface handle", __func__, __LINE__); + return HDF_FAILURE; + } + + for (uint8_t i = 1; i <= info->pipeNum; ++i) { + ret = UsbGetPipeInfo(interfaceHandle, info->curAltSetting, i, &pipeTmp); + HDF_LOGE( + "%{public}s:%{public}d UsbGetPipeInfo [%{public}d/%{public}d] ret:%{public}d Addr:0x%{public}02x " + "pipeAddr:0x%{public}02x id:%{public}d type:%{public}d direction:%{public}d ifcId:%{public}d", + __func__, __LINE__, i, info->pipeNum, ret, pipeAddr, pipeTmp.pipeAddress, pipeTmp.pipeId, pipeTmp.pipeType, + pipeTmp.pipeDirection, pipeTmp.interfaceId); + if ((ret == HDF_SUCCESS) && ((pipeTmp.pipeAddress | (uint8_t)pipeTmp.pipeDirection) == pipeAddr)) { + if (pipe) + *pipe = pipeTmp; + return HDF_SUCCESS; + } + } + return HDF_FAILURE; +} + +static int32_t GetPipe(const struct HostDevice *dev, uint8_t interfaceId, uint8_t pipeId, struct UsbPipeInfo *pipe) +{ + int32_t ret = HDF_SUCCESS; + struct UsbInterface *interface = NULL; + + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid parmas", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (interfaceId > USB_MAX_INTERFACES) { + HDF_LOGE("%{public}s:%{public}d invalid parmas", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + interface = dev->iface[interfaceId]; + if (interface == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid interface", __func__, __LINE__); + return HDF_FAILURE; + } + + ret = GetInterfacePipe(dev, interface, pipeId, pipe); + return ret; +} + +static void UsbdFreeCtrlPipe(struct HostDevice *dev) +{ + if (dev == NULL) { + return; + } + if (dev->ctrPipe) { + OsalMemFree(dev->ctrPipe); + dev->ctrPipe = NULL; + } +} + +static int32_t UsbdGetCtrlPipe(struct HostDevice *dev) +{ + int32_t ret; + struct UsbPipeInfo *pipe = NULL; + pipe = (struct UsbPipeInfo *)OsalMemAlloc(sizeof(struct UsbPipeInfo)); + if (pipe == NULL) { + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc failed", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + + memset(pipe, 0, sizeof(struct UsbPipeInfo)); + HDF_LOGE( + "%{public}s: constrol interface info : %{public}d, %{public}d, %{public}d, \ + %{public}d, %{public}d, %{public}d, %{public}d,", + __func__, dev->ctrIface->info.interfaceIndex, dev->ctrIface->info.altSettings, + dev->ctrIface->info.curAltSetting, dev->ctrIface->info.pipeNum, dev->ctrIface->info.interfaceClass, + dev->ctrIface->info.interfaceSubClass, dev->ctrIface->info.interfaceProtocol); + ret = UsbGetPipeInfo(dev->ctrDevHandle, dev->ctrIface->info.curAltSetting, 0, pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d get pipe failed ret = %{public}d", __func__, __LINE__, ret); + OsalMemFree(pipe); + return HDF_FAILURE; + } + dev->ctrPipe = pipe; + + return HDF_SUCCESS; +} + +static int32_t FunBulkReadSync(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + struct UsbPipeInfo pipe; + struct UsbRequest *request = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + + memset(&parmas, 0, sizeof(parmas)); + memset(&pipe, 0, sizeof(pipe)); + + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d read interfaceId error", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s:%{public}d read pipeId error", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d read timeout error", __func__, __LINE__); + return HDF_ERR_IO; + } + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d get pipe info failed interfaceId=%{public}d, pipeId=%{public}d", __func__, + __LINE__, interfaceId, pipeId); + return HDF_FAILURE; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (!interfaceHandle) { + HDF_LOGE("%{public}s:%{public}d InterfaceIdToHandle failed interfaceId=%{public}d, pipeId=%{public}d", __func__, + __LINE__, interfaceId, pipeId); + return HDF_FAILURE; + } + request = UsbAllocRequest(interfaceHandle, 0, pipe.maxPacketSize); + if (!request) { + HDF_LOGE("%{public}s:%{public}d readReq request faild", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + + HDF_LOGD("%{public}s:%{public}d request:%{public}p ", __func__, __LINE__, request); + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.interfaceId = pipe.interfaceId; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_DIR_OFFSET) & 0x1; + parmas.dataReq.length = pipe.maxPacketSize; + ret = UsbFillRequest(request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto out; + } + + ret = UsbSubmitRequestSync(request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestSync faile, ret=%{public}d \n", ret); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto out; + } + + HDF_LOGD("%{public}s:%{public}d fumang buffer:%{public}p-%{public}p-actualLength:%{public}d", __func__, __LINE__, + request->compInfo.buffer, (uint8_t *)request->compInfo.buffer, request->compInfo.actualLength); + struct UsbIfRequest *reqObj = (struct UsbIfRequest *)request; + OsalMutexLock(&reqObj->hostRequest->lock); + if (!HdfSbufWriteBuffer(reply, (const void *)request->compInfo.buffer, request->compInfo.actualLength)) { + HDF_LOGE("%{public}s: sbuf write buffer failed", __func__); + ret = HDF_ERR_IO; + } + OsalMutexUnlock(&reqObj->hostRequest->lock); + +out: + UsbFreeRequest(request); + return ret; +} + +static int32_t FunBulkWriteSync(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + uint32_t length = 0; + UsbInterfaceHandle *interfaceHandle = NULL; + struct UsbPipeInfo pipe; + struct UsbRequest *request = NULL; + struct UsbRequestParams parmas = {}; + + memset(&parmas, 0, sizeof(parmas)); + memset(&pipe, 0, sizeof(pipe)); + + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_IO; + } + + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed interfaceId=%{public}d, pipeId=%{public}d", __func__, interfaceId, + pipeId); + return HDF_FAILURE; + } + + interfaceHandle = InterfaceIdToHandle(port, interfaceId); + if (interfaceHandle == NULL) { + HDF_LOGE("%{public}s: get interface handle faild \n", __func__); + return HDF_ERR_INVALID_PARAM; + } + request = UsbAllocRequest(interfaceHandle, 0, pipe.maxPacketSize); + if (!request) { + HDF_LOGE("%{public}s: alloc request faild\n", __func__); + return HDF_ERR_MALLOC_FAIL; + } + + HDF_LOGD("%{public}s:%{public}d fumang debug buffer:%{public}s, length:%{public}d, maxPacketSize:%{public}d \n", + __func__, __LINE__, buffer, length, pipe.maxPacketSize); + parmas.interfaceId = pipe.interfaceId; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.userData = port; + parmas.dataReq.length = length; + parmas.dataReq.buffer = buffer; + ret = UsbFillRequest(request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto out; + } + HDF_LOGD("%{public}s:%{public}d fumang debug buffer:%{public}s, length:%{public}d, maxPacketSize:%{public}d \n", + __func__, __LINE__, buffer, length, pipe.maxPacketSize); + ret = UsbSubmitRequestSync(request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestSync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMSleep(SUBMIT_SLEEP_TIME); + } + +out: + UsbFreeRequest(request); + return ret; +} + +static int32_t UsbControlTransfer(struct HostDevice *dev, + int32_t requestCmd, + int32_t cmdType, + int32_t target, + int32_t direction, + int32_t value, + int32_t index, + int32_t timeout, + uint8_t *buffer, + uint32_t *length) +{ + int ret = 0; + struct UsbRequest *request = NULL; + struct UsbControlParams controlParams = {}; + struct UsbRequestParams parmas = {}; + + memset(&controlParams, 0, sizeof(controlParams)); + memset(&parmas, 0, sizeof(parmas)); + + if (NULL == dev || NULL == buffer || length == NULL) { + HDF_LOGE("%{public}s:%{public}d null pointer faild", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + request = UsbAllocRequest(dev->ctrDevHandle, 0, MAX_CONTROL_BUFF_SIZE); + if (!request) { + HDF_LOGE("%{public}s:%{public}d UsbAllocRequest alloc request faild\n", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + + controlParams.request = (uint8_t)requestCmd; + controlParams.target = (UsbRequestTargetType)target; + controlParams.reqType = (UsbControlRequestType)cmdType; + controlParams.directon = (UsbRequestDirection)direction; + controlParams.value = value; + controlParams.index = index; + controlParams.data = (void *)buffer; + controlParams.size = *length; + parmas.interfaceId = USB_CTRL_INTERFACE_ID; + parmas.pipeAddress = 0; + parmas.pipeId = 0; + parmas.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; + parmas.timeout = timeout; + UsbControlSetUp(&controlParams, &parmas.ctrlReq); + + ret = UsbFillRequest(request, dev->ctrDevHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d UsbFillRequest faile, ret=%{public}d ", __func__, __LINE__, ret); + goto out; + } + + ret = UsbSubmitRequestSync(request); + HDF_LOGD("%{public}s:%{public}d UsbSubmitRequestSync ret=%{public}d ", __func__, __LINE__, ret); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d UsbSubmitRequestSync faile, ret=%{public}d ", __func__, __LINE__, ret); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto out; + } + + if (USB_REQUEST_DIR_FROM_DEVICE == direction) { + HDF_LOGD("%{public}s: fumang debug length=%{public}d, actualLength=%{public}d rlen:=%{public}d", __func__, + request->compInfo.length, request->compInfo.actualLength, *length); + memcpy_s(buffer, *length, request->compInfo.buffer, request->compInfo.actualLength); + if (*length > request->compInfo.actualLength) + *length = request->compInfo.actualLength; + PrintBuffer("UsbControlTransfer", buffer, *length); + } + +out: + UsbFreeRequest(request); + return ret; +} + +static int32_t FunControlTransfer(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + int32_t requestCmd = 0, requestType = 0, value = 0, index = 0, timeout = 0; + int32_t target = 0, direction = 0, cmdType = 0; + + HDF_LOGE("%{public}s:%{public}d mangf FunControlTransfer entry", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (port->ctrDevHandle == NULL) { + HDF_LOGE("%{public}s:%{public}d interface handle is null \n", __func__, __LINE__); + ret = HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadInt32(data, &requestType)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &requestCmd)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &value)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &index)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d read param fail", __func__, __LINE__); + return HDF_ERR_IO; + } + + target = requestType & 0x1F; + direction = (requestType >> 7) & 0x1; + cmdType = (requestType >> 5) & 0x3; + HDF_LOGE("%{public}s:%{public}d direction:%{public}d target:%{public}d cmdType::%{public}d\n", __func__, __LINE__, + direction, target, cmdType); + if (direction == USB_REQUEST_DIR_TO_DEVICE) { + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s:%{public}d mangf hdf sbuf Read failed", __func__, __LINE__); + return HDF_FAILURE; + } + HDF_LOGE("%{public}s:%{public}d HdfSbufReadBuffer length = %{public}d", __func__, __LINE__, length); + } else { + length = MAX_CONTROL_BUFF_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (buffer == NULL) { + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc faild length = %{public}d", __func__, __LINE__, length); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc length = %{public}d", __func__, __LINE__, length); + } + ret = UsbControlTransfer(port, requestCmd, cmdType, target, direction, value, index, timeout, buffer, &length); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d UsbControlTransfer faild ret:%{public}d\n", __func__, __LINE__, ret); + } + HDF_LOGE("%{public}s:%{public}d UsbControlTransfer ok length = %{public}d", __func__, __LINE__, length); + if (direction == USB_REQUEST_DIR_FROM_DEVICE) { + PrintBuffer("FunControlTransfer 738", buffer, length); + if ((HDF_SUCCESS == ret) && (!HdfSbufWriteBuffer(reply, buffer, length))) { + HDF_LOGE("%{public}s:%{public}d sbuf write buffer failed", __func__, __LINE__); + } + if (buffer) + OsalMemFree(buffer); + } + return ret; +} + +static int32_t UsbdReleaseInterface(struct HostDevice *dev, uint8_t interfaceId) +{ + int32_t ret = HDF_FAILURE; + HDF_LOGE("%{public}s:%{public}d interfaceId:%{public}d dev:%{public}s", __func__, __LINE__, interfaceId, + dev ? "OK" : "NULL"); + if (interfaceId >= USB_MAX_INTERFACES) { + HDF_LOGE("%{public}s:%{public}d interfaceId:%{public}d fail", __func__, __LINE__, interfaceId); + return HDF_ERR_INVALID_PARAM; + } + if (!dev) { + HDF_LOGE("%{public}s:%{public}d dev is null", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (dev->devHandle[interfaceId] != NULL) { + ret = UsbCloseInterface(dev->devHandle[interfaceId]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbCloseInterface failed id = %{public}d ret:%{public}d", __func__, interfaceId, ret); + return ret; + } + dev->devHandle[interfaceId] = NULL; + } + + if (dev->iface[interfaceId] != NULL) { + ret = UsbReleaseInterface(dev->iface[interfaceId]); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: UsbReleaseInterface failed id = %{public}d ret:%{public}d", __func__, interfaceId, + ret); + return ret; + } + dev->iface[interfaceId] = NULL; + } + + return HDF_SUCCESS; +} + +static void UsbdReleaseInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return; + } + + for (int i = 0; i < USB_MAX_INTERFACES; ++i) { + if (dev->iface[i]) { + UsbReleaseInterface(dev->iface[i]); + dev->iface[i] = NULL; + } + } + if (dev->ctrIface) { + UsbReleaseInterface(dev->ctrIface); + dev->ctrIface = NULL; + } +} + +static int32_t UsbdClaimInterface(struct HostDevice *dev, uint8_t interfaceId) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (interfaceId >= USB_MAX_INTERFACES) { + return HDF_ERR_INVALID_PARAM; + } + + if (dev->iface[interfaceId] == NULL) { + dev->iface[interfaceId] = GetUsbInterfaceById((const struct HostDevice *)dev, interfaceId); + if (dev->iface[interfaceId] == NULL) { + HDF_LOGE( + "%{public}s:%{public}d UsbClaimInterface failed id = %{public}d, busNum=%{public}d, devAddr=%{public}d", + __func__, __LINE__, interfaceId, (int32_t)dev->busNum, (int32_t)dev->devAddr); + return HDF_FAILURE; + } + } + + if (dev->devHandle[interfaceId] == NULL) { + dev->devHandle[interfaceId] = UsbOpenInterface(dev->iface[interfaceId]); + if (dev->devHandle[interfaceId] == NULL) { + HDF_LOGE("%{public}s:%{public}d UsbOpenInterface failed id = %{public}d", __func__, __LINE__, interfaceId); + return HDF_FAILURE; + } + } + + return HDF_SUCCESS; +} + +static int32_t UsbdClaimInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + memset(dev->iface, 0, sizeof(struct UsbInterface *) * USB_MAX_INTERFACES); + + dev->ctrIface = GetUsbInterfaceById((const struct HostDevice *)dev, USB_CTRL_INTERFACE_ID); + if (dev->ctrIface == NULL) { + HDF_LOGE("%{public}s:%{public}d GetUsbInterfaceById null", __func__, __LINE__); + goto error; + } + + return HDF_SUCCESS; + +error: + UsbdReleaseInterfaces(dev); + return HDF_FAILURE; +} + +static void UsbdCloseInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return; + } + + for (int i = 0; i < USB_MAX_INTERFACES; ++i) { + if (dev->devHandle[i]) { + UsbCloseInterface(dev->devHandle[i]); + dev->devHandle[i] = NULL; + } + } + if (dev->ctrDevHandle) { + UsbCloseInterface(dev->ctrDevHandle); + dev->ctrDevHandle = NULL; + } +} + +static int32_t FunClaimInterface(struct HostDevice *port, struct HdfSBuf *data) +{ + if ((port == NULL) || (data == NULL)) { + HDF_LOGE("%{public}s:%{public}d invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + uint8_t interfaceId; + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d sbuf read interfaceNum failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + return UsbdClaimInterface(port, interfaceId); +} + +static int32_t FunReleaseInterface(struct HostDevice *port, struct HdfSBuf *data) +{ + if ((port == NULL) || (data == NULL)) { + HDF_LOGE("%{public}s:%{public}d invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + uint8_t interfaceId; + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d sbuf read interfaceNum failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s:%{public}d interfaceId:%{public}d", __func__, __LINE__, interfaceId); + return UsbdReleaseInterface(port, interfaceId); +} + +static int32_t UsbdOpenInterfaces(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + memset(dev->devHandle, 0, sizeof(UsbInterfaceHandle *) * USB_MAX_INTERFACES); + + HDF_LOGE("%{public}s:%{public}d UsbOpenInterface start", __func__, __LINE__); + dev->ctrDevHandle = UsbOpenInterface(dev->ctrIface); + HDF_LOGE("%{public}s:%{public}d UsbOpenInterface end", __func__, __LINE__); + if (dev->ctrDevHandle == NULL) { + HDF_LOGE("%{public}s:%{public}d ctrDevHandle UsbOpenInterface null", __func__, __LINE__); + goto error; + } + return HDF_SUCCESS; + +error: + UsbdCloseInterfaces(dev); + return HDF_FAILURE; +} +static int32_t FunGetDeviceDescriptor(struct HostDevice *port, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + length = USB_MAX_DESCRIPTOR_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (!buffer) { + HDF_LOGE("%{public}s:%{public}d malloc fail ", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_DESCRIPTOR, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, (int32_t)USB_DDK_DT_DEVICE << 8, 0, USB_CTRL_SET_TIMEOUT, + buffer, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed ret:%{public}d", __func__, __LINE__, ret); + goto out; + } + PrintBuffer("FunGetDeviceDescriptor", buffer, length); + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + } + +out: + if (buffer) + OsalMemFree(buffer); + return ret; +} + +static int32_t FunGetConfigDescriptor(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + uint8_t configId = 0; + + if ((port == NULL) || (reply == NULL) || (data == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &configId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + length = USB_MAX_DESCRIPTOR_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (!buffer) { + HDF_LOGE("%{public}s:%{public}d malloc fail ", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_DESCRIPTOR, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, ((int32_t)USB_DDK_DT_CONFIG << 8) + configId, 0, + USB_CTRL_SET_TIMEOUT, buffer, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + goto out; + } + PrintBuffer("FunGetConfigDescriptor", buffer, length); + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + } + +out: + if (buffer) + OsalMemFree(buffer); + return ret; +} + +static int32_t FunGetStringDescriptor(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t *buffer = NULL; + uint32_t length = 0; + uint8_t stringId = 0; + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &stringId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + length = USB_MAX_DESCRIPTOR_SIZE; + buffer = (uint8_t *)OsalMemAlloc(length); + if (!buffer) { + HDF_LOGE("%{public}s:%{public}d malloc fail ", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(buffer, 0, length); + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_DESCRIPTOR, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, ((int32_t)USB_DDK_DT_STRING << 8) + stringId, 0, + USB_CTRL_SET_TIMEOUT, buffer, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + goto out; + } + PrintBuffer("FunGetStringDescriptor", buffer, length); + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + } + +out: + if (buffer) + OsalMemFree(buffer); + return ret; +} + +static int32_t FunGetActiveConfig(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t configId = 0; + uint32_t length = 1; + + HDF_LOGE("%{public}s: mangf FunControlTransfer entry", __func__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, 0, 0, USB_CTRL_SET_TIMEOUT, &configId, &length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufWriteUint8(reply, configId)) { + ret = HDF_ERR_IO; + } + return ret; +} +static int32_t FunSetActiveConfig(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t configId = 0, configIdOld = 0, configIdNew = 0; + uint32_t length = 1; + + HDF_LOGE("%{public}s: mangf FunControlTransfer entry", __func__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &configId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + length = 1; + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, 0, 0, USB_CTRL_SET_TIMEOUT, &configIdOld, &length); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d config:%{public}d leng:%{public}d", __func__, __LINE__, ret, + configIdOld, length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d getConfiguration failed ret:%{public}d", __func__, __LINE__, ret); + return HDF_ERR_INVALID_PARAM; + } + if (configId == configIdOld) { + HDF_LOGE("%{public}s:%{public}d setConfiguration success configId:%{public}d old:%{public}d", __func__, + __LINE__, configId, configIdOld); + return HDF_SUCCESS; + } + length = 0; + ret = UsbControlTransfer(port, USB_DDK_REQ_SET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_TO_DEVICE, (int32_t)0 + configId, 0, USB_CTRL_SET_TIMEOUT, &configId, + &length); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d configId:%{public}d id2:%{public}d length:%{public}d", __func__, + __LINE__, ret, configId, configIdOld, length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d setConfiguration failed ret:%{public}d", __func__, __LINE__, ret); + return HDF_ERR_IO; + } + length = 1; + ret = UsbControlTransfer(port, USB_DDK_REQ_GET_CONFIGURATION, USB_REQUEST_TYPE_STANDARD, USB_REQUEST_TARGET_DEVICE, + USB_REQUEST_DIR_FROM_DEVICE, 0, 0, USB_CTRL_SET_TIMEOUT, &configIdNew, &length); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d config:%{public}d leng:%{public}d", __func__, __LINE__, ret, + configIdNew, length); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d getConfiguration failed ret:%{public}d", __func__, __LINE__, ret); + return HDF_ERR_IO; + } + if (configId != configIdNew) { + HDF_LOGE("%{public}s:%{public}d setConfiguration success configId:%{public}d new:%{public}d", __func__, + __LINE__, configId, configIdNew); + return HDF_ERR_NOT_SUPPORT; + } + if (configId != 0) { + uint8_t busNum = port->busNum; + uint8_t devAddr = port->devAddr; + UsbdRelease(port); + port->busNum = busNum; + port->devAddr = devAddr; + ret = UsbdInit(port); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbInit failed ret:%{public}d", __func__, __LINE__, ret); + UsbdRelease(port); + RemoveDevFromService(port->service, port); + OsalMemFree(port); + port = NULL; + return ret; + } + DataFifoReset(&port->readFifo); + + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen success", __func__, __LINE__); + OsalMSleep(OPEN_SLEPP_TIME); + } + return ret; +} + +static int32_t FunSetInterface(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, altIndex = 0; + uint32_t length = 0; + UsbInterfaceHandle *interfaceHandle = NULL; + + HDF_LOGE("%{public}s:%{public}d mangf FunControlTransfer entry", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &altIndex)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + + interfaceHandle = InterfaceIdToHandle(port, interfaceId); + if (interfaceHandle == NULL) { + HDF_LOGE( + "%{public}s:%{public}d InterfaceIdToHandle failed bus:%{public}d devAddr:%{public}d interfaceId:%{public}d", + __func__, __LINE__, port->busNum, port->devAddr, interfaceId); + return HDF_FAILURE; + } + + ret = UsbSelectInterfaceSetting(interfaceHandle, altIndex, &port->iface[interfaceId]); + HDF_LOGE("%{public}s:%{public}d ret:%{public}d ifId:%{public}d altIdx:%{public}d length:%{public}d", __func__, + __LINE__, ret, interfaceId, altIndex, length); + return ret; +} + +static int32_t FunBulkRead(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + struct UsbPipeInfo pipe; + struct RequestMsg *reqMsg = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + memset(&pipe, 0, sizeof(pipe)); + memset(&parmas, 0, sizeof(parmas)); + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s:%{public}d failed", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed", __func__); + return HDF_FAILURE; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (interfaceHandle == NULL) { + HDF_LOGE( + "%{public}s:%{public}d InterfaceIdToHandle failed bus:%{public}d devAddr:%{public}d interfaceId:%{public}d", + __func__, __LINE__, port->busNum, port->devAddr, pipe.interfaceId); + return HDF_FAILURE; + } + reqMsg = UsbdAllocRequestMsg(interfaceHandle, 0, pipe.maxPacketSize); + if (reqMsg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + parmas.userData = (void *)port; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.interfaceId = pipe.interfaceId; + parmas.callback = UsbdReadCallback; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + parmas.dataReq.length = pipe.maxPacketSize; + ret = UsbFillRequest(reqMsg->request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto error; + } + + OsalMutexLock(&port->requestLock); + struct UsbIfRequest *ifReq = (struct UsbIfRequest *)reqMsg->request; + struct UsbHostRequest *hostReq = (struct UsbHostRequest *)ifReq->hostRequest; + OsalSemInit(&hostReq->sem, 0); + ret = UsbSubmitRequestAsync(reqMsg->request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestAsync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMutexUnlock(&port->requestLock); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto error; + } + HdfSListAdd(&port->requestQueue, &reqMsg->node); + OsalMutexUnlock(&port->requestLock); + +error: + UsbdFreeRequestMsg(reqMsg); + return ret; +} + +static int32_t FunBulkWrite(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_FAILURE; + uint8_t interfaceId = 0, pipeId = 0; + int32_t timeout = 0; + uint32_t length = 0; + uint8_t *buffer = NULL; + struct UsbPipeInfo pipe; + struct RequestMsg *reqMsg = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + memset(&pipe, 0, sizeof(pipe)); + memset(&parmas, 0, sizeof(parmas)); + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed", __func__); + return HDF_FAILURE; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (interfaceHandle == NULL) { + return HDF_FAILURE; + } + reqMsg = UsbdAllocRequestMsg(interfaceHandle, 0, pipe.maxPacketSize); + if (reqMsg == NULL) { + return HDF_ERR_MALLOC_FAIL; + } + + parmas.userData = (void *)port; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.interfaceId = pipe.interfaceId; + parmas.callback = UsbdWriteCallback; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = timeout; + parmas.dataReq.numIsoPackets = 0; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + parmas.dataReq.length = length; + parmas.dataReq.buffer = buffer; + ret = UsbFillRequest(reqMsg->request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto error; + } + + OsalMutexLock(&port->requestLock); + struct UsbIfRequest *ifReq = (struct UsbIfRequest *)reqMsg->request; + struct UsbHostRequest *hostReq = (struct UsbHostRequest *)ifReq->hostRequest; + OsalSemInit(&hostReq->sem, 0); + ret = UsbSubmitRequestAsync(reqMsg->request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("UsbSubmitRequestAsync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMutexUnlock(&port->requestLock); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto error; + } + HdfSListAdd(&port->requestQueue, &reqMsg->node); + OsalMutexUnlock(&port->requestLock); + +error: + UsbdFreeRequestMsg(reqMsg); + return HDF_SUCCESS; +} + +static int32_t FunRequestQueue(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = 0; + struct UsbPipeInfo pipe; + struct RequestMsg *reqMsg = NULL; + struct UsbRequestParams parmas; + UsbInterfaceHandle *interfaceHandle = NULL; + uint8_t interfaceId = 0, pipeId = 0; + uint8_t *clientData = NULL, *buffer = NULL, *tclientData = NULL; + uint32_t clientLength = 0, length = 0; + bool bWrite = false; + int32_t requestCount = 0; + memset(&pipe, 0, sizeof(pipe)); + memset(&parmas, 0, sizeof(parmas)); + + if ((port == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &pipeId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadBuffer(data, (const void **)&tclientData, &clientLength)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadBuffer(data, (const void **)&buffer, &length)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + clientData = (uint8_t *)OsalMemAlloc(clientLength); + if (!clientData) { + HDF_LOGE("%{public}s:%{public}d OsalMemAlloc fail size:%{public}d", __func__, __LINE__, clientLength); + return HDF_ERR_MALLOC_FAIL; + } + memcpy(clientData, tclientData, clientLength); + + PrintBuffer("clientData", clientData, clientLength); + PrintBuffer("buffer", buffer, length); + ret = GetPipe(port, interfaceId, pipeId, &pipe); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s: get pipe info failed, interfaceId=%{public}d,pipeId=%{public}d pipeAddr:%{public}d", + __func__, interfaceId, pipeId, pipe.pipeAddress); + ret = HDF_FAILURE; + goto error1; + } + interfaceHandle = InterfaceIdToHandle(port, pipe.interfaceId); + if (interfaceHandle == NULL) { + ret = HDF_FAILURE; + goto error1; + } + reqMsg = UsbdAllocRequestMsg(interfaceHandle, 0, pipe.maxPacketSize); + if (reqMsg == NULL) { + ret = HDF_ERR_MALLOC_FAIL; + goto error1; + } + reqMsg->clientData = clientData; + reqMsg->clientLength = clientLength; + reqMsg->request->compInfo.status = -1; + bWrite = (pipe.pipeDirection == USB_PIPE_DIRECTION_OUT); + parmas.interfaceId = pipe.interfaceId; + parmas.pipeAddress = pipe.pipeDirection | pipe.pipeAddress; + parmas.pipeId = pipe.pipeId; + parmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + parmas.timeout = USB_CTRL_SET_TIMEOUT; + parmas.dataReq.numIsoPackets = 0; + parmas.userData = (void *)port; + parmas.dataReq.length = length; + HDF_LOGE( + "%{public}s: interfaceId=%{public}d,pipeId=%{public}d bwrite:%{public}d pipDriect:%{public}d " + "pipeAddr:%{public}d Addr:%{public}d", + __func__, interfaceId, pipeId, bWrite, pipe.pipeDirection, pipe.pipeAddress, parmas.pipeAddress); + if (bWrite) { + parmas.callback = UsbdWriteCallback; + parmas.dataReq.buffer = buffer; + } else { + parmas.callback = UsbdReadCallback; + parmas.dataReq.directon = (pipe.pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + } + ret = UsbFillRequest(reqMsg->request, interfaceHandle, &parmas); + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s: fumang UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + goto error; + } + HDF_LOGE( + "%{public}s: interfaceId=%{public}d,pipeId=%{public}d bwrite:%{public}d pipDriect:%{public}d pmdir:%{public}d ", + __func__, interfaceId, pipeId, bWrite, pipe.pipeDirection, parmas.dataReq.directon); + OsalMutexLock(&port->requestLock); + struct UsbIfRequest *ifReq = (struct UsbIfRequest *)reqMsg->request; + struct UsbHostRequest *hostReq = (struct UsbHostRequest *)ifReq->hostRequest; + OsalSemInit(&hostReq->sem, 0); + ret = UsbSubmitRequestAsync(reqMsg->request); + if (HDF_SUCCESS != ret) { + HDF_LOGE("fumang UsbSubmitRequestAsync faile, ret=%{public}d \n", ret); + ret = HDF_FAILURE; + OsalMutexUnlock(&port->requestLock); + OsalMSleep(SUBMIT_SLEEP_TIME); + goto error; + } + HdfSListAddTail(&port->requestQueue, &reqMsg->node); + requestCount = HdfSListCount(&port->requestQueue); + OsalMutexUnlock(&port->requestLock); + HDF_LOGE("%{public}s:%{public}d fumang send request %{public}p ok, count = %{public}d", __func__, __LINE__, reqMsg, + requestCount); + return HDF_SUCCESS; +error: + UsbdFreeRequestMsg(reqMsg); + return ret; +error1: + if (clientData) { + OsalMemFree(clientData); + clientData = NULL; + } + return ret; +} +static int32_t FunRequestWait(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_SUCCESS; + struct RequestMsg *reqMsg = NULL; + struct HdfSListNode *requestNode = NULL; + uint8_t *buffer = NULL; + uint32_t length = 0; + int32_t timeout = 0; + int32_t requestCount = 0; + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadInt32(data, &timeout)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s:%{public}d request wait entry ok timeout = %{public}d", __func__, __LINE__, timeout); + + OsalMutexLock(&port->requestLock); + if (!HdfSListIsEmpty(&port->requestQueue)) { + requestNode = HdfSListPop(&port->requestQueue); + requestCount = HdfSListCount(&port->requestQueue); + } + OsalMutexUnlock(&port->requestLock); + if (requestNode == NULL) { + HDF_LOGE("%{public}s:%{public}d fumang request node is null", __func__, __LINE__); + return HDF_FAILURE; + } + reqMsg = HDF_SLIST_CONTAINER_OF(struct HdfSListNode, requestNode, struct RequestMsg, node); + if (reqMsg == NULL) { + HDF_LOGE("%{public}s:%{public}d fumang request msg is null", __func__, __LINE__); + return HDF_FAILURE; + } + + HDF_LOGE("%{public}s:%{public}d fumang get request %{public}p ok, count=%{public}d status:%{public}d", __func__, + __LINE__, reqMsg, requestCount, reqMsg->request->compInfo.status); + + if ((int32_t)(reqMsg->request->compInfo.status) == -1) { + HDF_LOGE("%{public}s:%{public}d fumang request waitting... timeout:%{public}d", __func__, __LINE__, timeout); + ret = OsalSemWait(&((struct UsbIfRequest *)reqMsg->request)->hostRequest->sem, timeout); + HDF_LOGE("%{public}s:%{public}d wait over ret:%{public}d timeout:%{public}d status:%{public}d", __func__, + __LINE__, ret, timeout, reqMsg->request->compInfo.status); + ret = (int32_t)(reqMsg->request->compInfo.status); + if ((ret == USB_REQUEST_COMPLETED) || (USB_REQUEST_COMPLETED_SHORT == ret)) { + ret = HDF_SUCCESS; + } + if (HDF_SUCCESS != ret) { + HDF_LOGE("%{public}s:%{public}d fumang request wait failed ret = %{public}d", __func__, __LINE__, ret); + goto error; + } + } + + OsalMutexLock(&port->readLock); + length = DataFifoLen(&port->readFifo); + HDF_LOGE("%{public}s:%{public}d len:%{public}d", __func__, __LINE__, length); + if (length > 0) { + buffer = (uint8_t *)OsalMemCalloc(length + 1); + if (buffer == NULL) { + HDF_LOGE("%{public}s:%{public}d OsalMemCalloc error", __func__, __LINE__); + ret = HDF_ERR_MALLOC_FAIL; + OsalMutexUnlock(&port->readLock); + goto error; + } + memset(buffer, 0, length + 1); + length = DataFifoRead(&port->readFifo, buffer, length); + HDF_LOGE("%{public}s:%{public}d len:%{public}d", __func__, __LINE__, length); + } + OsalMutexUnlock(&port->readLock); + if (!HdfSbufWriteBuffer(reply, reqMsg->clientData, reqMsg->clientLength)) { + ret = HDF_ERR_IO; + HDF_LOGE("%{public}s:%{public}d fumang HdfSbufWriteBuffer failed", __func__, __LINE__); + goto out; + } + if (length > 0) { + if (!HdfSbufWriteBuffer(reply, buffer, length)) { + ret = HDF_ERR_IO; + HDF_LOGE("%{public}s:%{public}d fumang HdfSbufWriteBuffer failed", __func__, __LINE__); + goto out; + } + PrintBuffer("fumang request wait get data:", buffer, length); + } else { + if (!HdfSbufWriteUint32(reply, length)) { + ret = HDF_ERR_IO; + HDF_LOGE("%{public}s:%{public}d fumang HdfSbufWriteBuffer failed", __func__, __LINE__); + goto out; + } + } + HDF_LOGE("%{public}s:%{public}d fumang request wait success, buffer=%{public}p, length=%{public}d", __func__, + __LINE__, buffer, length); +out: + if (buffer) + OsalMemFree(buffer); +error: + UsbdFreeRequestMsg(reqMsg); + return ret; +} + +static int32_t FunRequestCancel(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t ret = HDF_SUCCESS; + struct RequestMsg *reqMsg = NULL; + struct HdfSListNode *requestNode = NULL; + uint8_t interfaceId = 0, endpointId = 0; + + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s: invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + if (!HdfSbufReadUint8(data, &interfaceId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (!HdfSbufReadUint8(data, &endpointId)) { + HDF_LOGE("%{public}s: mangf invalid parma", __func__); + return HDF_ERR_INVALID_PARAM; + } + + OsalMutexLock(&port->requestLock); + if (!HdfSListIsEmpty(&port->requestQueue)) { + requestNode = HdfSListPop(&port->requestQueue); + } + OsalMutexUnlock(&port->requestLock); + if (requestNode == NULL) { + HDF_LOGE("%{public}s:%{public}d request node is null", __func__, __LINE__); + return HDF_SUCCESS; + } + reqMsg = HDF_SLIST_CONTAINER_OF(struct HdfSListNode, requestNode, struct RequestMsg, node); + if (reqMsg == NULL) { + HDF_LOGE("%{public}s:%{public}d request msg is null", __func__, __LINE__); + return HDF_FAILURE; + } + ret = UsbCancelRequest(reqMsg->request); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d request cancel failed = %{public}d", __func__, __LINE__, ret); + } + OsalMSleep(SUBMIT_SLEEP_TIME); + UsbdFreeRequestMsg(reqMsg); + return ret; +} + +static int32_t UsbdInit(struct HostDevice *dev) +{ + int32_t ret = HDF_FAILURE; + struct UsbSession *session = NULL; + HDF_LOGE("%{public}s:%{public}d mangf UsbdInit", __func__, __LINE__); + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + HDF_LOGE("%{public}s:%{public}d mangf UsbdInit", __func__, __LINE__); + if (dev->initFlag == true) { + HDF_LOGE("%{public}s:%{public}d: mangf initFlag is true", __func__, __LINE__); + return HDF_SUCCESS; + } + HDF_LOGE("%{public}s:%{public}d mangf UsbdInit", __func__, __LINE__); + ret = UsbInitHostSdk(NULL); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbInitHostSdk faild", __func__, __LINE__); + return HDF_ERR_IO; + } + if (dev->service) + dev->service->session = session; + + HDF_LOGE("%{public}s:%{public}d UsbdClaimInterfaces start", __func__, __LINE__); + ret = UsbdClaimInterfaces(dev); + HDF_LOGE("%{public}s:%{public}d UsbdClaimInterfaces end ret:%{public}d", __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbdClaimInterfaces faild ret:%{public}d", __func__, __LINE__, ret); + goto error_claim_interfaces; + } + + HDF_LOGE("%{public}s:%{public}d UsbdOpenInterfaces start", __func__, __LINE__); + ret = UsbdOpenInterfaces(dev); + HDF_LOGE("%{public}s:%{public}d UsbdOpenInterfaces end ret:%{public}d", __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbdOpenInterfaces faild ret:%{public}d", __func__, __LINE__, ret); + goto error_open_interfaces; + } + + HDF_LOGE("%{public}s:%{public}d UsbdClaimInterfaces start", __func__, __LINE__); + ret = UsbdGetCtrlPipe(dev); + HDF_LOGE("%{public}s:%{public}d UsbdGetCtrlPipe end ret:%{public}d", __func__, __LINE__, ret); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbdGetPipes failed ret:%{public}d", __func__, __LINE__, ret); + goto error_get_pipes; + } + + dev->initFlag = true; + HDF_LOGD("%{public}s:%{public}d========OK busNum:%{public}d devAddr:%{public}d", __func__, __LINE__, dev->busNum, + dev->devAddr); + return HDF_SUCCESS; + +error_get_pipes: + UsbdCloseInterfaces(dev); +error_open_interfaces: + UsbdReleaseInterfaces(dev); +error_claim_interfaces: + UsbExitHostSdk(dev->service->session); + HDF_LOGD("%{public}s:%{public}d UsbExitHostSdk session:%{public}s ", __func__, __LINE__, + dev->service->session ? "OK" : "NULL"); + dev->service->session = NULL; + return ret; +} + +static void UsbdRelease(struct HostDevice *dev) +{ + if (dev == NULL) { + HDF_LOGE("%{public}s:%{public}d: invalid parma", __func__, __LINE__); + return; + } + + if (dev->initFlag == false) { + HDF_LOGE("%{public}s:%{public}d: initFlag is false", __func__, __LINE__); + return; + } + + UsbdFreeCtrlPipe(dev); + UsbdCloseInterfaces(dev); + UsbdReleaseInterfaces(dev); + UsbExitHostSdk(dev->service->session); + HDF_LOGD("%{public}s:%{public}d UsbExitHostSdk session:%{public}s ", __func__, __LINE__, + dev->service->session ? "OK" : "NULL"); + dev->service->session = NULL; + OsalMutexDestroy(&dev->writeLock); + OsalMutexDestroy(&dev->readLock); + OsalMutexDestroy(&dev->lock); + OsalMutexDestroy(&dev->requestLock); + dev->busNum = 0; + dev->devAddr = 0; + dev->initFlag = false; +} + +static int32_t FunOpenDevice(struct HostDevice *port, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int ret; + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen", __func__, __LINE__); + if ((port == NULL) || (data == NULL) || (reply == NULL)) { + HDF_LOGE("%{public}s:%{public}d mangf invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (port->initFlag) { + HDF_LOGE("%{public}s:%{public}d device is already on flag:%{public}d bus:%{public}d dev:%{public}d", __func__, + __LINE__, port->initFlag, port->busNum, port->devAddr); + return HDF_SUCCESS; + } + ret = UsbdInit(port); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbInit failed ret:%{public}d", __func__, __LINE__, ret); + goto err_init; + } + ret = UsbdAllocFifo(&port->readFifo, READ_BUF_SIZE); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d mangf UsbAllocFifo failed ret:%{public}d", __func__, __LINE__, ret); + ret = HDF_ERR_INVALID_PARAM; + goto err_fifo; + } + + HDF_LOGE("%{public}s:%{public}d mangf UsbOpen success", __func__, __LINE__); + OsalMSleep(OPEN_SLEPP_TIME); + return HDF_SUCCESS; + +err_fifo: + UsbdFreeFifo(&port->readFifo); +err_init: + UsbdRelease(port); + RemoveDevFromService(port->service, port); + OsalMemFree(port); + port = NULL; + return ret; +} + +static int32_t FunCloseDevice(struct HostDevice *port, struct HdfSBuf *data) +{ + if (port == NULL) { + HDF_LOGE("%{public}s:%{public}d invalid parma", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + if (!port->initFlag) { + HDF_LOGE("%{public}s:%{public}d device already close", __func__, __LINE__); + return HDF_SUCCESS; + } + UsbdFreeFifo(&port->readFifo); + UsbdRelease(port); + RemoveDevFromService(port->service, port); + OsalMemFree(port); + port = NULL; + return HDF_SUCCESS; +} + +static int32_t FunSetRole(struct HdfSBuf *data, struct HdfSBuf *reply, struct UsbdService *service) +{ + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + if (!HdfSbufReadInt32(data, &portId)) { + HDF_LOGE("%{public}s:%{public}d mangf Read data faild", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &powerRole)) { + HDF_LOGE("%{public}s:%{public}d mangf Read data faild", __func__, __LINE__); + return HDF_ERR_IO; + } + if (!HdfSbufReadInt32(data, &dataRole)) { + HDF_LOGE("%{public}s:%{public}d mangf Read data faild", __func__, __LINE__); + return HDF_ERR_IO; + } + + HDF_LOGE("%{public}s:%{public}d FunSetRole %{public}d %{public}d %{public}d", __func__, __LINE__, portId, powerRole, + dataRole); + int32_t ret = SetPort(portId, powerRole, dataRole, service); + if (ret) { + HDF_LOGE("%{public}s:%{public}d FunSetRole fasle", __func__, __LINE__); + return HDF_ERR_IO; + } + if (reply) + HdfSbufWriteInt32(reply, ret); + return HDF_SUCCESS; +} + +static int32_t FunQueryPort(struct HdfSBuf *data, struct HdfSBuf *reply, struct UsbdService *service) +{ + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + int32_t mode = 0; + int32_t ret = QueryPort(&portId, &powerRole, &dataRole, &mode, service); + if (ret) { + HDF_LOGE("%{public}s:%{public}d FunQueryPort fasle", __func__, __LINE__); + return HDF_ERR_IO; + } + if (reply) { + HdfSbufWriteInt32(reply, portId); + HdfSbufWriteInt32(reply, powerRole); + HdfSbufWriteInt32(reply, dataRole); + HdfSbufWriteInt32(reply, mode); + } + return HDF_SUCCESS; +} + +static int32_t FunGetCurrentFunctions(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t funcs = UsbdGetFunction(); + HDF_LOGE("%{public}s:%{public}d FunSetCurrentFunctions funcs: %{public}d", __func__, __LINE__, funcs); + if (reply) + HdfSbufWriteInt32(reply, funcs); + return HDF_SUCCESS; +} + +static int32_t FunSetCurrentFunctions(struct HdfSBuf *data, struct HdfSBuf *reply) +{ + int32_t funcs = 0; + HdfSbufReadInt32(data, &funcs); + HDF_LOGE("%{public}s:%{public}d FunSetCurrentFunctions funcs: %{public}d", __func__, __LINE__, funcs); + int ret = UsbdSetFunction(funcs); + if (ret) { + return HDF_ERR_IO; + } + return HDF_SUCCESS; +} + +static int32_t DispatchBindUsbSubscriber(struct UsbdService *service, struct HdfSBuf *data) +{ + struct UsbdSubscriber *subscriber = NULL; + HDF_LOGE("%{public}s:%{public}d fumang entry", __func__, __LINE__); + if (service == NULL || data == NULL) { + HDF_LOGW("%{public}s:%{public}d param is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + struct HdfRemoteService *remoteService = HdfSBufReadRemoteService(data); + if (remoteService == NULL) { + HDF_LOGW("%{public}s: remoteService is NULL", __func__); + return HDF_ERR_INVALID_PARAM; + } + + subscriber = (struct UsbdSubscriber *)OsalMemCalloc(sizeof(struct UsbdSubscriber)); + if (subscriber == NULL) { + HDF_LOGE("%{public}s: calloc subscriber error", __func__); + return HDF_ERR_MALLOC_FAIL; + } + memset(subscriber, 0, sizeof(struct UsbdSubscriber)); + subscriber->remoteService = remoteService; + return BindUsbSubscriber(service, subscriber); +} + +static int32_t DispatchUnbindUsbSubscriber(struct UsbdService *service) +{ + if (service == NULL) { + HDF_LOGW("%{public}s:%{public}d param is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_PARAM; + } + return UnbindUsbSubscriber(service); +} + +int32_t UsbdServiceDispatch(struct HdfDeviceIoClient *client, int cmd, struct HdfSBuf *data, struct HdfSBuf *reply) +{ + struct UsbdService *service = NULL; + struct HostDevice *port = NULL; + + if (client == NULL) { + HDF_LOGE("%{public}s:%{public}d client is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + if (client->device == NULL) { + HDF_LOGE("%{public}s:%{public}d client->device is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + if (client->device->service == NULL) { + HDF_LOGE("%{public}s:%{public}d client->device->service is NULL", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + + HDF_LOGE("%{public}s:%{public}d usbd dispatch cmd = %{public}d", __func__, __LINE__, cmd); + service = (struct UsbdService *)client->device->service; + if (cmd != CMD_FUN_GET_CURRENT_FUNCTIONS && cmd != CMD_FUN_SET_CURRENT_FUNCTIONS && cmd != CMD_SET_ROLE && + cmd != CMD_QUERY_PORT && CMD_BIND_USB_SUBSCRIBER != cmd && CMD_UNBIND_USB_SUBSCRIBER != cmd) { + uint8_t busNum = 0; + uint8_t devAddr = 0; + int32_t ret = 0; + ret = ParseDeviceBuf(data, &busNum, &devAddr); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d cmd = %{public}d ParseDeviceBuf error:%{public}d", __func__, __LINE__, cmd, + ret); + return ret; + } + port = FindDevFromService(service, busNum, devAddr); + switch (cmd) { + case CMD_FUN_OPEN_DEVICE: + if (!port) { + ret = HostDeviceCreate(&port); + HDF_LOGE( + "%{public}s:%{public}d OpenDevice create ret:%{public}d busNum:%{public}d devAddr:%{public}d " + "port:%{public}p", + __func__, __LINE__, ret, busNum, devAddr, port); + if ((HDF_SUCCESS == ret) && (port)) { + port->service = service; + port->busNum = busNum; + port->devAddr = devAddr; + OsalMutexLock(&service->lock); + HdfSListAdd(&service->devList, &port->node); + OsalMutexUnlock(&service->lock); + } else { + return ret; + } + } + break; + default: + if (!port) { + HDF_LOGE("%{public}s:%{public}d cmd = %{public}d busNum:%{public}d devAddr:%{public}d no device", + __func__, __LINE__, cmd, busNum, devAddr); + return HDF_DEV_ERR_NO_DEVICE; + } + break; + } + } + HDF_LOGE("%{public}s:%{public}d cmd = %{public}d port:%{public}p", __func__, __LINE__, cmd, port); + switch (cmd) { + case CMD_BIND_USB_SUBSCRIBER: + return DispatchBindUsbSubscriber(service, data); + case CMD_UNBIND_USB_SUBSCRIBER: + return DispatchUnbindUsbSubscriber(service); + case CMD_FUN_OPEN_DEVICE: + return FunOpenDevice(port, data, reply); + case CMD_FUN_CLOSE_DEVICE: + return FunCloseDevice(port, data); + case CMD_FUN_SEND_BULK_READ_ASYNC: + return FunBulkRead(port, data, reply); + case CMD_FUN_SEND_BULK_WRITE_ASYNC: + return FunBulkWrite(port, data, reply); + case CMD_FUN_SEND_BULK_READ_SYNC: + case CMD_FUN_SEND_INTERRUPT_READ_SYNC: + case CMD_FUN_SEND_ISO_READ_SYNC: + return FunBulkReadSync(port, data, reply); + case CMD_FUN_SEND_BULK_WRITE_SYNC: + case CMD_FUN_SEND_INTERRUPT_WRITE_SYNC: + case CMD_FUN_SEND_ISO_WRITE_SYNC: + return FunBulkWriteSync(port, data, reply); + case CMD_FUN_SEND_CTRL_REQUEST_SYNC: + return FunControlTransfer(port, data, reply); + case CMD_FUN_GET_DEVICE_DESCRIPTOR: + return FunGetDeviceDescriptor(port, reply); + case CMD_FUN_GET_CONFIG_DESCRIPTOR: + return FunGetConfigDescriptor(port, data, reply); + case CMD_FUN_GET_STRING_DESCRIPTOR: + return FunGetStringDescriptor(port, data, reply); + case CMD_FUN_REQUEST_QUEUE: + return FunRequestQueue(port, data, reply); + case CMD_FUN_REQUEST_WAIT: + return FunRequestWait(port, data, reply); + case CMD_FUN_REQUEST_CANCEL: + return FunRequestCancel(port, data, reply); + case CMD_FUN_CLAIM_INTERFACE: + return FunClaimInterface(port, data); + case CMD_FUN_RELEASE_INTERFACE: + return FunReleaseInterface(port, data); + case CMD_FUN_SET_CONFIG: + return FunSetActiveConfig(port, data, reply); + case CMD_FUN_GET_CONFIG: + return FunGetActiveConfig(port, data, reply); + case CMD_FUN_SET_INTERFACE: + return FunSetInterface(port, data, reply); + case CMD_SET_ROLE: + return FunSetRole(data, reply, service); + case CMD_QUERY_PORT: + return FunQueryPort(data, reply, service); + case CMD_FUN_GET_CURRENT_FUNCTIONS: + return FunGetCurrentFunctions(data, reply); + case CMD_FUN_SET_CURRENT_FUNCTIONS: + return FunSetCurrentFunctions(data, reply); + default: + return HDF_ERR_NOT_SUPPORT; + } + return HDF_SUCCESS; +} + +static int32_t HostDeviceInit(struct HostDevice *port) +{ + if (!port) { + HDF_LOGE("%{public}s:%{public}d param failed", __func__, __LINE__); + return HDF_ERR_INVALID_OBJECT; + } + port->busNum = 0; + port->devAddr = 0; + port->initFlag = false; + port->interfaceCnt = 0; + + if (OsalMutexInit(&port->lock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + if (OsalMutexInit(&port->requestLock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + if (OsalMutexInit(&port->writeLock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + if (OsalMutexInit(&port->readLock) != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d init lock fail!", __func__, __LINE__); + return HDF_FAILURE; + } + HdfSListInit(&port->requestQueue); + return HDF_SUCCESS; +} + +int32_t HostDeviceCreate(struct HostDevice **port) +{ + int32_t ret = HDF_SUCCESS; + struct HostDevice *tmp = NULL; + if (!port) { + return HDF_FAILURE; + } + tmp = (struct HostDevice *)OsalMemCalloc(sizeof(struct HostDevice)); + if (!tmp) { + HDF_LOGE("%{public}s:%{public}d Alloc usb host device failed", __func__, __LINE__); + return HDF_ERR_MALLOC_FAIL; + } + memset(tmp, 0, sizeof(struct HostDevice)); + + ret = HostDeviceInit(tmp); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s:%{public}d HostDeviceInit fail!", __func__, __LINE__); + goto out; + } + + tmp->initFlag = false; + *port = tmp; + return HDF_SUCCESS; +out: + OsalMemFree(tmp); + return ret; +} + +int32_t UsbdRealseDevices(struct UsbdService *service) +{ + if (!service) { + return HDF_ERR_INVALID_PARAM; + } + OsalMutexLock(&service->lock); + while (!HdfSListIsEmpty(&service->devList)) { + struct HostDevice *port = (struct HostDevice *)HdfSListPop(&service->devList); + if (port) { + UsbdRelease(port); + OsalMemFree(port); + } + } + OsalMutexUnlock(&service->lock); + return HDF_SUCCESS; +} + +static struct HostDevice *FindDevFromService(struct UsbdService *service, uint8_t busNum, uint8_t devAddr) +{ + struct HdfSListIterator it; + struct HostDevice *port = NULL; + bool flag = false; + if (!service) { + return NULL; + } + + OsalMutexLock(&service->lock); + HdfSListIteratorInit(&it, &service->devList); + while (HdfSListIteratorHasNext(&it)) { + port = (struct HostDevice *)HdfSListIteratorNext(&it); + if (!port) { + continue; + } + if ((port->busNum == busNum) && (port->devAddr == devAddr)) { + flag = true; + break; + } + } + OsalMutexUnlock(&service->lock); + if (!flag) { + return NULL; + } + return port; +} + +static int32_t RemoveDevFromService(struct UsbdService *service, struct HostDevice *port) +{ + struct HdfSListIterator it; + struct HostDevice *tport = NULL; + if (!service || !port) { + return HDF_SUCCESS; + } + + OsalMutexLock(&service->lock); + HdfSListIteratorInit(&it, &service->devList); + while (HdfSListIteratorHasNext(&it)) { + tport = (struct HostDevice *)HdfSListIteratorNext(&it); + if (!tport) { + continue; + } + if ((tport->busNum == port->busNum) && (tport->devAddr == port->devAddr)) { + HdfSListIteratorRemove(&it); + break; + } + } + OsalMutexUnlock(&service->lock); + + return HDF_SUCCESS; +} diff --git a/hdi/service/src/usbd_function.c b/hdi/service/src/usbd_function.c new file mode 100644 index 00000000..0797af91 --- /dev/null +++ b/hdi/service/src/usbd_function.c @@ -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. + */ +#include "usbd_function.h" + +#include +#include +#include +#include +#include +#include +#include "devmgr_hdi.h" +#include "hdf_log.h" +#include "hdf_remote_service.h" +#include "osal_time.h" +#include "securec.h" +#include "sys_param.h" + +#define DEV_SERVICE_NAME "usbfn_master" +#define ACM_SERVICE_NAME "usbfn_cdcacm" +#define ECM_SERVICE_NAME "usbfn_cdcecm" + +#define SYS_USB_FFS_READY "sys.usb.ffs.ready" +#define SYS_USB_CONFIGFS "sys.usb.configfs" +#define SYS_USB_CONFIG "sys.usb.config" +#define HDC_CONFIG_OFF "none" +#define HDC_CONFIG_ON "hdc" +#define HDC_CONFIGFS_OFF "0" +#define HDC_CONFIGFS_ON "1" + +#define FUNCTION_ADD 1 +#define FUNCTION_DEL 2 + +#define USB_INIT 100 +#define USB_RELEASE 101 +#define USB_ACM_OPEN 0 +#define USB_ACM_CLOSE 1 + +#define USB_FUNCTION_ACM 1 +#define USB_FUNCTION_ECM 2 +#define USB_FUNCTION_ACM_ECM 3 +#define USB_FUNCTION_HDC 4 +#define FUNCTIONS_MAX 7 + +static uint8_t currentFuncs = USB_FUNCTION_HDC; +static uint8_t pre_acm_ecm; + +static int send_cmd_to_service(const char *name, int cmd, unsigned char funcMask) +{ + int status; + struct HdfRemoteService *service; + struct HdfSBuf *data = NULL; + struct HdfSBuf *reply = NULL; + struct HDIServiceManager *servmgr = HDIServiceManagerGet(); + if (servmgr == NULL) { + printf("HDIServiceManagerGet err\n"); + return HDF_FAILURE; + } + service = servmgr->GetService(servmgr, name); + HDIServiceManagerRelease(servmgr); + if (service == NULL) { + printf("GetService err\n"); + return HDF_FAILURE; + } + + data = HdfSBufTypedObtain(SBUF_IPC); + reply = HdfSBufTypedObtain(SBUF_IPC); + if (data == NULL || reply == NULL) { + printf("data or reply err\n"); + status = HDF_FAILURE; + goto error; + } + if (!HdfSbufWriteInt8(data, funcMask)) { + printf("UsbEcmRead HdfSbufWriteInt8 error"); + status = HDF_FAILURE; + goto error_sbuf; + } + status = service->dispatcher->Dispatch(service, cmd, data, reply); + if (status) { + printf("serice %s dispatch cmd : %d error\n", name, cmd); + } +error_sbuf: + HdfSBufRecycle(data); + HdfSBufRecycle(reply); +error: + HdfRemoteServiceRecycle(service); + return status; +} + +// 1. 先卸载(acm/ecm, hdc) 2.再加载 +int UsbdSetFunction(int funcs) +{ + uint8_t _acm_ecm = funcs & USB_FUNCTION_ACM_ECM; + uint8_t status; + if (funcs < 0 || funcs > FUNCTIONS_MAX) { + HDF_LOGI("%{public}s:%{public}d funcs invalid \n", __func__, __LINE__); + goto err; + } + // HDC + if ((currentFuncs & USB_FUNCTION_HDC) || (funcs == 0)) { + if (!(funcs & USB_FUNCTION_HDC)) { + if (currentFuncs != funcs) { + HDF_LOGI("%{public}s:%{public}d remove hdc\n", __func__, __LINE__); + status = SystemSetParameter(SYS_USB_CONFIG, HDC_CONFIG_OFF); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove hdc config error = %{public}d\n", __func__, __LINE__, + status); + goto err; + } + status = SystemSetParameter(SYS_USB_CONFIGFS, HDC_CONFIGFS_OFF); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove hdc configs error = %{public}d\n", __func__, __LINE__, + status); + goto err; + } + } + } + } else { + if (funcs & USB_FUNCTION_HDC) { + HDF_LOGI("%{public}s:%{public}d add hdc\n", __func__, __LINE__); + status = SystemSetParameter(SYS_USB_CONFIGFS, HDC_CONFIGFS_ON); + if (status) { + HDF_LOGE("%{public}s:%{public}d add hdc configfs error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + status = SystemSetParameter(SYS_USB_CONFIG, HDC_CONFIG_ON); + if (status) { + HDF_LOGE("%{public}s:%{public}d add hdc config error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + } + + // acm_ecm + if (pre_acm_ecm != _acm_ecm) { + if ((pre_acm_ecm > 0) || (funcs == 0)) { + HDF_LOGI("%{public}s:%{public}d remove pre_acm_ecm = %{public}d \n", __func__, __LINE__, pre_acm_ecm); + if (pre_acm_ecm & USB_FUNCTION_ACM) { + status = send_cmd_to_service(ACM_SERVICE_NAME, USB_RELEASE, pre_acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d release acm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + if (pre_acm_ecm & USB_FUNCTION_ECM) { + status = send_cmd_to_service(ECM_SERVICE_NAME, USB_RELEASE, pre_acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d release ecm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + status = send_cmd_to_service(DEV_SERVICE_NAME, FUNCTION_DEL, pre_acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove device error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + if (_acm_ecm > 0) { + HDF_LOGI("%{public}s:%{public}d add _acm_ecm = %{public}d\n", __func__, __LINE__, _acm_ecm); + status = send_cmd_to_service(DEV_SERVICE_NAME, FUNCTION_ADD, _acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d add device _acm_ecm:%{public}d error = %{public}d\n", __func__, + __LINE__, _acm_ecm, status); + goto err; + } + if (_acm_ecm & USB_FUNCTION_ACM) { + status = send_cmd_to_service(ACM_SERVICE_NAME, USB_INIT, _acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove acm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + if (_acm_ecm & USB_FUNCTION_ECM) { + status = send_cmd_to_service(ECM_SERVICE_NAME, USB_INIT, _acm_ecm); + if (status) { + HDF_LOGE("%{public}s:%{public}d remove ecm error = %{public}d\n", __func__, __LINE__, status); + goto err; + } + } + } + } + + currentFuncs = funcs; + pre_acm_ecm = _acm_ecm; + return HDF_SUCCESS; + +err: + return HDF_FAILURE; +} + +int32_t UsbdGetFunction() +{ + HDF_LOGI("%{public}s:%{public}d currentFuncs:%{public}d\n", __func__, __LINE__, currentFuncs); + return currentFuncs; +} diff --git a/hdi/service/src/usbd_port.c b/hdi/service/src/usbd_port.c new file mode 100644 index 00000000..1122c345 --- /dev/null +++ b/hdi/service/src/usbd_port.c @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_port.h" +#include "usbd_function.h" +#include "usbd_publisher.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "hdf_log.h" +#include "osal_time.h" +#include "securec.h" +#include "sys_param.h" + +#define PORT_MODE_NONE_STR "none" +#define PORT_MODE_HOST_STR "host" +#define PORT_MODE_DEVICE_STR "device" +#define PORT_MODE_OTG_STR "otg" + +#define DEFAULT_PORT_ID 1 + +#define POWER_ROLE_NONE 0 +#define POWER_ROLE_SOURCE 1 +#define POWER_ROLE_SINK 2 + +#define DATA_ROLE_NONE 0 +#define DATA_ROLE_HOST 1 +#define DATA_ROLE_DEVICE 2 + +#define PORT_MODE_NONE 0 +#define PORT_MODE_HOST 1 +#define PORT_MODE_DEVICE 2 + +#define SYS_USB_PORT "sys.usb.port" +#define SYS_USB_FFS_READY "sys.usb.ffs.ready" +#define SYS_USB_CONFIGFS "sys.usb.configfs" +#define SYS_USB_CONFIG "sys.usb.config" +#define HDC_CONFIG_OFF "none" +#define HDC_CONFIG_ON "hdc" + +static int32_t currentPortId = 1; +static int32_t currentPowerRole = 1; +static int32_t currentDataRole = 1; +static int32_t currentMode = 1; + +int SetPort(int portId, int powerRole, int dataRole, struct UsbdService *service) +{ + HDF_LOGE("%{public}s: portId:%{public}d,powerRole:%{public}d,dataRole:%{public}d start", __func__, portId, + powerRole, dataRole); + int ret = 0; + char *fn = "/sys/kernel/debug/usb/100e0000.hidwc3_0/mode"; + int fd = -1; + int len = 0; + int mode = 0; + char *mode_str = NULL; + if (portId != DEFAULT_PORT_ID) { + return -1; + } + if (powerRole < 1 || powerRole >= 3) { + return -1; + } + if (dataRole < 1 || dataRole >= 3) { + return -1; + } + if (powerRole == POWER_ROLE_SOURCE && dataRole == DATA_ROLE_HOST) { + mode = PORT_MODE_HOST; + } + if (powerRole == POWER_ROLE_SINK && dataRole == DATA_ROLE_DEVICE) { + mode = PORT_MODE_DEVICE; + } + if (mode == PORT_MODE_HOST || mode == PORT_MODE_DEVICE) { + switch (mode) { + case PORT_MODE_HOST: + mode_str = PORT_MODE_HOST_STR; + break; + case PORT_MODE_DEVICE: + mode_str = PORT_MODE_DEVICE_STR; + break; + default: + mode_str = PORT_MODE_NONE; + break; + } + } + HDF_LOGE("%{public}s: mode = %{public}d, start", __func__, mode); + if (!mode_str) { + return -1; + } + len = strlen(mode_str); + fd = open(fn, O_WRONLY | O_TRUNC); + if (fd < 0) { + HDF_LOGE("%{public}s: file open error fd= %{public}d", __func__, fd); + return -1; + } + // otg host device + ret = write(fd, mode_str, len); + HDF_LOGE("%{public}s: set mode=%{public}d result:%{public}d len:%{pulibic}d", __func__, mode, ret, len); + if (ret == len) { + ret = 0; + currentPortId = portId; + currentPowerRole = powerRole; + currentDataRole = dataRole; + currentMode = mode; + NotifyUsbPortSubscriber(service->subscriber, currentPortId, currentPowerRole, currentDataRole, currentMode); + } else { + ret = -1; + } + close(fd); + HDF_LOGE("%{public}s: set mode end", __func__); + return 0; +} +static int SetDefaultPort(struct UsbdService *service) +{ + return SetPort(DEFAULT_PORT_ID, POWER_ROLE_SINK, DATA_ROLE_DEVICE, service); +} + +int QueryPort(int *portId, int *powerRole, int *dataRole, int *mode, struct UsbdService *service) +{ + int ret = SetDefaultPort(service); + if (ret) { + return -1; + } + sleep(1); + *portId = currentPortId; + *powerRole = currentPowerRole; + *dataRole = currentDataRole; + *mode = currentMode; + return 0; +} diff --git a/hdi/service/src/usbd_publisher.c b/hdi/service/src/usbd_publisher.c new file mode 100644 index 00000000..a5e589d0 --- /dev/null +++ b/hdi/service/src/usbd_publisher.c @@ -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 "usbd_publisher.h" + +#include "hdf_remote_service.h" +#include "utils/hdf_log.h" + +#define HDF_LOG_TAG usbd_publisher + +void NotifySubscriberDevice(const struct UsbdSubscriber *subscriber, + enum UsbdDeviceAction act, + int32_t busNum, + int32_t devNum) +{ + HDF_LOGD("%{public}s: enter subscriber:%{public}s act:%{public}d bus:%{public}d dev:%{public}d", __func__, + subscriber ? "OK" : "NULL", act, busNum, devNum); + if (subscriber == NULL) { + HDF_LOGD("%{public}s: subscriber is NULL", __func__); + return; + } + int ret; + struct HdfRemoteService *service = subscriber->remoteService; + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC); + struct HdfSBuf *reply = HdfSBufTypedObtain(SBUF_IPC); + if (data == NULL || reply == NULL) { + HDF_LOGE("%{public}s failed to obtain hdf sbuf", __func__); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return; + } + HdfSbufWriteInt32(data, act); + HdfSbufWriteInt32(data, busNum); + HdfSbufWriteInt32(data, devNum); + ret = service->dispatcher->Dispatch(service, CMD_NOTIFY_SUBSCRIBER_DEVICE_EVENT, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s failed to notify subscriber, ret: %{public}d", __func__, ret); + } else { + HDF_LOGD("%{public}s: succeed to notify subscriber", __func__); + } + HdfSBufRecycle(data); + HdfSBufRecycle(reply); +} + +void NotifyUsbPortSubscriber(const struct UsbdSubscriber *subscriber, + int32_t portId, + int32_t powerRole, + int32_t dataRole, + int32_t mode) +{ + HDF_LOGD("%{public}s: enter", __func__); + if (subscriber == NULL) { + HDF_LOGD("%{public}s: subscriber is NULL", __func__); + return; + } + int ret; + struct HdfRemoteService *service = subscriber->remoteService; + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC); + struct HdfSBuf *reply = HdfSBufTypedObtain(SBUF_IPC); + if (data == NULL || reply == NULL) { + HDF_LOGE("%{public}s failed to obtain hdf sbuf", __func__); + HdfSBufRecycle(data); + HdfSBufRecycle(reply); + return; + } + HdfSbufWriteInt32(data, portId); + HdfSbufWriteInt32(data, powerRole); + HdfSbufWriteInt32(data, dataRole); + HdfSbufWriteInt32(data, mode); + + ret = service->dispatcher->Dispatch(service, CMD_NOTIFY_PORT_CHANGED, data, reply); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%{public}s failed to notify subscriber, ret: %{public}d", __func__, ret); + } else { + HDF_LOGD("%{public}s: succeed to notify subscriber", __func__); + } + HdfSBufRecycle(data); + HdfSBufRecycle(reply); +} diff --git a/hdi/test/BUILD.gn b/hdi/test/BUILD.gn new file mode 100644 index 00000000..e3c24a7b --- /dev/null +++ b/hdi/test/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +#################################group######################################### +group("usbd_client_unittest") { + testonly = true + deps = [ "unittest/common:unittest", ] + +} +############################################################################### \ No newline at end of file diff --git a/hdi/test/unittest/common/BUILD.gn b/hdi/test/unittest/common/BUILD.gn new file mode 100644 index 00000000..41444c24 --- /dev/null +++ b/hdi/test/unittest/common/BUILD.gn @@ -0,0 +1,294 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +module_output_path = "usb_manager_native/usbd_client_test" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//base/usb/usb_manager/hdi/client/include", + ] +} + +##############################unittest##########################################= + +ohos_unittest("test_config") { + module_out_path = module_output_path + sources = [ + "src/usbd_config_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_transfer") { + module_out_path = module_output_path + sources = [ + "src/usbd_transfer_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_descriptor") { + module_out_path = module_output_path + sources = [ + "src/usbd_descriptor_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_device") { + module_out_path = module_output_path + sources = [ + "src/usbd_device_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_function") { + module_out_path = module_output_path + sources = [ + "src/usbd_function_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_interface") { + module_out_path = module_output_path + sources = [ + "src/usbd_interface_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_port") { + module_out_path = module_output_path + sources = [ + "src/usbd_port_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_request") { + module_out_path = module_output_path + sources = [ + "src/usbd_request_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +############################################################################### +group("unittest") { + testonly = true + deps = [ + ":test_config", + ":test_descriptor", + ":test_device", + ":test_function", + ":test_interface", + ":test_port", + ":test_request", + ":test_transfer", + ] +} +############################################################################### \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_config_test.h b/hdi/test/unittest/common/include/usbd_config_test.h new file mode 100644 index 00000000..08e8a996 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_config_test.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 USBD_CONFIG_TEST_H +#define USBD_CONFIG_TEST_H + +#include + +class UsbdConfigTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_CONFIG_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_descriptor_test.h b/hdi/test/unittest/common/include/usbd_descriptor_test.h new file mode 100644 index 00000000..55a0e59e --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_descriptor_test.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 USBD_DESCRIPTOR_TEST_H +#define USBD_DESCRIPTOR_TEST_H + +#include + +class UsbdDescriptorTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_DESCRIPTOR_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_device_test.h b/hdi/test/unittest/common/include/usbd_device_test.h new file mode 100644 index 00000000..3418d0d8 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_device_test.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 USBD_DEVICE_TEST_H +#define USBD_DEVICE_TEST_H + +#include + +class UsbdDeviceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_DEVICE_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_function_test.h b/hdi/test/unittest/common/include/usbd_function_test.h new file mode 100644 index 00000000..97e460b8 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_function_test.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 USBD_FUNCTION_TEST_H +#define USBD_FUNCTION_TEST_H + +#include + +class UsbdFunctionTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_FUNCTION_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_interface_test.h b/hdi/test/unittest/common/include/usbd_interface_test.h new file mode 100644 index 00000000..e0fbd8ff --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_interface_test.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 USBD_INTERFACE_TEST_H +#define USBD_INTERFACE_TEST_H + +#include + +class UsbdInterfaceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_INTERFACE_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_port_test.h b/hdi/test/unittest/common/include/usbd_port_test.h new file mode 100644 index 00000000..9ac29dfc --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_port_test.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 USBD_PORT_TEST_H +#define USBD_PORT_TEST_H + +#include + +class UsbdPortTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_PORT_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_request_test.h b/hdi/test/unittest/common/include/usbd_request_test.h new file mode 100644 index 00000000..f20324c6 --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_request_test.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 USBD_REQUEST_TEST_H +#define USBD_REQUEST_TEST_H + +#include + +class UsbdRequestTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_REQUEST_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/include/usbd_transfer_test.h b/hdi/test/unittest/common/include/usbd_transfer_test.h new file mode 100644 index 00000000..3947520f --- /dev/null +++ b/hdi/test/unittest/common/include/usbd_transfer_test.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 USBD_TRANSFER_TEST_H +#define USBD_TRANSFER_TEST_H + +#include + +class UsbdTransferTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif // USBD_TRANSFER_TEST_H \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_config_test.cpp b/hdi/test/unittest/common/src/usbd_config_test.cpp new file mode 100644 index 00000000..795fba6b --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_config_test.cpp @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_config_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +UsbDevice device; +void UsbdConfigTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdConfigTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d GetDevices=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d GetBusNum=%{public}d GetDevAddr=%{public}d", __LINE__, + device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + USBDevicePipe pipe; + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d GetBusNum=%{public}d GetDevAddr=%{public}d", __LINE__, + pipe.GetBusNum(), pipe.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdConfigTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdConfigTest-----------"); +} + +void UsbdConfigTest::SetUp(void) {} + +void UsbdConfigTest::TearDown(void) {} + +/** + * @tc.name: UsbdConfig001 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig001 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdConfigTest::UsbdSetConfigConfig001 %{public}d GetBusNum=%{public}d GetDevAddr=%{public}d", __LINE__, + device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfigConfig001 %{public}d config.GetId=%{public}d", + __LINE__, configIndex); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfigConfig001 %{public}d SetConfig=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig001 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig002 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetConfig002 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig002 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig002 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig003 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig003 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig003 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig003 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig004 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig004 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig004 %{public}d SetConfig=%{public}d", __LINE__, ret); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig004 %{public}d configIndex=%{public}d", __LINE__, + configIndex); + ASSERT_TRUE(ret == ERR_OK); + configIndex = device.GetConfigs().front().GetId(); + ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig004 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig005 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig005 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig005 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig005 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig006 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig006 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig006 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig006 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig007 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:devAddr、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig007 : SetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig007 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig007 : SetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig008 + * @tc.desc: Test functions to SetConfig + * @tc.desc: int32_t SetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:busNum、devAddr、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdSetConfig008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig008 : SetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configIndex = 222; + auto ret = UsbdClient::SetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdSetConfig008 %{public}d SetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig008 : SetConfig-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdConfig011 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig001 : GetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig001 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig001 : GetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig012 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig002 : GetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig002 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig002 : GetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig013 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig003 : GetConfig-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig003 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig003 : GetConfig-----------"); +} + +/** + * @tc.name: UsbdConfig014 + * @tc.desc: Test functions to GetConfig + * @tc.desc: int32_t GetConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdConfigTest, UsbdGetConfig004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdConfig004 : GetConfig-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configIndex = device.GetConfigs().front().GetId(); + auto ret = UsbdClient::GetConfig(busNum, devAddr, configIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdGetConfig004 %{public}d GetConfig=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdConfig004 : GetConfig-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_descriptor_test.cpp b/hdi/test/unittest/common/src/usbd_descriptor_test.cpp new file mode 100644 index 00000000..1b6c3676 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_descriptor_test.cpp @@ -0,0 +1,680 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_descriptor_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +UsbDevice device; +void UsbdDescriptorTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdDescriptorTest-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "device list NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + USBDevicePipe pipe; + device = deviceList.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdDescriptorTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdDescriptorTest-----------"); +} + +void UsbdDescriptorTest::SetUp(void) {} + +void UsbdDescriptorTest::TearDown(void) {} + +/** + * @tc.name: UsbdDescriptor001 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor001 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor001 %{public}d ret=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor001 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("设备描述符", buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor001 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor002 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor002 : GetDeviceDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor002 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor002 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor003 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor003 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 233; + uint8_t buffer[255] = {}; + uint32_t length = 255; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor003 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor003 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor004 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor004 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor004 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("设备描述符", buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor004 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor005 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor005 : GetDeviceDescriptor-----------"); + uint8_t busNum = 99; + uint8_t devAddr = 99; + uint8_t buffer[255] = {}; + uint32_t length = 255; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor005 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor005 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor006 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:参数异常,busNum、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor006 : GetDeviceDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor006 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor006 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor007 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor007 : GetDeviceDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t buffer[] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor007 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor007 : GetDeviceDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor008 + * @tc.desc: Test functions to GetDeviceDescriptor + * @tc.desc: int32_t GetDeviceDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) + * @tc.desc: 反向测试:busNum、devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetDeviceDescriptor008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor008 : GetDeviceDescriptor-----------"); + uint8_t busNum = 233; + uint8_t devAddr = 234; + uint8_t buffer[] = {}; + uint32_t length = 0; + auto ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetDeviceDescriptor008 %{public}d busNum=%{public}d devAddr=%{public}d", + __LINE__, busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetDeviceDescriptor008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor008 : GetDeviceDescriptor-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdDescriptor001 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor001 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 0; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor001 %{public}d ret=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor001 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor001 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor002 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor002 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor002 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor002 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor003 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor003 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 222; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor003 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor003 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor004 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor004 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor004 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("字符串描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor004 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor005 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor005 : GetStringDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor005 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor005 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor006 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor006 : GetStringDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t stringId = 1; + uint8_t buffer[255] = {0}; + uint32_t length = 0; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor006 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor006 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor007 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor007 : GetStringDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t stringId = 233; + uint8_t buffer[255] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor007 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor007 : GetStringDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor008 + * @tc.desc: Test functions to GetStringDescriptor + * @tc.desc: int32_t GetStringDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:busNum、devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetStringDescriptor008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor008 : GetStringDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t stringId = 222; + uint8_t buffer[10] = {0}; + uint32_t length = 255; + struct DescriptorParams descparams = {stringId, buffer, length}; + auto ret = UsbdClient::GetStringDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetStringDescriptor008 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetStringDescriptor008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor008 : GetStringDescriptor-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdDescriptor001 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor001 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = 0; + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor001 %{public}d ret=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor001 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("配置描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor001 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor002 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor002 : GetConfigDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor002 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor002 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor003 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor003 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 222; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor003 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor003 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor004 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,configId + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor004 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = 1; + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor004 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("配置描述符", descparams.buffer, descparams.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor004 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor005 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor005 : GetConfigDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = 222; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor005 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor005 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor006 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor006 : GetConfigDescriptor-----------"); + uint8_t busNum = 222; + uint8_t devAddr = device.GetDevAddr(); + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor006 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor006 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor007 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor007 : GetConfigDescriptor-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 1; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[255] = {0}; + uint32_t length = 8; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor007 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor007 : GetConfigDescriptor-----------"); +} + +/** + * @tc.name: UsbdDescriptor008 + * @tc.desc: Test functions to GetConfigDescriptor + * @tc.desc: int32_t GetConfigDescriptor(uint8_t busNum, uint8_t devAddr, struct DescriptorParams ¶ms); + * @tc.desc: 反向测试:busNum、devAddr、length错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDescriptorTest, UsbdGetConfigDescriptor008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDescriptor008 : GetConfigDescriptor-----------"); + uint8_t busNum = 255; + uint8_t devAddr = 222; + uint8_t configId = device.GetConfigs().front().GetId(); + uint8_t buffer[] = {0}; + uint32_t length = 0; + struct DescriptorParams descparams = {configId, buffer, length}; + auto ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, descparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDescriptorTest::UsbdGetConfigDescriptor008 %{public}d length=%{public}d buffer=%{public}d", + __LINE__, length, sizeof(buffer)); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDescriptorTest::UsbdGetConfigDescriptor008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDescriptor008 : GetConfigDescriptor-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_device_test.cpp b/hdi/test/unittest/common/src/usbd_device_test.cpp new file mode 100644 index 00000000..5040699f --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_device_test.cpp @@ -0,0 +1,230 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_device_test.h" +#include +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "delayed_sp_singleton.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +vector deviceList; + +UsbDevice device; + +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +void UsbdDeviceTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdDeviceTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Get DeviceList OK, result = %{public}d", __LINE__, + ret); + ASSERT_TRUE(!(deviceList.empty())) << "DeviceList NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d DeviceList size=%{public}d", __LINE__, + deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); +} + +void UsbdDeviceTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdDeviceTest-----------"); +} + +void UsbdDeviceTest::SetUp(void) {} + +void UsbdDeviceTest::TearDown(void) {} + +/** + * @tc.name: UsbdDevice001 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice001 : OpenDevice-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdDeviceTest:: Line:%{public}d OpenDevice GetBusNum =%{public}d GetDevAddr =%{public}d", __LINE__, + device.GetBusNum(), device.GetDevAddr()); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result =%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice001 : OpenDevice-----------"); +} + +/** + * @tc.name: UsbdDevice002 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice002 : OpenDevice-----------"); + uint8_t busNum = 255; + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice002 : OpenDevice-----------"); +} + +/** + * @tc.name: UsbdDevice003 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice003 : OpenDevice-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 255; + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice003 : OpenDevice-----------"); +} + +/** + * @tc.name: UsbdDevice004 + * @tc.desc: Test functions to OpenDevice + * @tc.desc: int32_t OpenDevice(busNum ,devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdOpenDevice004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice004 : OpenDevice-----------"); + uint8_t busNum = 255; + uint8_t devAddr = 255; + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice004 : OpenDevice-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdDevice011 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice001 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice001 : Close-----------"); +} + +/** + * @tc.name: UsbdDevice012 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice002 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice002 : Close-----------"); +} + +/** + * @tc.name: UsbdDevice013 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice003 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 255; + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice003 : Close-----------"); +} + +/** + * @tc.name: UsbdDevice014 + * @tc.desc: Test functions to CloseDevice + * @tc.desc: int32_t CloseDevice(uint8_t busNum, uint8_t devAddr) + * @tc.desc: + * @tc.type: FUNC + */ +HWTEST_F(UsbdDeviceTest, UsbdCloseDevice004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdDevice004 : Close-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d OpenDevice result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + devAddr = 255; + ret = UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d Close result=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdDevice004 : Close-----------"); +} \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_function_test.cpp b/hdi/test/unittest/common/src/usbd_function_test.cpp new file mode 100644 index 00000000..fc9abbbc --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_function_test.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_function_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +void UsbdFunctionTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdFunctionTest-----------"); +} + +void UsbdFunctionTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdFunctionTest-----------"); +} + +void UsbdFunctionTest::SetUp(void) {} + +void UsbdFunctionTest::TearDown(void) {} + +/** + * @tc.name: UsbdGetCurrentFunctions001 + * @tc.desc: Test functions to GetCurrentFunctions + * @tc.desc: int32_t GetCurrentFunctions() + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdGetCurrentFunctions001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction001 : GetCurrentFunctions-----------"); + int32_t funcs = 0; + auto ret = UsbdClient::GetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdGetCurrentFunctions001 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction001 : GetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdGetCurrentFunctions002 + * @tc.desc: Test functions to GetCurrentFunctions + * @tc.desc: int32_t GetCurrentFunctions() + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdGetCurrentFunctions002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction002 : GetCurrentFunctions-----------"); + auto ret = UsbdClient::SetCurrentFunctions(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction011 %{public}d SetCurrentFunctions=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + int32_t funcs = 255; + ret = UsbdClient::GetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction002 : GetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions001 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction001 : SetCurrentFunctions-----------"); + int32_t funcs = 1; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdFunctionTest::UsbdSetCurrentFunctions001 %{public}d SetCurrentFunctions=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction001 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions002 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 反向测试:参数异常,funcs错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction002 : SetCurrentFunctions-----------"); + int32_t funcs = -1; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction012 %{public}d ret=%{public}d", __LINE__, ret); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdFunction012 %{public}d funcs=%{public}d", __LINE__, funcs); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction002 : SetCurrentFunctions-----------"); +} +/** + * @tc.name: UsbdSetCurrentFunctions003 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction003 : SetCurrentFunctions-----------"); + int32_t funcs = 2; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction003 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions004 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction004 : SetCurrentFunctions-----------"); + int32_t funcs = 3; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction004 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions005 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction005 : SetCurrentFunctions-----------"); + int32_t funcs = 4; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction005 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions006 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction006 : SetCurrentFunctions-----------"); + int32_t funcs = 5; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction006 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions007 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction007 : SetCurrentFunctions-----------"); + int32_t funcs = 6; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction007 : SetCurrentFunctions-----------"); +} + +/** + * @tc.name: UsbdSetCurrentFunctions008 + * @tc.desc: Test functions to SetCurrentFunctions + * @tc.desc: int32_t SetCurrentFunctions(int32_t funcs) + * @tc.desc: 反向测试:参数异常,funcs错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdFunctionTest, UsbdSetCurrentFunctions008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdFunction008 : SetCurrentFunctions-----------"); + int32_t funcs = 8; + auto ret = UsbdClient::SetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdFunctionTest::UsbdSetCurrentFunctions008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdFunction008 : SetCurrentFunctions-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_interface_test.cpp b/hdi/test/unittest/common/src/usbd_interface_test.cpp new file mode 100644 index 00000000..0018c805 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_interface_test.cpp @@ -0,0 +1,643 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_interface_test.h" +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "delayed_sp_singleton.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); +UsbDevice device; +UsbInterface interface; + +void UsbdInterfaceTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdDeviceTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + USBDevicePipe pipe; + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdDeviceTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); +} + +void UsbdInterfaceTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdInterfaceTest-----------"); +} + +void UsbdInterfaceTest::SetUp(void) {} + +void UsbdInterfaceTest::TearDown(void) {} + +/** + * @tc.name: UsbdClaimInterface001 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface001 : ClaimInterface-----------"); + + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface001 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface002 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface002 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 20; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface002 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface003 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface003 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface003 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface004 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface004 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface004 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface005 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface005 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + devAddr = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface005 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface006 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface006 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface006 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface007 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface007 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 255; + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface007 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdClaimInterface008 + * @tc.desc: Test functions to ClaimInterface + * @tc.desc: int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdClaimInterface008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface008 : ClaimInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 255; + devAddr = 255; + interfaceid = 255; + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdClaimInterface008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface008 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface001 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface001 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface001 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface001 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface002 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface002 : ReleaseInterface-----------"); + uint8_t busNum = 25; + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface002 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface003 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface003 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 25; + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface003 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface003 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface004 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface004 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface004 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface004 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface005 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface005 : ReleaseInterface-----------"); + uint8_t busNum = 25; + uint8_t devAddr = 25; + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface005 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface005 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface006 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface006 : ReleaseInterface-----------"); + uint8_t busNum = 255; + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface006 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface006 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface007 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface007 : ReleaseInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 255; + int32_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface007 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface007 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbdReleaseInterface008 + * @tc.desc: Test functions to ReleaseInterface + * @tc.desc: int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) + * @tc.desc: 反向测试:busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdReleaseInterface008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface008 : ReleaseInterface-----------"); + uint8_t busNum = 255; + uint8_t devAddr = 255; + int32_t interfaceid = 255; + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdReleaseInterface008 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface008 : ReleaseInterface-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdSetInterface001 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface001 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface001 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface001 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface002 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface002 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + ; + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface002 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 222; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface002 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface003 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface003 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface003 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + devAddr = 222; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface003 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface004 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface004 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = 222; + uint8_t altIndex = 222; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface004 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface004 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface005 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface005 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t interfaceid = interface.GetId(); + uint8_t altIndex = interface.GetAlternateSetting(); + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface005 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 233; + devAddr = 233; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface005 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface006 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface006 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 224; + uint8_t altIndex = 1; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface006 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 224; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface006 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface007 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface007 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 225; + uint8_t altIndex = 225; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface007 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + devAddr = 225; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface007 : SetInterface-----------"); +} + +/** + * @tc.name: UsbdSetInterface008 + * @tc.desc: Test functions to SetInterface + * @tc.desc: int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) + * @tc.desc: 反向测试:busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdInterfaceTest, UsbdSetInterface008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdInterface008 : SetInterface-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + int32_t interfaceid = 225; + uint8_t altIndex = 225; + uint32_t length = 8; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface008 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + busNum = 225; + devAddr = 225; + ret = UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdInterfaceTest::UsbdSetInterface008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdInterface008 : SetInterface-----------"); +} \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_port_test.cpp b/hdi/test/unittest/common/src/usbd_port_test.cpp new file mode 100644 index 00000000..1bed0fc3 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_port_test.cpp @@ -0,0 +1,188 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_port_test.h" +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_port.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +void UsbdPortTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdPortTest-----------"); +} + +void UsbdPortTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdPortTest-----------"); +} + +void UsbdPortTest::SetUp(void) {} + +void UsbdPortTest::TearDown(void) {} + +/** + * @tc.name: UsbdSetPortRole001 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole001 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole001 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole002 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,portId错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole002 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(2, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole002 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole003 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,powerRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole003 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 4, 2); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole003 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole004 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole004 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 1, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole004 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole005 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,portId、powerRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole005 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 5, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole005 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole006 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:参数异常,portId、dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole006 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(5, 1, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole006 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole007 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:powerRole、dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole007 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 5, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole007 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbdSetPortRole008 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 反向测试:portId、powerRole、dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, UsbdSetPortRole008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole008 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(2, 5, 5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::UsbdSetPortRole008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole008 : SetPortRole-----------"); +} + +/** + * @tc.name: SetPortRole09 + * @tc.desc: Test functions to SetPortRole + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdPortTest, SetPortRole09, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdSetPortRole009 : SetPortRole-----------"); + auto ret = UsbdClient::SetPortRole(1, 2, 2); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdPortTest::SetPortRole09 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdSetPortRole009 : SetPortRole-----------"); +} diff --git a/hdi/test/unittest/common/src/usbd_request_test.cpp b/hdi/test/unittest/common/src/usbd_request_test.cpp new file mode 100644 index 00000000..b997377a --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_request_test.cpp @@ -0,0 +1,1091 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_request_test.h" +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "delayed_sp_singleton.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_request.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +UsbDevice device; + +void UsbdRequestTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdRequestTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d GetDevices=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + USBDevicePipe pipe; + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdRequestTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdRequestTest-----------"); +} + +void UsbdRequestTest::SetUp(void) {} + +void UsbdRequestTest::TearDown(void) {} + +/** + * @tc.name: UsbdRequest001 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest001 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue001 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest001 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest002 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + devAddr = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue002 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue002 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest003 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest003 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint8_t pointid = point.GetAddress(); + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + devAddr = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue003 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue003 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest003 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest004 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、configIndex错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest004 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t length = 255; + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + interfaceid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue004 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue004 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest004 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest005 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest005 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + devAddr = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue005 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest005 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest006 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:参数异常,busNum、interfaceId错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest006 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + busNum = 222; + interfaceid = 222; + pointid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue006 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest006 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest007 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 正向测试 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest007 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request 007"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue007 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue007 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue007 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqparams.clientData, reqparams.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqparams.buffer, reqparams.length); + + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest007 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest008 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:interfaceId错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest008 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "reuquest008"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue008 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue008 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + interfaceid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue008 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest008 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbdRequest009 + * @tc.desc: Test functions to RequestQueue + * @tc.desc: int32_t RequestQueue(uint8_t busNum, uint8_t devAddr, uint8_t ifId, uint8_t endpointid, struct + * RequestParams ¶ms); + * @tc.desc: 反向测试:interfaceId、poinid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestQueue009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest009 : RequestQueue-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request 009"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue009 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue009 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue009 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + interfaceid = 222; + pointid = 222; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestQueue009 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest009 : RequestQueue-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdRequest001 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest001 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait001 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest001 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest002 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 222; + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait002 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest002 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest003 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest003 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 222; + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait003 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest003 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest004 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:timeout错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest004 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, -500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait004 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest004 : RequestWait-----------"); +} + +/** + * @tc.name: UsbdRequest005 + * @tc.desc: Test functions to RequestWait + * @tc.desc: int32_t RequestWait(uint8_t busNum, uint8_t devAddr, int32_t timeout, struct RequestParams ¶ms); + * @tc.desc: 反向测试:busNum、devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestWait005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest005 : RequestWait-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t buffer[255] = {}; + uint32_t length = 255; + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + length = 0; + uint8_t *clientObj = new uint8_t[clientLength]; + struct RequestParams reqwait = {clientObj, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, 500, reqwait); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestWait005 %{public}d RequestWait=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("RequestWait:clientData", (uint8_t *)reqwait.clientData, reqwait.clientLength); + UsbdClient::PrintBuffer("RequestWait:buffer", reqwait.buffer, reqwait.length); + UsbdClient::PrintBuffer("RequestWait:clientData", (const uint8_t *)request.GetClientData(), + request.GetClientLength()); + UsbdClient::PrintBuffer("RequestWait:buffer", request.GetBuffer(), request.GetLength()); + delete[] clientObj; + clientObj = nullptr; + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest005 : RequestWait-----------"); +} + +/**********************************************************************************************************/ + +/** + * @tc.name: UsbdRequest001 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest001 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue write"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request001"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel001 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest001 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest002 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,busNum错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest002 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request002"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel002 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest002 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest003 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,devAddr错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest003 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request003"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel003 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest003 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest004 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,interfaceid错误 结果正常??? + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest004 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + UsbRequest request; + uint8_t tag[50] = "queue read"; + request.SetClientData((void *)tag, 11); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request004"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + interfaceid = 222; + pointid = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel004 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest004 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest005 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 正向测试 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest005 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request005"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestQueue001 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel005 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest005 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest006 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,busNum、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest006 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request006"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestCancel006 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 224; + interfaceid = 224; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel006 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest006 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest007 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest007 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request007"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestCancel007 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + devAddr = 224; + interfaceid = 224; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel007 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest007 : RequestCancel-----------"); +} + +/** + * @tc.name: UsbdRequest008 + * @tc.desc: Test functions to RequestCancel + * @tc.desc: int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointid) + * @tc.desc: 反向测试:参数异常,busNum、devAddr、interfaceid错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbdRequestTest, UsbdRequestCancel008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdRequest008 : RequestCancel-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint8_t buffer[255] = "request008"; + uint32_t length = 255; + uint8_t interfaceid = interface.GetId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdRequestTest::UsbdRequestCancel008 %{public}d interfaceid=%{public}d pointid=%{public}d", __LINE__, + interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "queue rWrite"; + request.SetClientData((void *)tag, 11); + uint32_t clientLength = sizeof(UsbRequest); + struct RequestParams reqparams = {(void *)&request, clientLength, buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, interfaceid, pointid, reqparams); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d RequestQueue=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + busNum = 222; + devAddr = 222; + interfaceid = 222; + ret = UsbdClient::RequestCancel(busNum, devAddr, interfaceid, pointid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdRequestTest::UsbdRequestCancel008 %{public}d RequestCancel=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdRequest008 : RequestCancel-----------"); +} \ No newline at end of file diff --git a/hdi/test/unittest/common/src/usbd_transfer_test.cpp b/hdi/test/unittest/common/src/usbd_transfer_test.cpp new file mode 100644 index 00000000..7ca6e544 --- /dev/null +++ b/hdi/test/unittest/common/src/usbd_transfer_test.cpp @@ -0,0 +1,824 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usbd_transfer_test.h" +#include +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_service.h" +#include "usb_srv_client.h" +#include "usbd_client.h" +#include "usbd_config_test.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +// OHOS::USB::CtrlTransferParamsParams ctrlparmas; +// OHOS::USB::TransferParams trsparamas; +std::vector deviceList; +auto &usbSrvClient = UsbSrvClient::GetInstance(); + +UsbDevice device; + +void UsbdTransferTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdTransferTest-----------"); + auto ret = usbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d GetDevices=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d size=%{public}d", __LINE__, deviceList.size()); + device = deviceList.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: Line:%{public}d DeviceList device.ToString=%{public}s", __LINE__, + device.ToString().c_str()); + USBDevicePipe pipe; + ret = usbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); +} + +void UsbdTransferTest::TearDownTestCase(void) +{ + auto ret = UsbdClient::CloseDevice(device.GetBusNum(), device.GetDevAddr()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest:: %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdTransferTest-----------"); +} + +void UsbdTransferTest::SetUp(void) {} + +void UsbdTransferTest::TearDown(void) {} + +/** + * @tc.name: UsbdControlTransfer001 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer001 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + const USBConfig &config = device.GetConfigs().front(); + uint8_t configId = config.GetId(); + uint32_t length = 255; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 8, 0, 0, &configId, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer001 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer001 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer002 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer002 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 6, 0x100, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer002 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer002 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer003 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer003 : ControlTransfer-----------"); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + int32_t intercafeidex = interface.GetId(); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t *buffer = (uint8_t *)interface.GetAlternateSetting(); + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0X0A, .0, intercafeidex, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer003 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer003 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer004 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer004 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer004 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer004 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer005 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer005 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer005 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer005 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer006 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer006 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer006 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer006 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer007 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer007 : ControlTransfer-----------"); + int idex = device.GetConfigs().front().GetInterfaces().front().GetEndpoints().front().GetEndpointNumber(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer007 %{public}d idex=%{public}d", __LINE__, + idex); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000010, 0X0C, 0, idex, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer007 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer007 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer008 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer008 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0XFFFF, 1, 1, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdConfigTest::UsbdControlTransfer008 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer008 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer009 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer009 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + const USBConfig &config = device.GetConfigs().front(); + uint8_t configId = config.GetId(); + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 0X0F, 0, 0, &configId, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer009 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer009 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer010 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer010 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 11, 0X7FFFFFFF, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer010 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer010 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer011 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer011, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer011 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 7, 0, 0b11111111, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer011 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer011 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer012 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer012, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer012 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t *buffer = nullptr; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 7, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer012 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer012: ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer013 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer013, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer013 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 0; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000000, 7, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer013 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer013 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer014 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer014, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer014 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, -1}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer014 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer014 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer015 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer015, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer015 : ControlTransfer-----------"); + uint8_t busNum = 255; + uint8_t devAddr = device.GetDevAddr(); + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer015 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer015 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdControlTransfer016 + * @tc.desc: Test functions to ControlTransfer(uint8_t busNum, uint8_t devAddr, struct CtrlTransferParamsParams + * ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdControlTransfer016, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdControlTransfer016 : ControlTransfer-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = 255; + uint32_t length = 255; + uint8_t buffer[255] = {0}; + struct CtrlTransferParamsParams ctrlparmas = {0b10000001, 0, 0, 0, buffer, length, 50}; + auto ret = UsbdClient::ControlTransfer(busNum, devAddr, ctrlparmas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdControlTransfer016 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("ControlTransfer", ctrlparmas.buffer, ctrlparmas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdControlTransfer016 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead001 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead001 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + uint8_t pointid = point.GetAddress(); + auto ret = UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ret = UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + uint8_t buffer[255] = {}; + uint32_t length = 8; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead001 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead001 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead002 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead002 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead002 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + busNum = 222; + uint32_t length = 100; + uint8_t buffer[100] = {0}; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead002 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead002 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead003 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead003 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead003 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead003 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + devAddr = 244; + uint32_t length = 100; + uint8_t buffer[100] = {0}; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead003 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead003 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead004 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead004 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead004 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead004 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + interfaceid = 244; + uint8_t *buffer = nullptr; + uint32_t length = 100; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead004 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead004 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferRead005 + * @tc.desc: Test functions to BulkTransferRead(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferRead005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferRead005 : BulkTransferRead-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(0); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead005 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferRead005 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 0; + uint8_t buffer[100] = {}; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferRead(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbdTransferTest::UsbdBulkTransferRead005 %{public}d UsbdBulkTransferRead=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferRead", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferRead005 : BulkTransferRead-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite001 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite001 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite001 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite001 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ01"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite001 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite001 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite002 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite002 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite002 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite002 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + interfaceid = 99; + busNum = 99; + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ02"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite002 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite002 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite003 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite003 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite003 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite003 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + devAddr = 244; + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ03"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite003 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite003 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite004 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite004 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite004 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite004 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + interfaceid = 255; + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ04"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite004 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite004 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite005 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite005 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite005 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = 255; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite005 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ05"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite005 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite005 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite006 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite006 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite006 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite006 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + devAddr = 99; + uint32_t length = 100; + uint8_t *buffer = nullptr; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite006 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite006 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite007 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite007 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite007 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = 99; + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite007 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 0; + uint8_t buffer[100] = "hello world bulk writ07"; + UsbRequest request; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, 50}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite007 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite007 : BulkTransferWrite-----------"); +} + +/** + * @tc.name: UsbdBulkTransferWrite008 + * @tc.desc: Test functions to BulkTransferWrite(uint8_t busNum, uint8_t devAddr, struct TransferParams ¶ms); + * @tc.type: FUNC + */ +HWTEST_F(UsbdTransferTest, UsbdBulkTransferWrite008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbdBulkTransferWrite008 : BulkTransferWrite-----------"); + uint8_t busNum = device.GetBusNum(); + uint8_t devAddr = device.GetDevAddr(); + USBEndpoint point = device.GetConfigs().front().GetInterfaces().at(1).GetEndpoints().at(1); + uint8_t interfaceid = point.GetInterfaceId(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite008 %{public}d interfaceid=%{public}d", + __LINE__, interfaceid); + uint8_t pointid = point.GetAddress(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite008 %{public}d pionid=%{public}d", __LINE__, + pointid); + UsbdClient::ReleaseInterface(busNum, devAddr, interfaceid); + UsbdClient::ClaimInterface(busNum, devAddr, interfaceid); + uint32_t length = 100; + uint8_t buffer[100] = "hello world bulk writ08"; + struct TransferParams trsparamas = {interfaceid, pointid, buffer, length, -1}; + auto ret = UsbdClient::BulkTransferWrite(busNum, devAddr, trsparamas); + USB_HILOGI(MODULE_USB_SERVICE, "UsbdTransferTest::UsbdBulkTransferWrite008 %{public}d BulkTransferWrite=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbdClient::PrintBuffer("BulkTransferWrite", trsparamas.buffer, trsparamas.length); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbdBulkTransferWrite008 : BulkTransferWrite-----------"); +} diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn new file mode 100644 index 00000000..10c4be72 --- /dev/null +++ b/interfaces/innerkits/BUILD.gn @@ -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. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("usbsrv_private_config") { + include_dirs = [ + "${usb_manager_path}/services/zidl/include", + "//utils/system/safwk/native/include", + ] +} + +config("usbsrv_public_config") { + include_dirs = [ "native/include" ] +} + +ohos_shared_library("usbsrv_client") { + sources = [ + "${usb_manager_path}/services/zidl/src/usb_srv_proxy.cpp", + "native/src/usb_srv_client.cpp", + "native/src/usb_device.cpp", + "native/src/usb_device_pipe.cpp", + "native/src/usb_request.cpp", + ] + + configs = [ + "${utils_path}:utils_config", + ":usbsrv_private_config", + ":usbsrv_public_config", + ] + + public_configs = [ ":usbsrv_public_config" ] + + deps = [ "//utils/native/base:utils" ] + + external_deps = [ + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + part_name = "usb_manager_native" +} diff --git a/interfaces/innerkits/native/include/iusb_srv.h b/interfaces/innerkits/native/include/iusb_srv.h new file mode 100644 index 00000000..ac71a1db --- /dev/null +++ b/interfaces/innerkits/native/include/iusb_srv.h @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_INNERKITS_IUSB_SRV_H +#define USBMGR_INNERKITS_IUSB_SRV_H + +#include +#include +#include "iremote_broker.h" +#include "iremote_object.h" +#include "usb_device.h" +#include "usb_info.h" +#include "usb_port.h" + +namespace OHOS { +namespace USB { + +class IUsbSrv : public IRemoteBroker { +public: + enum { + USB_FUN_HAS_RIGHT = 0, + USB_FUN_REQUEST_RIGHT, + USB_FUN_OPEN_DEVICE, + USB_FUN_GET_DEVICE, + USB_FUN_GET_DEVICES, + USB_FUN_GET_CURRENT_FUNCTIONS, + USB_FUN_SET_CURRENT_FUNCTIONS, + USB_FUN_USB_FUNCTIONS_FROM_STRING, + USB_FUN_USB_FUNCTIONS_TO_STRING, + USB_FUN_CLAIM_INTERFACE, + USB_FUN_RELEASE_INTERFACE, + USB_FUN_BULK_TRANSFER_READ, + USB_FUN_BULK_TRANSFER_WRITE, + USB_FUN_CONTROL_TRANSFER, + USB_FUN_SET_ACTIVE_CONFIG, + USB_FUN_GET_ACTIVE_CONFIG, + USB_FUN_SET_INTERFACE, + USB_FUN_GET_PORTS, + USB_FUN_GET_SUPPORTED_MODES, + USB_FUN_SET_PORT_ROLE, + USB_FUN_REQUEST_QUEUE, + USB_FUN_REQUEST_WAIT, + USB_FUN_REQUEST_CANCEL, + USB_FUN_GET_DESCRIPTOR, + USB_FUN_CLOSE_DEVICE, + }; + + virtual int32_t OpenDevice(uint8_t busNum, uint8_t devAddr) = 0; + virtual int32_t HasRight(std::string deviceName) = 0; + virtual int32_t RequestRight(std::string deviceName) = 0; + virtual int32_t GetDevices(std::vector &deviceList) = 0; + virtual int32_t GetCurrentFunctions(int32_t &funcs) = 0; + virtual int32_t SetCurrentFunctions(int32_t funcs) = 0; + virtual int32_t UsbFunctionsFromString(std::string funcs) = 0; + virtual std::string UsbFunctionsToString(int32_t funcs) = 0; + virtual int32_t GetPorts(std::vector &ports) = 0; + virtual int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes) = 0; + virtual int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) = 0; + virtual int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) = 0; + virtual int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) = 0; + virtual int32_t BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpointid, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) = 0; + virtual int32_t BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpointid, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) = 0; + virtual int32_t ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) = 0; + virtual int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configId) = 0; + virtual int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configId) = 0; + virtual int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) = 0; + virtual int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) = 0; + virtual int32_t RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientData, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) = 0; + virtual int32_t RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) = 0; + virtual int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) = 0; + virtual int32_t Close(uint8_t busNum, uint8_t devAddr) = 0; + +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.usb.IUsbSrv"); +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_INNERKITS_IUSB_SRV_H diff --git a/interfaces/innerkits/native/include/usb_config.h b/interfaces/innerkits/native/include/usb_config.h new file mode 100644 index 00000000..fce40039 --- /dev/null +++ b/interfaces/innerkits/native/include/usb_config.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_CONFIG_H +#define USB_CONFIG_H + +#include +#include +#include +#include +#include +#include "usb_common.h" +#include "usb_interface.h" + +namespace OHOS { +namespace USB { +class USBConfig { +public: + USBConfig(uint32_t id, + uint32_t attributes, + std::string name, + uint32_t maxPower, + std::vector interfaces) + { + this->id = id; + this->attributes = attributes; + this->maxPower = maxPower; + this->name = name; + this->interfaces = interfaces; + } + USBConfig() {} + + const int32_t &GetId() const + { + return id; + } + + const int32_t &GetAttributes() const + { + return attributes; + } + + bool GetInterface(uint32_t index, UsbInterface &interface) const + { + if (index >= interfaces.size()) { + return false; + } + interface = interfaces[index]; + return true; + } + + int32_t GetInterfaceCount() const + { + return interfaces.size(); + } + + int32_t GetMaxPower() const + { + return maxPower * 2; + } + + const std::string &GetName() const + { + return name; + } + + bool IsRemoteWakeup() const + { + return (attributes & USB_CFG_REMOTE_WAKEUP) != 0; + } + + bool IsSelfPowered() const + { + return (attributes & USB_CFG_SELF_POWERED) != 0; + } + + void SetInterfaces(const std::vector &interfaces) + { + this->interfaces = interfaces; + } + std::vector &GetInterfaces() + { + return interfaces; + } + void SetId(int32_t id) + { + this->id = id; + } + void SetAttribute(int32_t attributes) + { + this->attributes = attributes; + } + void SetMaxPower(int32_t maxPower) + { + this->maxPower = maxPower; + } + std::string ToString() const + { + std::string str; + std::ostringstream ss; + ss << "name=" << name << "," + << "id=" << id << "," + << "iConfiguration=" << (int32_t)iConfiguration << "," + << "attributes=" << attributes << "," + << "maxPower=" << maxPower << "; "; + str = ss.str(); + ss.str(""); + for (size_t i = 0; i < interfaces.size(); ++i) { + const UsbInterface &interface = interfaces[i]; + str += interface.ToString(); + } + return str; + } + void SetName(std::string Name) + { + this->name = Name; + } + void SetiConfiguration(uint8_t idx) + { + this->iConfiguration = idx; + } + uint8_t GetiConfiguration() + { + return this->iConfiguration; + } + +private: + int32_t id = INVALID_USB_INT_VALUE; + int32_t attributes = INVALID_USB_INT_VALUE; + std::vector interfaces; + int32_t maxPower = INVALID_USB_INT_VALUE; + std::string name; + uint8_t iConfiguration; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_CONFIG_H diff --git a/interfaces/innerkits/native/include/usb_device.h b/interfaces/innerkits/native/include/usb_device.h new file mode 100644 index 00000000..6d7b8e5c --- /dev/null +++ b/interfaces/innerkits/native/include/usb_device.h @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_DEVICE_H +#define USB_DEVICE_H + +#include +#include +#include +#include +#include "iremote_object.h" +#include "usb_config.h" +#include "usb_interface.h" + +namespace OHOS { +namespace USB { +class UsbDevice { +public: + UsbDevice(std::string mName, + std::string mManufacturerName, + std::string mProductName, + std::string mVersion, + uint8_t devAddr, + uint8_t busNum, + int mVendorId, + int mProductId, + int mClass, + int mSubclass, + int mProtocol, + std::vector configs) + { + this->mName = mName; + this->mManufacturerName = mManufacturerName; + this->mProductName = mProductName; + this->mVersion = mVersion; + this->devAddr = devAddr; + this->busNum = busNum; + this->mVendorId = mVendorId; + this->mProductId = mProductId; + this->mClass = mClass; + this->mSubclass = mSubclass; + this->mProtocol = mProtocol; + this->configs = configs; + } + UsbDevice() {} + const std::string &GetName() const + { + return mName; + } + const std::string &GetManufacturerName() const + { + return mManufacturerName; + } + const std::string &GetProductName() const + { + return mProductName; + } + const std::string &GetVersion() const + { + return mVersion; + } + int32_t GetVendorId() const + { + return mVendorId; + } + int32_t GetProductId() const + { + return mProductId; + } + int32_t GetClass() const + { + return mClass; + } + int32_t GetSubclass() const + { + return mSubclass; + } + int32_t GetProtocol() const + { + return mProtocol; + } + int32_t GetConfigCount() const + { + return configs.size(); + } + int32_t GetConfig(uint32_t index, USBConfig &config) const + { + if (index >= configs.size()) { + return ERR_INVALID_VALUE; + } + config = configs[index]; + return ERR_OK; + } + void SetConfigs(const std::vector &configs) + { + this->configs = configs; + } + + uint8_t GetDevAddr() const + { + return devAddr; + } + uint8_t GetBusNum() const + { + return busNum; + } + bool GetDescConfigCount() + { + return descConfigCount; + } + + void SetDevAddr(uint8_t Num) + { + devAddr = Num; + } + void SetBusNum(uint8_t Num) + { + busNum = Num; + } + void SetName(std::string Name) + { + mName = Name; + } + void SetManufacturerName(std::string Name) + { + mManufacturerName = Name; + } + void SetProductName(std::string Name) + { + mProductName = Name; + } + void SetVersion(std::string Name) + { + mVersion = Name; + } + void SetVendorId(int Id) + { + mVendorId = Id; + } + void SetProductId(int Id) + { + mProductId = Id; + } + void SetClass(int Id) + { + mClass = Id; + } + void SetSubclass(int Id) + { + mSubclass = Id; + } + void SetProtocol(int Id) + { + mProtocol = Id; + } + void SetDescConfigCount(uint8_t count) + { + descConfigCount = count; + } + + std::vector &GetConfigs() + { + return configs; + } + + std::string ToString() const + { + std::string str; + std::ostringstream ss; + ss << "mName=" << mName << "," + << "mManufacturerName=" << mManufacturerName << "," + << "mProductName=" << mProductName << "," + << "mVersion=" << mVersion << "," + << "mSerial=" << mSerial << "," + << "busNum=" << (int32_t)busNum << "," + << "devAddr=" << (int32_t)devAddr << "," + << "mVendorId=" << mVendorId << "," + << "mProductId=" << mProductId << "," + << "mClass=" << mClass << "," + << "mSubclass=" << mSubclass << "," + << "mProtocol=" << mProtocol << "; "; + str = ss.str(); + ss.str(""); + std::string strConfigs; + for (size_t i = 0; i < configs.size(); ++i) { + const USBConfig &config = configs[i]; + strConfigs += config.ToString(); + } + str += strConfigs; + return str; + } + + void SetiManufacturer(uint8_t idx) + { + this->iManufacturer = idx; + } + uint8_t GetiManufacturer() + { + return this->iManufacturer; + } + void SetiProduct(uint8_t idx) + { + this->iProduct = idx; + } + uint8_t GetiProduct() + { + return this->iProduct; + } + void SetiSerialNumber(uint8_t idx) + { + this->iSerialNumber = idx; + } + uint8_t GetiSerialNumber() + { + return this->iSerialNumber; + } + void SetmSerial(std::string Name) + { + this->mSerial = Name; + } + std::string GetmSerial() + { + return this->mSerial; + } + void SetbMaxPacketSize0(uint8_t val) + { + this->bMaxPacketSize0 = val; + } + uint8_t GetbMaxPacketSize0() + { + return this->bMaxPacketSize0; + } + void SetbcdUSB(uint16_t val) + { + this->bcdUSB = val; + } + uint16_t GetbcdUSB() + { + return this->bcdUSB; + } + void SetbcdDevice(uint16_t val) + { + this->bcdDevice = val; + } + uint16_t GetbcdDevice() + { + return this->bcdDevice; + } + +private: + std::string mName; + std::string mManufacturerName; + std::string mProductName; + std::string mVersion; + std::string mSerial; + uint8_t devAddr; + uint8_t busNum; + uint8_t descConfigCount; + + uint8_t bMaxPacketSize0; + uint16_t bcdUSB; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + + int mVendorId; + int mProductId; + int mClass; + int mSubclass; + int mProtocol; + std::vector configs; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_DEVICE_H diff --git a/interfaces/innerkits/native/include/usb_device_pipe.h b/interfaces/innerkits/native/include/usb_device_pipe.h new file mode 100644 index 00000000..4aaf5fd3 --- /dev/null +++ b/interfaces/innerkits/native/include/usb_device_pipe.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_PIPE_H +#define USB_PIPE_H + +#include +#include +#include "iremote_object.h" +#include "iusb_srv.h" + +namespace OHOS { +namespace USB { +class USBDevicePipe { +public: + USBDevicePipe(); + USBDevicePipe(uint8_t busNum, uint8_t devAddr); + int32_t ClaimInterface(const UsbInterface &interface, bool force); + int32_t ReleaseInterface(const UsbInterface &interface); + int32_t BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t timeout); + int32_t ControlTransfer(int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout); + int32_t SetConfiguration(const USBConfig &config); + int32_t SetInterface(const UsbInterface &interface); + int32_t Close(); + + void SetBusNum(uint8_t busNum); + void SetDevAddr(uint8_t devAddr); + uint8_t GetBusNum() const; + uint8_t GetDevAddr() const; + +private: + uint8_t busNum; + uint8_t devAddr; + void *usbClient; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_PIPE_H diff --git a/interfaces/innerkits/native/include/usb_endpoint.h b/interfaces/innerkits/native/include/usb_endpoint.h new file mode 100644 index 00000000..b63d3be5 --- /dev/null +++ b/interfaces/innerkits/native/include/usb_endpoint.h @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_ENDPOINT_H +#define USB_ENDPOINT_H + +#include +#include +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { +class USBEndpoint { +public: + USBEndpoint(uint32_t address, uint32_t attributes, uint32_t interval, uint32_t maxPacketSize) + { + this->address = address; + this->attributes = attributes; + this->interval = interval; + this->maxPacketSize = maxPacketSize; + } + USBEndpoint() {} + + uint8_t GetNumber() const + { + return address & USB_ENDPOINT_NUMBER_MASK; + } + const int32_t &GetAddress() const + { + return address; + } + + int32_t GetDirection() const + { + return address & USB_ENDPOINT_DIR_MASK; + } + + const int32_t &GetAttributes() const + { + return attributes; + } + + int32_t GetEndpointNumber() const + { + return address & USB_ENDPOINT_NUMBER_MASK; + } + + const int32_t &GetInterval() const + { + return interval; + } + + const int32_t &GetMaxPacketSize() const + { + return maxPacketSize; + } + + int32_t GetType() const + { + return (attributes & USB_ENDPOINT_XFERTYPE_MASK); + } + + std::string ToString() const + { + std::string ret = "USBEndpoint:[Address:"; + ret.append(std::to_string(address)) + .append(", Direction:") + .append(std::to_string(GetDirection())) + .append(", Attributes:") + .append(std::to_string(attributes)) + .append(", EndpointNumber:") + .append(std::to_string(GetEndpointNumber())) + .append(", Interval:") + .append(std::to_string(interval)) + .append(", MaxPacketSize:") + .append(std::to_string(maxPacketSize)) + .append(", Type:") + .append(std::to_string(GetType())) + .append("]"); + return ret; + } + void SetAddr(int32_t val) + { + address = val; + } + void SetAttr(int32_t val) + { + attributes = val; + } + void SetInterval(int32_t val) + { + interval = val; + } + void SetMaxPacketSize(int32_t val) + { + maxPacketSize = val; + } + void SetInterfaceId(uint8_t interfaceId) + { + this->interfaceId = interfaceId; + } + int8_t GetInterfaceId() const + { + return interfaceId; + } + +private: + int32_t address = INVALID_USB_INT_VALUE; + int32_t attributes = INVALID_USB_INT_VALUE; + int32_t interval = INVALID_USB_INT_VALUE; + int32_t maxPacketSize = INVALID_USB_INT_VALUE; + uint8_t interfaceId; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_ENDPOINT_H diff --git a/interfaces/innerkits/native/include/usb_info.h b/interfaces/innerkits/native/include/usb_info.h new file mode 100644 index 00000000..972342de --- /dev/null +++ b/interfaces/innerkits/native/include/usb_info.h @@ -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. + */ + +#ifndef USB_INFO_H +#define USB_INFO_H + +#include +#include + +namespace OHOS { +namespace USB { +static constexpr int32_t INVALID_BATT_INT_VALUE = -1; +static constexpr int32_t INVALID_BATT_TEMP_VALUE = 100; +static constexpr bool INVALID_BATT_BOOL_VALUE = true; + +struct FoundDevice { + int i; +}; + +struct USBPortStatusInfo { + int currentMode; + int currentPowerRole; + int currentDataRole; +}; + +struct USBPortInfo { + int id; + int supportedModes; + USBPortStatusInfo status; +}; + +struct USBDeviceInfo { + int status; + int busNum; + int devNum; +}; + +class UsbInfo { +public: + void SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) const {} + + void setDevInfoStatus(int status) + { + devInfo.status = status; + } + void setDevInfoBusNum(int busNum) + { + devInfo.busNum = busNum; + } + void setDevInfoDevNum(int devNum) + { + devInfo.devNum = devNum; + } + + int getDevInfoStatus() const + { + return devInfo.status; + } + int getDevInfoBusNum() const + { + return devInfo.busNum; + } + int getDevInfoDevNum() const + { + return devInfo.devNum; + } + +private: + // USBPortInfo port; + USBDeviceInfo devInfo; +}; +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_INFO_H diff --git a/interfaces/innerkits/native/include/usb_interface.h b/interfaces/innerkits/native/include/usb_interface.h new file mode 100644 index 00000000..5122d10c --- /dev/null +++ b/interfaces/innerkits/native/include/usb_interface.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_INTERFACE_H +#define USB_INTERFACE_H + +#include +#include +#include +#include +#include "usb_endpoint.h" + +namespace OHOS { +namespace USB { +class UsbInterface { +public: + UsbInterface(int32_t mId, + int32_t mProtocol, + int32_t mClass, + int32_t mSubClass, + int32_t mAlternateSetting, + std::string mName, + std::vector mEndpoints) + { + this->mId = mId; + this->mProtocol = mProtocol; + this->mClass = mClass; + this->mSubClass = mSubClass; + this->mAlternateSetting = mAlternateSetting; + this->mEndpoints = mEndpoints; + } + UsbInterface() {} + const std::string &GetName() const + { + return mName; + } + int32_t GetId() const + { + return mId; + } + int32_t GetClass() const + { + return mClass; + } + int32_t GetSubClass() const + { + return mSubClass; + } + int32_t GetAlternateSetting() const + { + return mAlternateSetting; + } + int32_t GetProtocol() const + { + return mProtocol; + } + int32_t GetEndpointCount() const + { + return mEndpoints.size(); + } + void GetEndpoint(uint32_t index, USBEndpoint &ep) const + { + if (index < mEndpoints.size()) { + ep = mEndpoints[index]; + } + } + std::vector &GetEndpoints() + { + return mEndpoints; + } + void SetEndpoints(const std::vector &eps) + { + mEndpoints = eps; + } + void SetId(int Val) + { + mId = Val; + } + void SetProtocol(int Val) + { + mProtocol = Val; + } + void SetClass(int Val) + { + mClass = Val; + } + void SetSubClass(int Val) + { + mSubClass = Val; + } + void SetAlternateSetting(int Val) + { + mAlternateSetting = Val; + } + void SetName(std::string Name) + { + mName = Name; + } + ~UsbInterface() {} + std::string ToString() const + { + std::string str; + std::ostringstream ss; + ss << "id=" << mId << "," + << "mName=" << mName << "," + << "iInterface=" << (int32_t)iInterface << "," + << "mClass=" << mClass << "," + << "mSubClass=" << mSubClass << "," + << "mProtocol=" << mProtocol << "," + << "mAlternateSetting=" << mAlternateSetting << "; "; + str = ss.str(); + ss.str(""); + for (size_t i = 0; i < mEndpoints.size(); ++i) { + const USBEndpoint &endpoint = mEndpoints[i]; + str += endpoint.ToString(); + } + return str; + } + void SetiInterface(uint8_t idx) + { + this->iInterface = idx; + } + uint8_t GetiInterface() + { + return this->iInterface; + } + +private: + int mId; + int mProtocol; + int mClass; + int mSubClass; + int mAlternateSetting; + std::string mName; + std::vector mEndpoints; + uint8_t iInterface; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_INTERFACE_H diff --git a/interfaces/innerkits/native/include/usb_port.h b/interfaces/innerkits/native/include/usb_port.h new file mode 100644 index 00000000..16b1991d --- /dev/null +++ b/interfaces/innerkits/native/include/usb_port.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_PORT_H +#define USB_PORT_H + +#include +#include +#include "usb_common.h" +#include "usb_port_status.h" + +namespace OHOS { +namespace USB { +// class UsbPort { +// public: +// UsbPort(uint32_t id, uint32_t supportedModes, +// UsbPortStatus *usbPortStatus) { +// mId = id; +// mSupportedModes = supportedModes; +// mUsbPortStatus = usbPortStatus; +// } +// UsbPort(); +// ~UsbPort(); + +// uint32_t getId() const { return mId; } +// uint32_t getSupportedModes() const { return mSupportedModes; } +// UsbPortStatus *getUsbPortStatus() const { return mUsbPortStatus; } + +// private: +// uint32_t mId = INVALID_USB_INT_VALUE; +// uint32_t mSupportedModes = INVALID_USB_INT_VALUE; +// UsbPortStatus *mUsbPortStatus; +// }; + +struct UsbPortStatus { + int32_t currentMode; + /** + * POWER_ROLE_NONE, + * POWER_ROLE_SOURCE, + * POWER_ROLE_SINK + */ + int32_t currentPowerRole; + /** + * DATA_ROLE_NONE, + * DATA_ROLE_HOST, + * DATA_ROLE_DEVICE + */ + int32_t currentDataRole; +}; +struct UsbPort { + int32_t id; + /** + * MODE_NONE + * MODE_DFP + * MODE_UFP + * MODE_DUAL + */ + int32_t supportedModes; + UsbPortStatus *usbPortStatus; +}; + +} // namespace USB +} // namespace OHOS +#endif // USB_PORT_H diff --git a/interfaces/innerkits/native/include/usb_port_status.h b/interfaces/innerkits/native/include/usb_port_status.h new file mode 100644 index 00000000..480e926b --- /dev/null +++ b/interfaces/innerkits/native/include/usb_port_status.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_PORT_STATUS_H +#define USB_PORT_STATUS_H + +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { +// class UsbPortStatus { +// public: +// UsbPortStatus(uint32_t currentMode, uint32_t currentPowerRole, +// uint32_t currentDataRole) { +// mCurrentMode = currentMode; +// mCurrentPowerRole = currentPowerRole; +// mCurrentDataRole = currentDataRole; +// } +// UsbPortStatus() { +// mCurrentMode = 0; +// mCurrentPowerRole = 0; +// mCurrentDataRole = 0; +// } +// ~UsbPortStatus(); + +// int32_t GetCurrentMode() const { return mCurrentMode; } + +// int32_t GetCurrentPowerRole() const { return mCurrentPowerRole; } + +// int32_t GetCurrentDataRole() const { return mCurrentDataRole; } + +// private: +// int32_t mCurrentMode; +// int32_t mCurrentPowerRole; +// int32_t mCurrentDataRole; +// }; +} // namespace USB +} // namespace OHOS + +#endif // USB_PORT_STATUS_H diff --git a/interfaces/innerkits/native/include/usb_request.h b/interfaces/innerkits/native/include/usb_request.h new file mode 100644 index 00000000..d840d97e --- /dev/null +++ b/interfaces/innerkits/native/include/usb_request.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_REQUEST_H +#define USB_REQUEST_H + +#include +#include "iusb_srv.h" +#include "securec.h" +#include "usb_device_pipe.h" +#include "usb_endpoint.h" + +namespace OHOS { +namespace USB { +class UsbSrvClient; +class UsbRequest { +public: + UsbRequest(); + int32_t Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint); + int32_t Queue(uint8_t *buffer, uint32_t length); + int32_t Free(); + int32_t Abort(); + void SetPipe(const USBDevicePipe &pipe) + { + this->pipe = pipe; + } + void SetEndpoint(const USBEndpoint &endpoint) + { + this->endpoint = endpoint; + } + void SetClientData(void *obj, uint32_t objLength) + { + clientData = obj; + clientLength = objLength; + } + void SetBuffer(uint8_t *buffer) + { + this->buffer = buffer; + } + void SetBufferData(uint8_t *data, uint32_t dataSize) + { + if (data == nullptr || dataSize == 0 || length < dataSize) { + return; + } + memcpy_s(buffer, length, data, dataSize); + } + void SetLength(uint8_t length) + { + this->length = length; + } + void *GetClientData() + { + return clientData; + } + const USBDevicePipe &GetPipe() const + { + return pipe; + } + const USBEndpoint &GetEndpoint() const + { + return endpoint; + } + uint32_t GetClientLength() const + { + return clientLength; + } + uint8_t *GetBuffer() const + { + return buffer; + } + uint32_t GetLength() const + { + return length; + } + +public: + USBDevicePipe pipe; + USBEndpoint endpoint; + void *clientData; + uint32_t clientLength; + uint8_t *buffer; + uint32_t length; + +private: + UsbSrvClient *usbClient; +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_REQUEST_H diff --git a/interfaces/innerkits/native/include/usb_srv_client.h b/interfaces/innerkits/native/include/usb_srv_client.h new file mode 100644 index 00000000..d10538ac --- /dev/null +++ b/interfaces/innerkits/native/include/usb_srv_client.h @@ -0,0 +1,111 @@ +/* + + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_USB_SRV_CLIENT_H +#define USBMGR_USB_SRV_CLIENT_H + +#include +#include +#include +#include +#include "iremote_object.h" +#include "iusb_srv.h" +#include "usb_device.h" +#include "usb_device_pipe.h" +#include "usb_port.h" +#include "usb_request.h" + +namespace OHOS { +namespace USB { + +const std::string MAXVERSION = "001"; +const std::string SUBVERSION = "001"; +const std::string DLPVERSION = "010"; +const std::string SEVVERSION = MAXVERSION + "." + SUBVERSION + "." + DLPVERSION; + +class UsbSrvClient final : public DelayedRefSingleton { + + DECLARE_DELAYED_REF_SINGLETON(UsbSrvClient) + +public: + DISALLOW_COPY_AND_MOVE(UsbSrvClient); + + int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); + int32_t HasRight(std::string deviceName); + int32_t RequestRight(std::string deviceName); + int32_t GetDevices(std::vector &deviceList); + int32_t GetPorts(std::vector &usbports); + int32_t GetSupportedModes(int32_t portId, int32_t &result); + int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); + int32_t GetCurrentFunctions(int32_t &funcs); + int32_t SetCurrentFunctions(int32_t funcs); + int32_t UsbFunctionsFromString(std::string funcs); + std::string UsbFunctionsToString(int32_t funcs); + int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); + int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); + int32_t BulkTransfer(USBDevicePipe &pip, + const USBEndpoint &endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout); + int32_t ControlTransfer(USBDevicePipe &pip, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout); + int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); + int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); + int32_t GetRawDescriptors(uint8_t *buffer, uint32_t length); + int32_t GetFileDescriptor(); + bool Close(const USBDevicePipe &pip); + int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); + + int32_t RequestInitialize(UsbRequest &request); + int32_t RequestFree(UsbRequest &request); + int32_t RequestAbort(UsbRequest &request); + int32_t RequestQueue(UsbRequest &request, uint8_t *buffer, uint32_t length); + + std::string GetVersion() + { + return SEVVERSION; + } + +private: + class UsbSrvDeathRecipient : public IRemoteObject::DeathRecipient { + public: + UsbSrvDeathRecipient() = default; + ~UsbSrvDeathRecipient() = default; + void OnRemoteDied(const wptr &remote); + + private: + DISALLOW_COPY_AND_MOVE(UsbSrvDeathRecipient); + }; + + static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); + int32_t Connect(); + sptr proxy_{nullptr}; + sptr deathRecipient_{nullptr}; + void ResetProxy(const wptr &remote); + std::mutex mutex_; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SRV_CLIENT_H diff --git a/interfaces/innerkits/native/src/usb_device.cpp b/interfaces/innerkits/native/src/usb_device.cpp new file mode 100644 index 00000000..3653a2b1 --- /dev/null +++ b/interfaces/innerkits/native/src/usb_device.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_device.h" + +namespace OHOS { +namespace USB { + +} // namespace USB +} // namespace OHOS diff --git a/interfaces/innerkits/native/src/usb_device_pipe.cpp b/interfaces/innerkits/native/src/usb_device_pipe.cpp new file mode 100644 index 00000000..f2821e43 --- /dev/null +++ b/interfaces/innerkits/native/src/usb_device_pipe.cpp @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_device_pipe.h" +#include "iusb_srv.h" +#include "usb_common.h" +#include "usb_device.h" +#include "usb_request.h" +#include "usb_srv_client.h" + +namespace OHOS { +namespace USB { +USBDevicePipe::USBDevicePipe() : usbClient(&UsbSrvClient::GetInstance()) {} +USBDevicePipe::USBDevicePipe(uint8_t busNum, uint8_t devAddr) + : busNum(busNum), devAddr(devAddr), usbClient(&UsbSrvClient::GetInstance()) +{ +} + +int32_t USBDevicePipe::Close() +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + int32_t ret = ERR_OK; + bool bSuccess = ((UsbSrvClient *)usbClient)->Close(*this); + if (!bSuccess) { + ret = ERR_INVALID_VALUE; + } + return ret; +} +int32_t USBDevicePipe::ClaimInterface(const UsbInterface &interface, bool force) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->ClaimInterface(*this, interface, force); +} +int32_t USBDevicePipe::ReleaseInterface(const UsbInterface &interface) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->ReleaseInterface(*this, interface); +} + +int32_t USBDevicePipe::BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t timeout) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + return ((UsbSrvClient *)usbClient)->BulkTransfer(*this, endpoint, buffer, length, timeout); +} + +int32_t USBDevicePipe::ControlTransfer(int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + return ((UsbSrvClient *)usbClient) + ->ControlTransfer(*this, requestType, request, value, index, buffer, length, timeout); +} +int32_t USBDevicePipe::SetConfiguration(const USBConfig &config) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->SetConfiguration(*this, config); +} +int32_t USBDevicePipe::SetInterface(const UsbInterface &interface) +{ + RETURN_IF_WITH_RET(usbClient == nullptr, ERR_NO_INIT); + return ((UsbSrvClient *)usbClient)->SetInterface(*this, interface); +} +void USBDevicePipe::SetBusNum(uint8_t busNum) +{ + this->busNum = busNum; +} +void USBDevicePipe::SetDevAddr(uint8_t devAddr) +{ + this->devAddr = devAddr; +} +uint8_t USBDevicePipe::GetBusNum() const +{ + return busNum; +} +uint8_t USBDevicePipe::GetDevAddr() const +{ + return devAddr; +} +} // namespace USB +} // namespace OHOS diff --git a/interfaces/innerkits/native/src/usb_request.cpp b/interfaces/innerkits/native/src/usb_request.cpp new file mode 100644 index 00000000..eba471ad --- /dev/null +++ b/interfaces/innerkits/native/src/usb_request.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_request.h" +#include "usb_common.h" +#include "usb_srv_client.h" + +namespace OHOS { +namespace USB { +UsbRequest::UsbRequest() + : clientData(nullptr), clientLength(0), buffer(nullptr), length(0), usbClient(&UsbSrvClient::GetInstance()) +{ +} +int32_t UsbRequest::Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) +{ + this->pipe = pipe; + this->endpoint = endpoint; + return usbClient->RequestInitialize(*this); +} + +int32_t UsbRequest::Queue(uint8_t *buffer, uint32_t length) +{ + this->buffer = buffer; + this->length = length; + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : buffer=%{public}p, length=%{public}d", __func__, buffer, length); + return usbClient->RequestQueue(*this, buffer, length); +} + +int32_t UsbRequest::Free() +{ + return usbClient->RequestFree(*this); +} + +int32_t UsbRequest::Abort() +{ + return usbClient->RequestAbort(*this); +} +} // namespace USB +} // namespace OHOS diff --git a/interfaces/innerkits/native/src/usb_srv_client.cpp b/interfaces/innerkits/native/src/usb_srv_client.cpp new file mode 100644 index 00000000..31ad54ae --- /dev/null +++ b/interfaces/innerkits/native/src/usb_srv_client.cpp @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_srv_client.h" +#include +#include "datetime_ex.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "usb_common.h" + +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device.h" + +namespace OHOS { +namespace USB { +#define USB_MAX_REQUEST_DATA_SIZE 1024 + +UsbSrvClient::UsbSrvClient() +{ + Connect(); +} +UsbSrvClient::~UsbSrvClient() {} + +void UsbSrvClient::PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << 二进制数据流[" << length << "字节] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_INNERKIT, "%{public}s", oss.str().c_str()); +} +int32_t UsbSrvClient::Connect() +{ + std::lock_guard lock(mutex_); + if (proxy_ != nullptr) { + return ERR_OK; + } + sptr sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (sm == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:fail to get Registry", __func__); + return E_GET_SYSTEM_ABILITY_MANAGER_FAILED; + } + sptr remoteObject_ = sm->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + if (remoteObject_ == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "GetSystemAbility failed."); + return E_GET_USB_SERVICE_FAILED; + } + proxy_ = iface_cast(remoteObject_); + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s :Connect UsbService ok.", __func__); + return ERR_OK; +} + +void UsbSrvClient::ResetProxy(const wptr &remote) +{ + std::lock_guard lock(mutex_); + RETURN_IF(proxy_ == nullptr); + auto serviceRemote = proxy_->AsObject(); + if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) { + serviceRemote->RemoveDeathRecipient(deathRecipient_); + proxy_ = nullptr; + } +} + +void UsbSrvClient::UsbSrvDeathRecipient::OnRemoteDied(const wptr &remote) +{ + if (remote == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbSrvDeathRecipient::OnRemoteDied failed, remote is nullptr."); + return; + } + UsbSrvClient::GetInstance().ResetProxy(remote); + USB_HILOGI(MODULE_USB_INNERKIT, "UsbSrvDeathRecipient::Recv death notice."); +} + +int32_t UsbSrvClient::OpenDevice(const UsbDevice &device, USBDevicePipe &pipe) +{ + int32_t ret; + USB_HILOGI(MODULE_USB_INNERKIT, " Calling OpenDevice Start!"); + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->OpenDevice(device.GetBusNum(), device.GetDevAddr()); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + return ret; + } + + pipe.SetBusNum(device.GetBusNum()); + pipe.SetDevAddr(device.GetDevAddr()); + return ERR_OK; +} + +int32_t UsbSrvClient::HasRight(std::string deviceName) +{ + int32_t ret = 0; + USB_HILOGI(MODULE_USB_INNERKIT, " Calling HasRight Start!"); + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->HasRight(deviceName); + if (ret) { + USB_HILOGI(MODULE_USB_INNERKIT, " Calling HasRight False!"); + } + return ret; +} + +int32_t UsbSrvClient::RequestRight(std::string deviceName) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->RequestRight(deviceName); + if (ret) { + USB_HILOGI(MODULE_USB_INNERKIT, " Calling RequestRight False!"); + } + return ret; +} + +int32_t UsbSrvClient::GetDevices(std::vector &deviceList) +{ + int32_t ret; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->GetDevices(deviceList); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s list size = %{public}d!", __func__, deviceList.size()); + return ret; +} + +int32_t UsbSrvClient::GetCurrentFunctions(int32_t &funcs) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + ret = proxy_->GetCurrentFunctions(funcs); + if (ret < ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + USB_HILOGI(MODULE_USB_INNERKIT, " Calling GetCurrentFunctions Success!"); + return ret; +} +int32_t UsbSrvClient::SetCurrentFunctions(int32_t funcs) +{ + RETURN_IF_WITH_RET(Connect() != ERR_OK, false); + int32_t ret = proxy_->SetCurrentFunctions(funcs); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + return ret; + } + USB_HILOGI(MODULE_USB_INNERKIT, " Calling SetCurrentFunctions Success!"); + return ret; +} + +int32_t UsbSrvClient::UsbFunctionsFromString(std::string funcs) +{ + int32_t result = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + result = proxy_->UsbFunctionsFromString(funcs); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling UsbFunctionsFromString Success!"); + return result; +} + +std::string UsbSrvClient::UsbFunctionsToString(int32_t funcs) +{ + std::string result; + RETURN_IF_WITH_RET(Connect() != ERR_OK, result); + result = proxy_->UsbFunctionsToString(funcs); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling UsbFunctionsToString Success!"); + return result; +} + +int32_t UsbSrvClient::GetPorts(std::vector &usbports) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling GetPorts"); + ret = proxy_->GetPorts(usbports); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + return ret; +} + +int32_t UsbSrvClient::GetSupportedModes(int32_t portId, int32_t &result) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling GetSupportedModes"); + ret = proxy_->GetSupportedModes(portId, result); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + return ret; +} + +int32_t UsbSrvClient::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + int32_t ret = 0; + RETURN_IF_WITH_RET(Connect() != ERR_OK, ERR_NO_INIT); + USB_HILOGI(MODULE_USB_INNERKIT, " Calling SetPortRole"); + ret = proxy_->SetPortRole(portId, powerRole, dataRole); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s failed ret = %{public}d!", __func__, ret); + } + return ret; +} + +int32_t UsbSrvClient::ClaimInterface(USBDevicePipe &pipe, const UsbInterface &interface, bool force) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + ret = proxy_->ClaimInterface(pipe.GetBusNum(), pipe.GetDevAddr(), interface.GetId()); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + return ret; +} +int32_t UsbSrvClient::ReleaseInterface(USBDevicePipe &pipe, const UsbInterface &interface) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + ret = proxy_->ReleaseInterface(pipe.GetBusNum(), pipe.GetDevAddr(), interface.GetId()); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + return ret; +} +int32_t UsbSrvClient::BulkTransfer(USBDevicePipe &pipe, + const USBEndpoint &endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ret; + } + PrintBuffer("UsbSrvClient::BulkTransfer", (const uint8_t *)buffer, length); + if (USB_ENDPOINT_DIR_IN == endpoint.GetDirection()) { + ret = proxy_->BulkTransferRead(pipe.GetBusNum(), pipe.GetDevAddr(), endpoint.GetInterfaceId(), + endpoint.GetAddress(), buffer, length, timeout); + } else if (USB_ENDPOINT_DIR_OUT == endpoint.GetDirection()) { + ret = proxy_->BulkTransferWrite(pipe.GetBusNum(), pipe.GetDevAddr(), endpoint.GetInterfaceId(), + endpoint.GetAddress(), buffer, length, timeout); + } + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + return ret; +} +int32_t UsbSrvClient::ControlTransfer(USBDevicePipe &pipe, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + if ((length > 0) && (!buffer)) { + return ret; + } + ret = proxy_->ControlTransfer(pipe.GetBusNum(), pipe.GetDevAddr(), requestType, request, value, index, buffer, + length, timeout); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : failed width ret = %{public}d !", __func__, ret); + } + + return ret; +} +int32_t UsbSrvClient::SetConfiguration(USBDevicePipe &pipe, const USBConfig &config) +{ + int32_t ret = ERR_OK; + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + ret = proxy_->SetActiveConfig(pipe.GetBusNum(), pipe.GetDevAddr(), config.GetId()); + return ret; +} +int32_t UsbSrvClient::SetInterface(USBDevicePipe &pipe, const UsbInterface &interface) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_NO_INIT); + return proxy_->SetInterface(pipe.GetBusNum(), pipe.GetDevAddr(), interface.GetId(), + interface.GetAlternateSetting()); +} +int32_t UsbSrvClient::GetRawDescriptors(uint8_t *buffer, uint32_t length) +{ + length = 0; + return 0; +} +int32_t UsbSrvClient::GetFileDescriptor() +{ + return 0; +} + +bool UsbSrvClient::Close(const USBDevicePipe &pipe) +{ + int32_t ret = ERR_OK; + RETURN_IF_WITH_RET(proxy_ == nullptr, false); + ret = proxy_->Close(pipe.GetBusNum(), pipe.GetDevAddr()); + return (ret == ERR_OK); +} + +int32_t UsbSrvClient::PipeRequestWait(USBDevicePipe &pipe, int64_t timeout, UsbRequest &req) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + int32_t ret = ERR_OK; + uint32_t length = USB_MAX_REQUEST_DATA_SIZE; + uint8_t *buffer = new uint8_t[length]; + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + uint32_t clientLength = sizeof(UsbRequest); + uint8_t *clientObj = new uint8_t[clientLength]; + ret = proxy_->RequestWait(pipe.GetBusNum(), pipe.GetDevAddr(), timeout, clientObj, clientLength, buffer, length); + if (ret != ERR_OK) { + delete[] buffer; + delete[] clientObj; + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s :failed width ret = %{public}d.", __func__, ret); + return ret; + } + + PrintBuffer("UsbSrvClient::PipeRequestWait out", (const uint8_t *)clientObj, clientLength); + UsbRequest *sendReq = reinterpret_cast(clientObj); + if (sendReq == nullptr || clientLength == 0) { + delete[] buffer; + delete[] clientObj; + return ERR_INVALID_VALUE; + } + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : buffer=%{public}p, length=%{public}d", __func__, sendReq->GetBuffer(), + sendReq->GetLength()); + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : clientData=%{public}p, ClientLength=%{public}d", __func__, + sendReq->GetClientData(), sendReq->GetClientLength()); + + req = *sendReq; + if (length > 0) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : buffer=%{public}p, length=%{public}d.", __func__, req.GetBuffer(), + req.GetLength()); + req.SetLength(length); + req.SetBuffer(buffer); + } else { + delete[] buffer; + } + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s : ok", __func__); + delete[] clientObj; + return ERR_OK; +} + +int32_t UsbSrvClient::RequestInitialize(UsbRequest &request) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &endpoint = request.GetEndpoint(); + return proxy_->ClaimInterface(pipe.GetBusNum(), pipe.GetDevAddr(), endpoint.GetInterfaceId()); +} + +int32_t UsbSrvClient::RequestFree(UsbRequest &request) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &ep = request.GetEndpoint(); + return proxy_->ReleaseInterface(pipe.GetBusNum(), pipe.GetDevAddr(), ep.GetInterfaceId()); +} + +int32_t UsbSrvClient::RequestAbort(UsbRequest &request) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &ep = request.GetEndpoint(); + return proxy_->RequestCancel(pipe.GetBusNum(), pipe.GetDevAddr(), ep.GetInterfaceId(), ep.GetAddress()); +} + +int32_t UsbSrvClient::RequestQueue(UsbRequest &request, uint8_t *buffer, uint32_t length) +{ + RETURN_IF_WITH_RET(proxy_ == nullptr, ERR_INVALID_VALUE); + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + const USBDevicePipe &pipe = request.GetPipe(); + const USBEndpoint &ep = request.GetEndpoint(); + return proxy_->RequestQueue(pipe.GetBusNum(), pipe.GetDevAddr(), ep.GetInterfaceId(), ep.GetAddress(), &request, + sizeof(UsbRequest), const_cast(buffer), length); +} +} // namespace USB +} // namespace OHOS diff --git a/interfaces/kits/java/BUILD.gn b/interfaces/kits/java/BUILD.gn new file mode 100644 index 00000000..f3a90d8c --- /dev/null +++ b/interfaces/kits/java/BUILD.gn @@ -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. + +import("//build/config/ohos/rules.gni") +import("//build/ohos.gni") + +USB_MANAGER_ROOT = "//base/usb/usb_manager" +ADAPTER_DIR = "$USB_MANAGER_ROOT/adapter" +INTERFACES_ROOT = "$USB_MANAGER_ROOT/interfaces" + +java_library("usb_manager_java") { + java_files = [ + "$INTERFACES_ROOT/kits/java/ohos/usb/USBLoggerFactory.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBDevice.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBDevicePipe.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBInterface.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBCore.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBRequest.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBConfig.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/USBEndpoint.java", + "$INTERFACES_ROOT/kits/java/ohos/usb/package-info.java", + ] + + deps = [ "//utils/java:utils_maple_java" ] + + external_deps = [ + "appexecfwk:appexecfwk_java", + "appexecfwk:appexecfwk_java_maple", + "hilog:hilog_maple_java", + "samgr:samgr_java", + "samgr:samgr_java_maple", + ] + + subsystem_name = "usb" + part_name = "usb_manager" +} + +ohos_maple_java("usb_manager_maple_java") { + deps = [ ":usb_manager_java" ] + external_deps = [ "hilog:hilog_maple_java" ] + so_name = "usb_manager_java" + part_name = "usb_manager" + output_dir = "$root_build_dir/usb/" +} diff --git a/interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java b/interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java new file mode 100644 index 00000000..50adf081 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/IUSBDevicePipeController.java @@ -0,0 +1,42 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.RemoteException; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; + +public interface IUSBDevicePipeController extends IRemoteBroker { + + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int length, int timeout) throws RemoteException; + + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout) throws RemoteException; + + boolean claimInterface(USBInterface interfaceObj, boolean force) throws RemoteException; + + void close() throws RemoteException; + + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int offset, int length, int timeout) throws RemoteException; + + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) throws RemoteException; + + int getFileDescriptor() throws RemoteException; + + byte[] getRawDescriptors() throws RemoteException; + + String getSerial() throws RemoteException; + + boolean releaseInterface(USBInterface interfaceObj) throws RemoteException; + + USBRequest requestWait(long timeout) throws TimeoutException, RemoteException; + + USBRequest requestWait() throws RemoteException; + + boolean setConfiguration(USBConfig config) throws RemoteException; + + boolean setInterface(USBInterface interfaceObj) throws RemoteException; + + boolean openByInt(String name, int fd) throws RemoteException; + +} diff --git a/interfaces/kits/java/ohos/usb/IUSBRequestController.java b/interfaces/kits/java/ohos/usb/IUSBRequestController.java new file mode 100644 index 00000000..990baa03 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/IUSBRequestController.java @@ -0,0 +1,28 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.RemoteException; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; + +import java.util.List; + +public interface IUsbRequestController extends IRemoteBroker { + + void abort() throws RemoteException; + + void free() throws RemoteException; + + boolean initialize(USBDevicePipe connection, USBEndpoint ep) throws RemoteException; + + boolean queue(ByteBuffer buffer) throws RemoteException; + + boolean queue(ByteBuffer buffer, int length) throws RemoteException; + + void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) throws RemoteException; + + void setClientData(Object data) throws RemoteException; + +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/IUsbCoreController.java b/interfaces/kits/java/ohos/usb/IUsbCoreController.java new file mode 100644 index 00000000..13d34442 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/IUsbCoreController.java @@ -0,0 +1,43 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.RemoteException; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; + +import java.util.List; + +public interface IUsbCoreController extends IRemoteBroker { + + + HashMap getDevices() throws RemoteException; + + USBDevicePipe connectDevice(USBDevice device) throws RemoteException; + + boolean hasRight(USBDevice device) throws RemoteException; + + void requestRight(USBDevice device, String intentName) throws RemoteException; + + String usbFunctionsToString(long functions) throws RemoteException; + + long usbFunctionsFromString(String functions) throws RemoteException; + + String getCurrentFunctions() throws RemoteException; + + void setCurrentFunctions(long functions) throws RemoteException; + + void setCurrentFunction(String functions, boolean usbDataUnlocked) throws RemoteException; + + void setHdcEnabled(boolean enable) throws RemoteException; + + void addFunction(String functions, String function) throws RemoteException; + + void removeFunction(String functions, String function) throws RemoteException; + + void setPortRoles(int powerRole,int dataRole) throws RemoteException; + + UsbPortStatus getPortStatus(USBPort port) throws RemoteException; + +} diff --git a/interfaces/kits/java/ohos/usb/USBConfig.java b/interfaces/kits/java/ohos/usb/USBConfig.java new file mode 100644 index 00000000..4d43cad6 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBConfig.java @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Gets information about USB configuration. + * + *

When using this class, a USB device is attached to a USB host. According to the USB protocol specifications, + * a device contains one or more configurations, a configuration contains one or more interfaces, and an interface + * contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBConfig { + private int id; + + private int maxPower; + + private String name; + + private boolean isRemoteWakeup; + + private boolean isSelfPowered; + + private USBInterface[] interfaces; + + public USBConfig(int id, int maxPower, String name, boolean isRemoteWakeup, boolean isSelfPowered) { + this.id = id; + this.maxPower = maxPower; + this.name = name; + this.isRemoteWakeup = isRemoteWakeup; + this.isSelfPowered = isSelfPowered; + } + + /** + * Get a {@code USBInterface} object by index in the {@code USBConfig}. + * + * @param index Indicates the {@code USBInterface} object index in the {@code USBConfig}. + * @return Returns the {@code USBInterface} object . + * @since 5 + */ + public USBInterface getInterface(int index) { + if (interfaces == null || index < 0 || index >= interfaces.length) { + return null; + } + + return interfaces[index]; + } + + /** + * Sets a local {@code USBInterface} object. + * + * @param interfaces Indicates a local {@code USBInterface} object. + * @since 5 + */ + public void setInterfaces(USBInterface[] interfaces) { + this.interfaces = interfaces; + } + + /** + * Get the number of interfaces of the configuration. + * + * @return Returns the number of interfaces of the configuration. + * @since 5 + */ + public int getInterfaceCount() { + if (interfaces == null) { + return 0; + } + + return interfaces.length; + } + + /** + * Get the current configuration ID. + * + * @return Returns the current configuration ID. + * @since 5 + */ + public int getId() { + return id; + } + + /** + * Get the maximum power consumption of the current configuration. + * + * @return Returns the maximum power consumption. + * @since 5 + */ + public int getMaxPower() { + return maxPower; + } + + /** + * Get the current configuration name. + * + * @return Returns the current configuration name. + * @since 5 + */ + public String getName() { + return name; + } + + /** + * Checks whether the current configuration supports remote wakeup. + * + * @return Returns {@code true} if the configuration supports remote wakeup; returns {@code false} otherwise. + * @since 5 + */ + public boolean isRemoteWakeup() { + return isRemoteWakeup; + } + + /** + * Checks whether the configuration supports an independent power source. + * + * @return Returns {@code true} if the configuration supports an independent power source; + * returns {@code false} otherwise. + * @since 5 + */ + public boolean isSelfPowered() { + return isSelfPowered; + } +} + diff --git a/interfaces/kits/java/ohos/usb/USBCore.java b/interfaces/kits/java/ohos/usb/USBCore.java new file mode 100644 index 00000000..2b9a5dbf --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBCore.java @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.StringJoiner; + +import ohos.app.Context; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * This class allows you to obtain USB devices currently attached, obtain USB device status, + * and communicate with USB devices. + * Currently, only the host mode is supported. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBCore { + + /** + * A constructor used to create a {@code USBCore}. + * + * @since 5 + */ + public USBCore() { + + } + + /** + * Returns the hash map of USB devices. + * + *

The hash map contains devices and their names. Applications can traverse USB devices in the hash map to + * perform operations on the devices. For details on the operations, see {@link ohos.usb.USBDevice}. + * + * @return Returns a hash map containing devices and their names. + * @since 5 + */ + public HashMap getDevices() { + HashMap results = new HashMap(); + native_get_devices(results); + return results; + } + + public HashMap getPeripherals() { + + } + + /** + * Opens a USB device based on device information returned by {@link ohos.usb.USBCore#getDevices}. + * + *

A {@link ohos.usb.USBDevicePipe} instance is returned. Data transfer is performed based on the + * instance. + * + * @param device Indicates a {@link ohos.usb.USBDevicePipe} instance. + * @return Returns a {@link ohos.usb.USBDevicePipe} instance. + * @since 5 + */ + public USBDevicePipe connectDevice(USBDevice device) { + return native_connnect_device(device); + } + + /** + * Returns true if the caller has right to access the device. + * + * @param device to check right for + * @return {@code true} if caller has right to access this device + * @since 5 + */ + public boolean hasRight(USBDevice device) { + return native_has_right(device); + } + + /** + * Requests temporary permission for the given package to access the device. + * + * @param device Device to request permissions for + * @param intentName Intent for returning result + */ + public void requestRight(USBDevice device, String intentName) { + native_request_right(device, intentName); + } + + /** + * Converts the given function mask to string. Maintains ordering with respect to init scripts. + * + * @param functions the usb functions long value + * @return String representation of given mask + * @since 5 + */ + public String usbFunctionsToString(long functions) { + return native_usb_function_to_string(functions); + } + + /** + * Parses a string of usb functions that are comma separated. + * + * @param functions the usb functions + * @return A mask of all valid functions in the string + * @since 5 + */ + public long usbFunctionsFromString(String functions) { + return native_usb_function_from_string(functions); + } + + public String getCurrentFunctions() { + return native_get_current_functions(); + } + + public void setCurrentFunctions(long functions) { + native_set_current_functions(functions); + } + + public void setCurrentFunction(String functions, boolean usbDataUnlocked) { + native_set_current_function(functions, usbDataUnlocked); + } + + public void setHdcEnabled(boolean enable) { + native_set_hdc_enabled(enable); + } + + public void addFunction(String functions, String function) { + native_add_function(functions, function); + } + + public void removeFunction(String functions, String function) { + native_remove_function(functions, function); + } + + public void setPortRoles(int powerRole,int dataRole) { + native_set_port_roles(powerRole, dataRole); + } + + public UsbPortStatus getPortStatus(USBPort port) { + return native_get_port_status(port); + } + + private native void native_get_devices(HashMap results); + + private native USBDevicePipe native_connnect_device(USBDevice device); + + private native boolean native_has_right(USBDevice device); + + private native void native_request_right(USBDevice device, String intentName); + + private native String native_usb_function_to_string(long functions); + + private native long native_usb_function_from_string(String functions); + + private native String native_get_current_functions(); + + private native void native_set_current_functions(long functions); + + private native void native_set_current_function(String functions, boolean usbDataUnlocked); + + private native void native_set_hdc_enabled(boolean enable); + + private native void native_add_function(String functions, String function); + + private native void native_remove_function(String functions, String function); + + private native void native_set_port_roles(int powerRole,int dataRole); + + private native UsbPortStatus native_get_port_status(USBPort port); +} + + + + + + diff --git a/interfaces/kits/java/ohos/usb/USBDevice.java b/interfaces/kits/java/ohos/usb/USBDevice.java new file mode 100644 index 00000000..428c24e7 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBDevice.java @@ -0,0 +1,290 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Get configuration information of a USB device. For details on the information + * structure, see USB protocol specifications. + * + *

+ * When using this class, a USB device is attached to a USB host. According to + * the USB protocol specifications, a device contains one or more + * configurations, a configuration contains one or more interfaces, and an + * interface contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBDevice { + + private final int deviceId; + + private final String deviceName; + + private final String manufacturerName; + + private final String productName; + + private final String version; + + private final String serialNumber; + + private final int vendorId; + + private final int productId; + + private final int classId; + + private final int subclass; + + private final int protocol; + + private USBConfig[] configs; + + private USBInterface[] interfaces; + + /** + * A constructor used to create a {@code USBDevice}. + * + * @param deviceId Indicates the id of the USB device, which is usually determined by the low layer. + * @param deviceName Indicates the name of the USB device, which is usually determined by the low layer. + * @param vendorId Indicates the vendor ID of the USB device, which is assigned by the USB-IF. + * @param productId Indicates the product ID of the USB device, which is assigned by the USB-IF. + * @param classId Indicates the class code of the USB device, which is assigned by the USB-IF. + * @param subClassId Indicates the subclass code of the USB device, which is assigned by the USB-IF. + * @param protocolId Indicates the protocol code of the USB device, which is assigned by the USB-IF. + * @param manufacturerName Indicates the manufacturer name of the USB device. + * @param productName Indicates the product name of the USB device. + * @param version Indicates the version number of the USB device. + * @param serialNumber Indicates the serial number of the USB device. + * + * @since 5 + */ + public USBDevice(int deviceId, String deviceName, int vendorId, int productId, int classId, int subClassId, int protocolId, + String manufacturerName, String productName, String version, String serialNumber) { + this.deviceId = deviceId; + this.deviceName = deviceName; + this.vendorId = vendorId; + this.productId = productId; + this.classId = classId; + this.subclass = subClassId; + this.protocol = protocolId; + this.manufacturerName = manufacturerName; + this.productName = productName; + this.version = version; + this.serialNumber = serialNumber; + } + + /** + * Gets the {@code Class} field of a USB device. + * + * @return Returns the {@code Class} field. + * @since 5 + */ + public int getDeviceClass() { + return classId; + } + + /** + * Gets the {@code Id} field of a USB device. + * + * @return Returns the {@code Id} field. + * @since 5 + */ + public int getDeviceId() { + return deviceId; + } + + /** + * Get the {@code Name} field of a USB device. + * + * @return Returns the {@code Name} field. + * @since 5 + */ + public String getDeviceName() { + return deviceName; + } + + /** + * Get the {@code Name} field of a USB device. + * + * @param id Id of the USB device. + * @return Returns the {@code Name} field. + * @since 5 + */ + public static String getDeviceName(int id) { + return "default_dev"; + } + + /** + * Get the {@code Protocol} field of a USB device. + * + * @return Returns the {@code Protocol} field. + * @since 5 + */ + public int getDeviceProtocol() { + return protocol; + } + + /** + * Get the {@code SubClass} field of a USB device. + * + * @return Returns the {@code SubClass} field. + * @since 5 + */ + public int getDeviceSubclass() { + return subclass; + } + + /** + * Sets interfaces for a local object. + * + * @param interfaces Indicates the array of a {@code USBInterface} object. + * @since 5 + */ + public void setInterfaces(USBInterface[] interfaces) { + this.interfaces = interfaces; + } + + /** + * Get an interface instance of this device by index. + * + * @param index Indicates the interface index. + * @return Returns the interface. + * @since 5 + */ + public USBInterface getInterface(int index) { + if (interfaces == null || index < 0 || index >= interfaces.length) { + return null; + } + return interfaces[index]; + } + + /** + * Get the number of interfaces of this device. + * + * @return Returns the number of interfaces. + * @since 5 + */ + public int getInterfaceCount() { + if (interfaces == null) { + return 0; + } + + return interfaces.length; + } + + /** + * Get the manufacturer string of this device. + * + * @return Returns the manufacturer string of this device. + * @since 5 + */ + public String getManufacturerName() { + return manufacturerName; + } + + /** + * Get the {@code ProductId} field of a USB device. + * + * @return Returns the {@code ProductId} field. + * @since 5 + */ + public int getProductId() { + return productId; + } + + /** + * Get the {@code ProductName} field of a USB device. + * + * @return Returns the {@code ProductName} field. + * @since 5 + */ + public String getProductName() { + return productName; + } + + /** + * Get the {@code SerialNumber} field of a USB device. + * + * @return Returns the {@code SerialNumber} field. + * @since 5 + */ + public String getSerialNumber() { + return serialNumber; + } + + /** + * Get the {@code VendorId} field of a USB device. + * + * @return Returns the {@code VendorId} field. + * @since 5 + */ + public int getVendorId() { + return vendorId; + } + + /** + * Get the {@code Version} field of a USB device. + * + * @return Returns the {@code Version} field. + * @since 5 + */ + public String getVersion() { + return version; + } + + /** + * Get a {@code USBConfig} instance of this device by index. + * + * @param index Indicates the configuration index. + * @return Returns the corresponding {@code USBConfig} object. + * @since 5 + */ + public USBConfig getConfiguration(int index) { + if (configs == null || index < 0 || index >= configs.length) { + return null; + } + return configs[index]; + } + + /** + * Get the number of configurations of this device. + * + * @return Returns the number of configurations. + * @since 5 + */ + public int getConfigurationCount() { + if (configs == null) { + return 0; + } + return configs.length; + } + + /** + * Sets configurations of this device. + * + * @param configs Indicates the array of a {@code USBConfig} object. + * @since 5 + */ + public void setConfigurations(USBConfig[] configs) { + this.configs = configs; + } +} diff --git a/interfaces/kits/java/ohos/usb/USBDevicePipe.java b/interfaces/kits/java/ohos/usb/USBDevicePipe.java new file mode 100644 index 00000000..e8ebb792 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBDevicePipe.java @@ -0,0 +1,263 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import java.util.concurrent.TimeoutException; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Provides methods for transferring data and control messages between USB devices. + * + *

Applications can get device descriptors from {@link ohos.usb.USBDevice} to operate the USB devices. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBDevicePipe { + /** + * Indicates a {@code USBDevice}. + */ + public final USBDevice device; + + public USBDevicePipe(USBDevice device) { + this.device = device; + } + + /** + * Performs bulk data transfer on a specified endpoint. + * + * @param epObj the endpoint instance. + * @param buffer Indicates the buffer for bulk data transfer. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. The value {@code 0} indicates that the + * transfer never times out. + * @return Returns a value greater than or equal to {@code 0} if the data transfer is successful; returns a + * negative value otherwise. + * @since 5 + */ + public int bulkTransfer(USBEndpoint epObj, byte[] buffer, int length, int timeout) { + return native_bulk_transfer(epObj, buffer, 0, length, timeout); + } + + /** + * Performs bulk data transfer on a specified endpoint. + * + * @param epObj the endpoint instance. + * @param buffer Indicates the buffer for bulk data transfer. + * @param offset Indicates the offset from first byte in the buffer. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. The value {@code 0} indicates that the + * transfer never times out. + * @return Returns a value greater than or equal to {@code 0} if the data transfer is successful; returns a negative + * value otherwise. + * @since 5 + */ + public int bulkTransfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout) { + return native_bulk_transfer(epObj, buffer, offset, length, timeout); + } + + /** + * Claims that a specified interface is exclusively occupied. This must be done before transferring data to the + * endpoint of the {@code interfaceObj} interface. + * + * @param interfaceObj Indicates the interface to be exclusively occupied. + * @param force Indicates whether the kernel driver is disconnected. The value {@code true} indicates that the + * kernel driver is disconnected. The value {@code false} indicates that the kernel driver is connected + * @return Returns {@code true} if the claim is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean claimInterface(USBInterface interfaceObj, boolean force) { + return native_claim_interface(interfaceObj, force); + } + + /** + * Closes the request. + */ + public void close() { + native_close(); + } + + /** + * Performs control message transfer on endpoint zero. + * + * @param requestType Indicates the type of request initiated for control message transfer. For details, + * see USB protocol specifications. If the most significant bit is 1, data is written from the host. If the most + * significant bit is 0, data is written into the host. + * @param request Indicates the request ID. + * @param value Indicates the value of the transfer. + * @param index Indicates the index of the transfer. + * @param buffer Indicates the buffer from which data is to be transferred. + * @param offset Indicates the offset address starting from 0 in the data buffer. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. + * @return Returns the number of bytes transferred; returns {@code 0} if the transfer fails. + * @since 5 + */ + public int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int offset, + int length, int timeout) { + return native_control_transfer(requestType, request, value, index, buffer, offset, length, timeout); + } + + /** + * Performs control message transfer on endpoint zero. + * + * @param requestType Indicates the type of request initiated for control message transfer. For details, see USB + * protocol specifications. If the most significant bit is 1, data is written from the host. If the most + * significant bit is 0, data is written into the host. + * @param request Indicates the request ID. + * @param value Indicates the value of the transfer. + * @param index Indicates the index of the transfer. + * @param buffer Indicates the buffer from which data is to be transferred. + * @param length Indicates the length of the data to transfer. + * @param timeout Indicates the transfer timeout period, in millisecond. + * @return Returns the number of bytes transferred; returns {@code 0} if the transfer fails. + * @since 5 + */ + public int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, + int timeout) { + return controlTransfer(requestType, request, value, index, buffer, 0, length, timeout); + } + + /** + * Get the file descriptor. + * + * @return Returns the file descriptor. + * @since 5 + */ + public int getFileDescriptor() { + return native_get_file_descriptor(); + } + + /** + * Get the original USB descriptors. + * + * @return Returns the original USB descriptors. + * @since 5 + */ + public byte[] getRawDescriptors() { + return native_get_raw_descriptors(); + } + + /** + * Get the serial number, in string. + * + * @return Returns the serial number. + * @since 5 + */ + public String getSerial() { + return native_get_serial(); + } + + /** + * Claims that a specified interface is released. + * + * @param interfaceObj Indicates the interface to release. + * @return Returns {@code true} if the release is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean releaseInterface(USBInterface interfaceObj) { + return native_release_interface(interfaceObj); + } + + /** + * Waits for the result returned by the {@link ohos.usb.USBRequest#queue} method. This is an + * asynchronous + * method call. If the operation times out, a timeout exception is thrown. + * + * @param timeout Indicates the timeout period, in milliseconds. The value {@code 0} indicates no waiting. + * @return Returns a {@link ohos.usb.USBRequest} object. + * @throws TimeoutException Throws this exception if the specified timeout elapses. + * @since 5 + */ + public USBRequest requestWait(long timeout) throws TimeoutException { + return native_request_wait(timeout); + } + + /** + * Waits for the result returned by the {@link ohos.usb.USBRequest#queue} method. + * + * @return Returns a {@link ohos.usb.USBRequest} object. + * @since 5 + */ + public USBRequest requestWait() { + return native_request_wait(); + } + + /** + * Sets the current USB configuration. + * + * @param config The config instance. + * @return Returns {@code true} if the setting is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean setConfiguration(USBConfig config) { + return native_set_configuration(config); + } + + /** + * Sets the current USB interface. + * + * @param interfaceObj Indicates a {@code USBInterface} object. + * @return Returns {@code true} if the setting is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean setInterface(USBInterface interfaceObj) { + return native_set_interface(interfaceObj); + } + + /** + * Performs an open process on the file descriptor. + * + * @param name Indicates the device name. + * @param fd Indicates the file descriptor of the device connection. + * @return Returns the result of the open process. + */ + public boolean openByInt(String name, int fd) { + return native_open_by_int(name, fd); + } + + private native int native_bulk_transfer(USBEndpoint epObj, byte[] buffer, int length, int timeout); + + private native int native_bulk_transfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout); + + private native boolean native_claim_interface(USBInterface interfaceObj, boolean force); + + private native void native_close(); + + private native int native_control_transfer(int requestType, int request, int value, int index, byte[] buffer, int offset, int length, int timeout); + + private native int native_get_file_descriptor(); + + private native byte[] native_get_raw_descriptors(); + + private native String native_get_serial(); + + private native boolean native_release_interface(USBInterface interfaceObj); + + private native USBRequest native_request_wait(long timeout); + + private native USBRequest native_request_wait(); + + private native boolean native_set_configuration(USBConfig config); + + private native boolean native_set_interface(USBInterface interfaceObj); + + private native boolean native_open_by_int(String name, int fd); + +} diff --git a/interfaces/kits/java/ohos/usb/USBDevicePipeController.java b/interfaces/kits/java/ohos/usb/USBDevicePipeController.java new file mode 100644 index 00000000..88904b7c --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBDevicePipeController.java @@ -0,0 +1,142 @@ +package ohos.usb; + +import java.util.concurrent.TimeoutException; + +import ohos.aafwk.ability.Ability; +import ohos.aafwk.ability.Lifecycle; +import ohos.app.Context; +import ohos.event.intentagent.IntentAgent; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.SystemCap; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; +import ohos.nfc.tag.TagInfo; + +@SystemCap("SystemCapability.Communication.USB") +public class USBDevicePipeController { + + private static UsbDevicePipeController sUsbDevicePipeController; + private UsbDevicePipeControllerProxy mUsbDevicePipeControllerProxy; + private Context mContext; + + /** + * A callback to be invoked when the system finds a tag while the foreground page is operating in reader mode. + * + */ + public interface ReaderModeCallback extends IRemoteBroker { + /** + * Indicates the transaction code of the callback specific to inter-process communication (IPC). + */ + int TRANSACTION_ON_CALLBACK = 1; + + /** + * Called when a tag is discovered. + * + * @param tagInfo Indicates information of the discovered tag. + * @since 4 + */ + void onTagDiscovered(TagInfo tagInfo); + } + + /** + * Provides ReaderModeCallback for communicate with remote. + * + * @since 4 + */ + public class ReaderModeCallbackStub extends RemoteObject implements ReaderModeCallback { + private ReaderModeCallback callback; + + public ReaderModeCallbackStub(ReaderModeCallback callback) { + super(); + this.callback = callback; + } + + private void readInterfaceToken(Parcel data) { + data.readInt(); + data.readInt(); + data.readString(); + } + + @Override + public boolean onRemoteRequest( + int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { + HiLog.debug(LABEL, "call ReaderModeCallbackStub's onTransact"); + + switch (code) { + case TRANSACTION_ON_CALLBACK: { + readInterfaceToken(data); + + TagInfo tagInfo = new TagInfo(null, null, null, 0); + if (tagInfo instanceof Sequenceable) { + data.readSequenceable((Sequenceable) tagInfo); + } + onTagDiscovered(tagInfo); + + // writeNoException + reply.writeInt(0); + break; + } + default: { + + return super.onRemoteRequest(code, data, reply, option); + } + } + return true; + } + + @Override + public IRemoteObject asObject() { + return this; + } + + @Override + public void onTagDiscovered(TagInfo tagInfo) { + if (callback != null) { + callback.onTagDiscovered(tagInfo); + } + } + } + + private UsbDevicePipeController(Context context) { + mUsbDevicePipeControllerProxy = UsbDevicePipeControllerProxy.getInstance(); + mContext = context; + } + + /** + * Obtains a singleton instance of the {@code NfcController} class. + * + *

If no singleton instance is available, a singleton instance will be created. + * + * @param context Indicates the application context. + * @return Returns a singleton instance. + * @throws IllegalArgumentException if the caller is missing required context. + * @since 1 + */ + public static synchronized UsbDevicePipeController getInstance(Context context) throws IllegalArgumentException { + if (sUsbDevicePipeController == null) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + sUsbDevicePipeController = new UsbDevicePipeController(context.getApplicationContext()); + } + return sUsbDevicePipeController; + } + + /** + * get the context of application + * + * @return the context of application + * @hide + */ + public Context getContext() { + return mContext; + } +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/USBEndpoint.java b/interfaces/kits/java/ohos/usb/USBEndpoint.java new file mode 100644 index 00000000..838d52cc --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBEndpoint.java @@ -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. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Get endpoint information about a USB device. + * + *

When using this class, a USB device is attached to a USB host. According to the USB protocol specifications, + * a device contains one or more configurations, a configuration contains one or more interfaces, and an interface + * contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBEndpoint { + private int address; + + private int attributes; + + private int direction; + + private int number; + + private int interval; + + private int maxPacketSize; + + private int type; + + /** + * Creates a {@code USBEndpoint} instance. + * + * @param address Indicates the USB endpoint address, which consists of the endpoint ID and data transfer direction. + * @param attributes Indicates USB endpoint attributes, such as the data transfer type. + * @param direction Indicates the USB endpoint direction. Value 0 indicates OUT, and value 1 indicates IN. + * @param number Indicates the USB endpoint number, which uniquely identifies a USB endpoint on a USB device. + * @param interval Indicates the polling interval of the USB endpoint during data transfer. + * @param maxPacketSize Indicates the maximum packet size of the USB endpoint, that is, the maximum size of packets + * that can be received or transmitted by the endpoint after it is activated. + * @param type Indicates the USB endpoint type. + * + * @since 5 + */ + public USBEndpoint(int address, int attributes, int direction, int number, int interval, int maxPacketSize, + int type) { + this.address = address; + this.attributes = attributes; + this.direction = direction; + this.number = number; + this.interval = interval; + this.maxPacketSize = maxPacketSize; + this.type = type; + } + + /** + * Get the endpoint address. + * + * @return Returns the endpoint address. + * @since 5 + */ + public int getAddress() { + return address; + } + + /** + * Get the endpoint attributes. + * + * @return Returns the endpoint attributes. + * @since 5 + */ + public int getAttributes() { + return attributes; + } + + /** + * Get the endpoint direction. + * + * @return Returns the endpoint direction. + * @since 5 + */ + public int getDirection() { + return direction; + } + + /** + * Get the endpoint number. + * + * @return Returns the endpoint number. + * @since 5 + */ + public int getEndpointNumber() { + return number; + } + + /** + * Get the endpoint interval. + * + * @return Returns the endpoint interval, in ms. + * @since 5 + */ + public int getInterval() { + return interval; + } + + /** + * Get the maximum packet size of this endpoint. + * + * @return Returns the maximum packet size. + * @since 5 + */ + public int getMaxPacketSize() { + return maxPacketSize; + } + + /** + * Get the endpoint type. + * + * @return Returns the endpoint type. + * @since 5 + */ + public int getType() { + return type; + } + + @Override + public String toString() { + return new StringBuilder( + "USBEndpoint[address=" + address + ", attributes=" + attributes + ", direction=" + direction + ", number=" + + number + ", interval=" + interval + ", maxPacketSize=" + maxPacketSize + ", type=" + type + + "]").toString(); + } +} + + diff --git a/interfaces/kits/java/ohos/usb/USBInterface.java b/interfaces/kits/java/ohos/usb/USBInterface.java new file mode 100644 index 00000000..8034935f --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBInterface.java @@ -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. + */ + +package ohos.usb; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Get interface and endpoint information about a USB device. + * + *

+ * When using this class, a USB device is attached to a USB host. According to + * the USB protocol specifications, a device contains one or more + * configurations, a configuration contains one or more interfaces, and an + * interface contains one or more endpoints. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBInterface { + private final int id; + + private final int alternateSetting; + + private final String name; + + private final int classType; + + private final int subclass; + + private final int protocol; + + private USBEndpoint[] endpoints; + + /** + * Creates a {@code USBInterface} object. + * + * @param id Indicates the ID of an interface. + * @param alternateSetting Indicates the alternative configuration of the interface. + * @param name Indicates the interface name. + * @param class Indicates the interface class. + * @param subClass Indicates the interface subclass. + * @param protocol Indicates the protocol supported by the interface. + * + * @since 5 + */ + public USBInterface(int id, int alternateSetting, String name, int Class, int subClass, int protocol) { + this.id = id; + this.alternateSetting = alternateSetting; + this.name = name; + this.classType = Class; + this.subclass = subClass; + this.protocol = protocol; + } + + /** + * Get the {@code AlternateSetting} field of a USB interface. + * + * @return Returns the {@code AlternateSetting} field. + * @since 5 + */ + public int getAlternateSetting() { + return alternateSetting; + } + + /** + * Get the {@code localId} field of a USB interface. + * + * @return Returns the {@code InterfaceId} field. + * @since 5 + */ + public int getId() { + return id; + } + + /** + * Get the {@code InterfaceClass} field of a USB interface. + * + * @return Returns the {@code InterfaceClass} field. + * @since 5 + */ + public int getInterfaceClass() { + return classType; + } + + /** + * Get the {@code InterfaceProtocol} field of a USB interface. + * + * @return Returns the {@code InterfaceProtocol} field. + * @since 5 + */ + public int getInterfaceProtocol() { + return protocol; + } + + /** + * Get the {@code InterfaceSubclass} field of a USB interface. + * + * @return Returns the {@code InterfaceSubclass} field. + * @since 5 + */ + public int getInterfaceSubclass() { + return subclass; + } + + /** + * Get the {@code localName} field of a USB interface. + * + * @return Returns the {@code InterfaceName} field. + * @since 5 + */ + public String getName() { + return name; + } + + /** + * Get a {@code USBEndpoint} instance of this interface by index. + * + * @param index Indicates the endpoint index. + * @return Returns the {@code USBEndpoint} instance. + */ + public USBEndpoint getEndpoint(int index) { + if (endpoints == null || index < 0 || index >= endpoints.length) { + return null; + } + return endpoints[index]; + } + + /** + * Get the number of endpoints. + * + * @return Returns the number of endpoints. + * @since 5 + */ + public int getEndpointCount() { + if (endpoints == null) { + return 0; + } + return endpoints.length; + } + + /** + * Sets the endpoints list for a local {@code USBEndpoint} object. + * + * @param endpoints Indicates the endpoints of the interface. + * @since 5 + */ + public void setEndpoints(USBEndpoint[] endpoints) { + this.endpoints = endpoints; + } + + @Override + public String toString() { + return new StringBuilder( + "USBInterface[id=" + id + ", alternateSetting=" + alternateSetting + ", name=" + name + ", class=" + + classType + ", subclass=" + subclass + ", protocol=" + protocol + "]").toString(); + } +} diff --git a/interfaces/kits/java/ohos/usb/USBLoggerFactory.java b/interfaces/kits/java/ohos/usb/USBLoggerFactory.java new file mode 100644 index 00000000..c9413b64 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBLoggerFactory.java @@ -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. + */ + +package ohos.usb; + +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; + +/** + * An USB logger factory class + * + * @since 5 + * {@hide} + */ + +public class USBLoggerFactory { + private static final int DOMAIN = 0xD002A00; + + private static final String DEFAULT_TAG = "UsbService"; + + private USBLoggerFactory() { + } + + public static HiLogLabel getHilogLabel(String tag) { + if (tag == null || tag.isEmpty()) { + return USBLoggerFactory.getHilogLabel(); + } + return new HiLogLabel(HiLog.LOG_CORE, USBLoggerFactory.DOMAIN, tag); + } + + public static HiLogLabel getHilogLabel() { + return new HiLogLabel(HiLog.LOG_CORE, USBLoggerFactory.DOMAIN, DEFAULT_TAG); + } +} diff --git a/interfaces/kits/java/ohos/usb/USBPort.java b/interfaces/kits/java/ohos/usb/USBPort.java new file mode 100644 index 00000000..2a99499d --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBPort.java @@ -0,0 +1,4 @@ +package ohos.usb; + +public class USBPort { +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/USBRequest.java b/interfaces/kits/java/ohos/usb/USBRequest.java new file mode 100644 index 00000000..926f8ea5 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/USBRequest.java @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ohos.usb; + +import java.nio.ByteBuffer; + +import ohos.utils.system.SystemCap; +import ohos.utils.system.SystemCapability; + +/** + * Implements bulk transfer of data and control messages between USB devices. + * + * @Syscap {@link SystemCapability.Usb#USB_MANAGER} + * @since 5 + */ +@SystemCap(SystemCapability.Usb.USB_MANAGER) +public class USBRequest { + private Object clientData; + + + public USBRequest() { + + } + + /** + * Aborts a pending queue operation. + */ + public void abort() { + native_abort(); + } + + /** + * Frees all resources related to this request. + */ + public void free() { + native_free(); + } + + /** + * Initializes a specified endpoint for data transfer. + * + * @param connection Indicates a {@code USBDevicePipe} instance. + * @param ep Indicates an instance of the {@code USBEndpoint} class. + * @return Returns {@code true} if the initialization is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean initialize(USBDevicePipe connection, USBEndpoint ep) { + return native_initialize(connection, ep); + } + + /** + * Transfers data on the requested endpoint, and queues the request. + * + * @param buffer Indicates the buffer from which data is to be transferred. + * @return Returns {@code true} if the data transfer is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean queue(ByteBuffer buffer) { + return native_queue(buffer); + } + + /** + * Transfers data on the requested endpoint, and queues the request. + * + * @param buffer Indicates the buffer from which data is to be transferred. + * @param length Indicates the length of buffer. + * @return Returns {@code true} if the data transfer is successful; returns {@code false} otherwise. + * @since 5 + */ + public boolean queue(ByteBuffer buffer, int length) { + return native_queue(buffer, length); + } + + /** + * Dequeues a request to send or receive data on its endpoint. + * + * @param useBufferOverflowInsteadOfIllegalArg Specifies whether to replace the illegal parameter + * with a buffer overflow. + * @since 5 + */ + public void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) { + native_dequeue(useBufferOverflowInsteadOfIllegalArg); + } + + /** + * Sets client data of the {@code USBRequst} instance. + * + * @param data The client data to be set. + * @since 5 + */ + public void setClientData(Object data) { + native_set_client_data(data); + } + + /** + * Gets client data of the {@code USBRequst} instance. + * + * @since 5 + * @return Returns the client data. + */ + public Object getClientData() { + return clientData; + } + + private native void native_abort(); + + private native void native_free(); + + private native boolean native_initialize(USBDevicePipe connection, USBEndpoint ep); + + private native boolean native_queue(ByteBuffer buffer); + + private native boolean native_queue(ByteBuffer buffer, int length); + + private native void native_set_client_data(Object data); + + private native void native_dequeue(boolean useBufferOverflowInsteadOfIllegalArg); +} diff --git a/interfaces/kits/java/ohos/usb/UsbCoreController.java b/interfaces/kits/java/ohos/usb/UsbCoreController.java new file mode 100644 index 00000000..e2b32a88 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbCoreController.java @@ -0,0 +1,142 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.aafwk.ability.Lifecycle; +import ohos.app.Context; +import ohos.event.intentagent.IntentAgent; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.SystemCap; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; +import ohos.nfc.tag.TagInfo; + +import java.util.List; + +@SystemCap("SystemCapability.Communication.USB") +public class UsbCoreController { + + private static UsbCoreController sUsbCoreController; + private UsbCoreControllerProxy mUsbCoreControllerProxy; + private Context mContext; + + /** + * A callback to be invoked when the system finds a tag while the foreground page is operating in reader mode. + * + */ + public interface ReaderModeCallback extends IRemoteBroker { + /** + * Indicates the transaction code of the callback specific to inter-process communication (IPC). + */ + int TRANSACTION_ON_CALLBACK = 1; + + /** + * Called when a tag is discovered. + * + * @param tagInfo Indicates information of the discovered tag. + * @since 4 + */ + void onTagDiscovered(TagInfo tagInfo); + } + + /** + * Provides ReaderModeCallback for communicate with remote. + * + * @since 4 + */ + public class ReaderModeCallbackStub extends RemoteObject implements ReaderModeCallback { + private ReaderModeCallback callback; + + public ReaderModeCallbackStub(ReaderModeCallback callback) { + super(); + this.callback = callback; + } + + private void readInterfaceToken(Parcel data) { + data.readInt(); + data.readInt(); + data.readString(); + } + + @Override + public boolean onRemoteRequest( + int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { + HiLog.debug(LABEL, "call ReaderModeCallbackStub's onTransact"); + + switch (code) { + case TRANSACTION_ON_CALLBACK: { + readInterfaceToken(data); + + TagInfo tagInfo = new TagInfo(null, null, null, 0); + if (tagInfo instanceof Sequenceable) { + data.readSequenceable((Sequenceable) tagInfo); + } + onTagDiscovered(tagInfo); + + // writeNoException + reply.writeInt(0); + break; + } + default: { + + return super.onRemoteRequest(code, data, reply, option); + } + } + return true; + } + + @Override + public IRemoteObject asObject() { + return this; + } + + @Override + public void onTagDiscovered(TagInfo tagInfo) { + if (callback != null) { + callback.onTagDiscovered(tagInfo); + } + } + } + + private UsbCoreController(Context context) { + mUsbCoreControllerProxy = UsbCoreControllerProxy.getInstance(); + mContext = context; + } + + /** + * Obtains a singleton instance of the {@code NfcController} class. + * + *

If no singleton instance is available, a singleton instance will be created. + * + * @param context Indicates the application context. + * @return Returns a singleton instance. + * @throws IllegalArgumentException if the caller is missing required context. + * @since 1 + */ + public static synchronized UsbCoreController getInstance(Context context) throws IllegalArgumentException { + if (sUsbCoreController == null) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + sUsbCoreController = new UsbCoreController(context.getApplicationContext()); + } + return sUsbCoreController; + } + + /** + * get the context of application + * + * @return the context of application + * @hide + */ + public Context getContext() { + return mContext; + } +} diff --git a/interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java b/interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java new file mode 100644 index 00000000..d356d016 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbCoreControllerProxy.java @@ -0,0 +1,414 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.interwork.utils.PacMapEx; +import ohos.usb.UsbCoreController.ReaderModeCallback; +import ohos.usb.UsbCoreController.ReaderModeCallbackStub; +import ohos.rpc.IRemoteObject; +import ohos.rpc.IRemoteObject.DeathRecipient; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.safwk.java.SystemAbilityDefinition; + +import java.util.List; + +public class UsbCoreControllerProxy implements IUsbCoreController { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE,UsbKitsUtils.USB_DOMAIN_ID, "UsbCoreControllerProxy"); + private static final String USB_CORE_CONTROLLER = "ohos.usb.IUSBCoreController"; + private static UsbCoreControllerProxy sUsbCoreControllerProxy; + private final Object mRemoteLock = new Object(); + private IRemoteObject mRemoteObject; + + private UsbCoreControllerProxy() { + + } + + /** + * Gets a {@cod UsbControllerProxy} instance. + * + * @return Returns the instance of UsbControllerProxy. + */ + public static synchronized UsbCoreControllerProxy getInstance() { + if (sUsbCoreControllerProxy == null) { + sUsbCoreControllerProxy = new UsbCoreControllerProxy(); + } + return sUsbCoreControllerProxy; + } + + @Override + public IRemoteObject asObject() { + if (mRemoteObject != null) { + return mRemoteObject; + } + synchronized (mRemoteLock) { + mRemoteObject = SysAbilityManager.getSysAbility(SystemAbilityDefinition.NFC_MANAGER_SYS_ABILITY_ID); + if (mRemoteObject != null) { + mRemoteObject.addDeathRecipient(new UsbCoreControllerDeathRecipient(), 0); + HiLog.info(LABEL, "Get UsbManagerService completed."); + } else { + HiLog.error(LABEL, "getSysAbility(UsbManagerService) failed."); + } + return mRemoteObject; + } + } + + @Override + public HashMap getDevices() throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(1, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "getDevices call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + public USBDevicePipe connectDevice(USBDevice device) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + boolean hasRight(USBDevice device) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void requestRight(USBDevice device, String intentName) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + String usbFunctionsToString(long functions) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + long usbFunctionsFromString(String functions) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + String getCurrentFunctions() throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setCurrentFunctions(long functions) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setCurrentFunction(String functions, boolean usbDataUnlocked) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setHdcEnabled(boolean enable) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void addFunction(String functions, String function) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void removeFunction(String functions, String function) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void setPortRoles(int powerRole,int dataRole) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + UsbPortStatus getPortStatus(USBPort port) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(2, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "connectDevice call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + // Implementation of IPC Death Recipient. + private class UsbCoreControllerDeathRecipient implements DeathRecipient { + @Override + public void onRemoteDied() { + HiLog.warn(LABEL, "UsbCoreControllerDeathRecipient::onRemoteDied."); + setRemoteObject(null); + } + } + + private void setRemoteObject(IRemoteObject remoteObject) { + synchronized (mRemoteLock) { + mRemoteObject = remoteObject; + } + } +} diff --git a/interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java b/interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java new file mode 100644 index 00000000..9432ac91 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbDevicePipeControllerProxy.java @@ -0,0 +1,173 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.interwork.utils.PacMapEx; +import ohos.usb.UsbDevicePipeController.ReaderModeCallback; +import ohos.usb.UsbDevicePipeController.ReaderModeCallbackStub; +import ohos.rpc.IRemoteObject; +import ohos.rpc.IRemoteObject.DeathRecipient; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.safwk.java.SystemAbilityDefinition; + +import java.util.List; + +public class UsbDevicePipeControllerProxy implements IUsbDevicePipeController { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE,UsbKitsUtils.USB_DOMAIN_ID, "UsbDevicePipeControllerProxy"); + private static final String USB_DevicePipe_CONTROLLER = "ohos.usb.IUSBDevicePipeController"; + private static UsbDevicePipeControllerProxy sUsbDevicePipeControllerProxy; + private final Object mRemoteLock = new Object(); + private IRemoteObject mRemoteObject; + + private UsbDevicePipeControllerProxy() { + + } + + /** + * Gets a {@cod UsbControllerProxy} instance. + * + * @return Returns the instance of UsbControllerProxy. + */ + public static synchronized UsbDevicePipeControllerProxy getInstance() { + if (sUsbDevicePipeControllerProxy == null) { + sUsbDevicePipeControllerProxy = new UsbDevicePipeControllerProxy(); + } + return sUsbDevicePipeControllerProxy; + } + + @Override + public IRemoteObject asObject() { + if (mRemoteObject != null) { + return mRemoteObject; + } + synchronized (mRemoteLock) { + mRemoteObject = SysAbilityManager.getSysAbility(SystemAbilityDefinition.NFC_MANAGER_SYS_ABILITY_ID); + if (mRemoteObject != null) { + mRemoteObject.addDeathRecipient(new UsbDevicePipeControllerDeathRecipient(), 0); + HiLog.info(LABEL, "Get UsbManagerService completed."); + } else { + HiLog.error(LABEL, "getSysAbility(UsbManagerService) failed."); + } + return mRemoteObject; + } + } + + @Override + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int length, int timeout) throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_DevicePipe_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(1, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "getDevices call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + int bulkTransfer(USBEndpoint epObj, byte[] buffer, int offset, int length, int timeout) throws RemoteException { + + } + + @Override + boolean claimInterface(USBInterface interfaceObj, boolean force) throws RemoteException { + + } + + @Override + void close() throws RemoteException { + + } + + @Override + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int offset, int length, int timeout) throws RemoteException { + + } + + @Override + int controlTransfer(int requestType, int request, int value, int index, byte[] buffer, int length, int timeout) throws RemoteException { + + } + + @Override + int getFileDescriptor() throws RemoteException { + + } + + @Override + byte[] getRawDescriptors() throws RemoteException { + + } + + @Override + String getSerial() throws RemoteException { + + } + + @Override + boolean releaseInterface(USBInterface interfaceObj) throws RemoteException { + + } + + @Override + USBRequest requestWait(long timeout) throws TimeoutException, RemoteException{ + + } + + @Override + USBRequest requestWait() throws RemoteException { + + } + + @Override + boolean setConfiguration(USBConfig config) throws RemoteException { + + } + + @Override + boolean setInterface(USBInterface interfaceObj) throws RemoteException { + + } + + @Override + boolean openByInt(String name, int fd) throws RemoteException { + + } + + // Implementation of IPC Death Recipient. + private class UsbDevicePipeControllerDeathRecipient implements DeathRecipient { + @Override + public void onRemoteDied() { + HiLog.warn(LABEL, "UsbDevicePipeControllerDeathRecipient::onRemoteDied."); + setRemoteObject(null); + } + } + + private void setRemoteObject(IRemoteObject remoteObject) { + synchronized (mRemoteLock) { + mRemoteObject = remoteObject; + } + } +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/UsbKitsUtils.java b/interfaces/kits/java/ohos/usb/UsbKitsUtils.java new file mode 100644 index 00000000..b85024cd --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbKitsUtils.java @@ -0,0 +1,7 @@ +package ohos.usb; + +public class UsbKitsUtils { + + /** USB Domain ID. */ + public static final int USB_DOMAIN_ID = 0xD002900; +} diff --git a/interfaces/kits/java/ohos/usb/UsbPortStatus.java b/interfaces/kits/java/ohos/usb/UsbPortStatus.java new file mode 100644 index 00000000..c820c43d --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbPortStatus.java @@ -0,0 +1,4 @@ +package ohos.usb; + +public class UsbPortStatus { +} \ No newline at end of file diff --git a/interfaces/kits/java/ohos/usb/UsbRequestController.java b/interfaces/kits/java/ohos/usb/UsbRequestController.java new file mode 100644 index 00000000..68d63bb9 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbRequestController.java @@ -0,0 +1,142 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.aafwk.ability.Lifecycle; +import ohos.app.Context; +import ohos.event.intentagent.IntentAgent; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.SystemCap; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.rpc.IRemoteBroker; +import ohos.rpc.IRemoteObject; +import ohos.interwork.utils.PacMapEx; +import ohos.nfc.tag.TagInfo; + +import java.util.List; + +@SystemCap("SystemCapability.Communication.USB") +public class UsbRequestController { + + private static UsbRequestController sUsbRequestController; + private UsbRequestControllerProxy mUsbRequestControllerProxy; + private Context mContext; + + /** + * A callback to be invoked when the system finds a tag while the foreground page is operating in reader mode. + * + */ + public interface ReaderModeCallback extends IRemoteBroker { + /** + * Indicates the transaction code of the callback specific to inter-process communication (IPC). + */ + int TRANSACTION_ON_CALLBACK = 1; + + /** + * Called when a tag is discovered. + * + * @param tagInfo Indicates information of the discovered tag. + * @since 4 + */ + void onTagDiscovered(TagInfo tagInfo); + } + + /** + * Provides ReaderModeCallback for communicate with remote. + * + * @since 4 + */ + public class ReaderModeCallbackStub extends RemoteObject implements ReaderModeCallback { + private ReaderModeCallback callback; + + public ReaderModeCallbackStub(ReaderModeCallback callback) { + super(); + this.callback = callback; + } + + private void readInterfaceToken(Parcel data) { + data.readInt(); + data.readInt(); + data.readString(); + } + + @Override + public boolean onRemoteRequest( + int code, MessageParcel data, MessageParcel reply, MessageOption option) throws RemoteException { + HiLog.debug(LABEL, "call ReaderModeCallbackStub's onTransact"); + + switch (code) { + case TRANSACTION_ON_CALLBACK: { + readInterfaceToken(data); + + TagInfo tagInfo = new TagInfo(null, null, null, 0); + if (tagInfo instanceof Sequenceable) { + data.readSequenceable((Sequenceable) tagInfo); + } + onTagDiscovered(tagInfo); + + // writeNoException + reply.writeInt(0); + break; + } + default: { + + return super.onRemoteRequest(code, data, reply, option); + } + } + return true; + } + + @Override + public IRemoteObject asObject() { + return this; + } + + @Override + public void onTagDiscovered(TagInfo tagInfo) { + if (callback != null) { + callback.onTagDiscovered(tagInfo); + } + } + } + + private UsbRequestController(Context context) { + mUsbRequestControllerProxy = UsbRequestControllerProxy.getInstance(); + mContext = context; + } + + /** + * Obtains a singleton instance of the {@code NfcController} class. + * + *

If no singleton instance is available, a singleton instance will be created. + * + * @param context Indicates the application context. + * @return Returns a singleton instance. + * @throws IllegalArgumentException if the caller is missing required context. + * @since 1 + */ + public static synchronized UsbRequestController getInstance(Context context) throws IllegalArgumentException { + if (sUsbRequestController == null) { + if (context == null) { + throw new IllegalArgumentException("context is null"); + } + sUsbRequestController = new UsbRequestController(context.getApplicationContext()); + } + return sUsbRequestController; + } + + /** + * get the context of application + * + * @return the context of application + * @hide + */ + public Context getContext() { + return mContext; + } +} diff --git a/interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java b/interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java new file mode 100644 index 00000000..27a88791 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/UsbRequestControllerProxy.java @@ -0,0 +1,134 @@ +package ohos.usb; + +import ohos.aafwk.ability.Ability; +import ohos.event.intentagent.IntentAgent; +import ohos.hiviewdfx.HiLog; +import ohos.hiviewdfx.HiLogLabel; +import ohos.interwork.utils.PacMapEx; +import ohos.usb.UsbRequestController.ReaderModeCallback; +import ohos.usb.UsbRequestController.ReaderModeCallbackStub; +import ohos.rpc.IRemoteObject; +import ohos.rpc.IRemoteObject.DeathRecipient; +import ohos.rpc.MessageParcel; +import ohos.rpc.MessageOption; +import ohos.rpc.RemoteException; +import ohos.rpc.RemoteObject; +import ohos.sysability.samgr.SysAbilityManager; +import ohos.utils.Parcel; +import ohos.utils.Sequenceable; +import ohos.utils.system.safwk.java.SystemAbilityDefinition; + +import java.util.List; + +public class UsbRequestControllerProxy implements IUsbRequestController { + + private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_CORE,UsbKitsUtils.USB_DOMAIN_ID, "UsbRequestControllerProxy"); + private static final String USB_Request_CONTROLLER = "ohos.usb.IUSBRequestController"; + private static UsbRequestControllerProxy sUsbRequestControllerProxy; + private final Object mRemoteLock = new Object(); + private IRemoteObject mRemoteObject; + + private UsbRequestControllerProxy() { + + } + + /** + * Gets a {@cod UsbControllerProxy} instance. + * + * @return Returns the instance of UsbControllerProxy. + */ + public static synchronized UsbRequestControllerProxy getInstance() { + if (sUsbRequestControllerProxy == null) { + sUsbRequestControllerProxy = new UsbRequestControllerProxy(); + } + return sUsbRequestControllerProxy; + } + + @Override + public IRemoteObject asObject() { + if (mRemoteObject != null) { + return mRemoteObject; + } + synchronized (mRemoteLock) { + mRemoteObject = SysAbilityManager.getSysAbility(SystemAbilityDefinition.NFC_MANAGER_SYS_ABILITY_ID); + if (mRemoteObject != null) { + mRemoteObject.addDeathRecipient(new UsbRequestControllerDeathRecipient(), 0); + HiLog.info(LABEL, "Get UsbManagerService completed."); + } else { + HiLog.error(LABEL, "getSysAbility(UsbManagerService) failed."); + } + return mRemoteObject; + } + } + + @Override + void abort() throws RemoteException { + IRemoteObject service = asObject(); + if (service == null) { + throw new RemoteException("service is null"); + } + MessageParcel data = MessageParcel.obtain(); + MessageParcel reply = MessageParcel.obtain(); + MessageOption option = new MessageOption(); + try { + data.writeString(USB_CORE_CONTROLLER); + data.writeInt(isEnabled ? TRUE : FALSE); + // TODO 第一个参数是硬编码,参数定义在UsbKitsUtil,待补充 + service.sendRequest(1, data, reply, option); + // TODO 返回值待处理,从reply中获取 + return null; + } catch (RemoteException remoteException) { + HiLog.error(LABEL, "getDevices call failed."); + throw remoteException; + } finally { + reply.reclaim(); + data.reclaim(); + } + } + + @Override + void free() throws RemoteException { + + } + + @Override + boolean initialize(USBDevicePipe connection, USBEndpoint ep) throws RemoteException { + + } + + @Override + boolean queue(ByteBuffer buffer) throws RemoteException { + + } + + @Override + boolean queue(ByteBuffer buffer, int length) throws RemoteException { + + } + + @Override + void dequeue(boolean useBufferOverflowInsteadOfIllegalArg) throws RemoteException { + + } + + @Override + void setClientData(Object data) throws RemoteException { + + } + + + // Implementation of IPC Death Recipient. + private class UsbRequestControllerDeathRecipient implements DeathRecipient { + @Override + public void onRemoteDied() { + HiLog.warn(LABEL, "UsbRequestControllerDeathRecipient::onRemoteDied."); + setRemoteObject(null); + } + } + + private void setRemoteObject(IRemoteObject remoteObject) { + synchronized (mRemoteLock) { + mRemoteObject = remoteObject; + } + } +} diff --git a/interfaces/kits/java/ohos/usb/package-info.java b/interfaces/kits/java/ohos/usb/package-info.java new file mode 100644 index 00000000..f7a002e0 --- /dev/null +++ b/interfaces/kits/java/ohos/usb/package-info.java @@ -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. + */ + +/** + * Provides basic USB communication capabilities for other peripherals and devices running OHOS. + * + *

The basic USB communication capabilities include control transfer and bulk transfer. + * + * @since 5 + */ + +package ohos.usb; \ No newline at end of file diff --git a/interfaces/kits/js/@ohos.usb.d.ts b/interfaces/kits/js/@ohos.usb.d.ts new file mode 100644 index 00000000..7d3eb2cb --- /dev/null +++ b/interfaces/kits/js/@ohos.usb.d.ts @@ -0,0 +1,789 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare namespace usb { + /** + * 获取USB服务版本号,测试用 + * + * @return USB服务当前的版本号. + * @since 8 + */ + function getVersion(): string; + + /* usb core functions begin */ + /** + * 获取USB设备列表 + * + * @return 设备信息{@link USBDevice}列表. + * @since 8 + */ + function getDevices(): Array>; + + /** + * 根据{@link getDevices()}返回的设备信息打开USB设备 + * + * @param device 设备信息,{@link getDevices()}返回的列表中的一个设备信息 + * @return 指定的传输通道 {@link USBDevicePipe} 对象. + * @since 8 + */ + function connectDevice(device: USBDevice): Readonly; + + /** + * 判断是否有权访问设备 + * + * @param deviceName 设备名称,{@link USBDevice.name} + * @return true 有权限, false 没有权限 + * @since 8 + */ + function hasRight(deviceName: string): boolean; + + /** + * 请求给定软件包的临时权限以访问设备 + * + * @param deviceName 设备名称,{@link USBDevice.name} + * @return true 请求权限成功, false 请求权限失败 + * @since 8 + */ + function requestRight(deviceName: string): Promise; + + /** + * 将给定的功能列表描述字符串转换为功能列表的数字组合掩码 + * + * @param funcs 支持的功能列表描述符 + * @return 功能列表的数字组合掩码 + * @systemapi + * @since 8 + */ + function usbFunctionsFromString(funcs: string): number; + + /** + * 将给定的功能列表的数字组合掩码转换为功能列表描述字符串 + * + * @param funcs 支持的功能列表的数字组合掩码 + * @return 支持的功能列表描述字符串 + * @systemapi + * @since 8 + */ + function usbFunctionsToString(funcs: FunctionType): string; + + /** + * 在设备模式下设置当前的USB功能列表 + * + * @param funcs 设置支持的功能列表的数字组合掩码{@link FunctionType} + * @return true 设置成功, false 设置失败 + * @systemapi + * @since 8 + */ + function setCurrentFunctions(funcs: FunctionType): Promise; + /** + * 获取设备模式下的当前USB功能列表的数字组合掩码 + * + * @return 支持的功能列表的数字组合掩码{@link FunctionType} + * @systemapi + * @since 8 + */ + function getCurrentFunctions(): FunctionType; + + /* usb port functions begin */ + /** + * 获取物理USB端口描述信息{@link USBPort}列表 + * + * @return {@link USBPort}列表 + * @systemapi + * @since 8 + */ + function getPorts(): Array; + + /** + * 获取指定的端口{@link USBPort}支持的模式列表的组合掩码 + * + * @return 支持的模式列表的组合掩码{@link PortModeType} + * @systemapi + * @since 8 + */ + function getSupportedModes(portId: number): PortModeType; + + /** + * 设置指定的端口{@link USBPort}支持的角色模式,包含充电角色、数据传输角色 + * + * @param portId 端口的唯一标识 + * @param powerRole 充电的角色{@link PowerRoleType} + * @param dataRole 数据传输的角色{@link DataRoleType} + * @return 支持的模式 + * @systemapi + * @since 8 + */ + function setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise; + + /* usb pipe functions begin */ + /** + * 获取接口 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param iface 用于确定需要获取接口的索引 {@link USBInterface}. + * @param force 是否强制获取 + * @return 成功:0;失败:错误码 + * @since 8 + */ + function claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number; + /** + * 释放接口 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param iface 用于确定需要释放接口的索引 {@link USBInterface}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number; + /** + * 设置设备配置 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param config 用于确定需要设置配置的索引 {@link USBConfig}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function setConfiguration(pipe: USBDevicePipe, config: USBConfig): number; + /** + * 设置设备接口 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @param iface 用于确定需要设置接口的索引 {@link USBInterface}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function setInterface(pipe: USBDevicePipe, iface: USBInterface): number; + /** + * 获取原始的USB描述符 + * + * @param pipe 用于确定总线号和设备地址 {@link USBDevicePipe}. + * @return 返回获取的原始数据 + * @since 8 + */ + function getRawDescriptor(pipe: USBDevicePipe): Uint8Array; + /** + * 获取文件描述符 + * + * @param pipe 用于确定设备 {@link USBDevicePipe}. + * @return 返回设备对应的文件描述符 + * @since 8 + */ + function getFileDescriptor(pipe: USBDevicePipe): number; + /** + * 控制传输 + * + * @param pipe 用于确定设备 {@link USBDevicePipe}. + * @param contrlparam 控制传输参数 + * @param timeout 超时时间,可选参数,默认为0不超时 + * @return 传输或接收到的数据块大小,异常返回-1 + * @since 8 + */ + function controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise; + + /** + * 批量传输 + * + * @param pipe 用于确定设备 {@link USBDevicePipe}. + * @param endpoint 用于确定传输的端口 {@link USBEndpoint}. + * @param buffer 用于写入或读取的缓冲区 + * @param timeout 超时时间,可选参数,默认为0不超时 + * @return 传输或接收到的数据块大小,异常返回-1 + * @since 8 + */ + function bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, + timeout?: number): Promise; + + /** + * 关闭USBDevicePipe + * + * @param pipe 用于确定pipe {@link USBDevicePipe}. + * @return 成功:0;失败:错误码 + * @since 8 + */ + function closePipe(pipe: USBDevicePipe): number; + + /** + * 通过USB发送和接收数据的端口。通过{@link USBInterface}获取。 + * + * @since 8 + */ + interface USBEndpoint { + /** + * 端点地址 + * + * @since 8 + */ + address: number; + + /** + * 端点属性 + * + * @since 8 + */ + attributes: number; + + /** + * 端点间隔 + * + * @since 8 + */ + interval: number; + + /** + * 端点最大数据包大小 + * + * @since 8 + */ + maxPacketSize: number; + + /** + * 端点的方向。 + * + * @since 8 + */ + direction: USBRequestDirection; + + /** + * 端点号 + * + * @since 8 + */ + number: number; + + /** + * 端点类型 + * + * @since 8 + */ + type: number; + + /** + * 端点所属的接口的唯一标识{@link USBInterface.id} + * + * @since 8 + */ + interfaceId: number; + } + + + /** + * 一个{@link USBConfig}中可以含有多个interface,每个interface提供一个功能。 + * + * @since 8 + */ + interface USBInterface { + /** + * 接口的唯一标识 + * + * @since 8 + */ + id: number; + + /** + * 接口的协议 + * + * @since 8 + */ + protocol: number; + + /** + * 设备类型 + * + * @since 8 + */ + clazz: number; + + /** + * 设备子类 + * + * @since 8 + */ + subClass: number; + + /** + *在同一个接口中的多个描述符中进行切换设置 + * + * @since 8 + */ + alternateSetting: number; + + /** + * 接口名称 + * + * @since 8 + */ + name: string; + + /** + * 当前接口所包含的端点{@link USBEndpoint} + * + * @since 8 + */ + endpoints: Array; + } + + /** + * USB配置,一个{@link USBDevice}中可以含有多个配置。 + * + * @since 8 + */ + interface USBConfig { + /** + * 配置的唯一标识 + * + * @since 8 + * + * + */ + id: number; + + /** + * 配置的属性 + * + * @since 8 + */ + attributes: number; + + /** + * 最大功耗,以毫安为单位 + * + * @since 8 + */ + maxPower: number; + + /** + * 配置的名称,可以为空 + * + * @since 8 + */ + name: string; + + /** + * 检查当前配置是否支持远程唤醒 + * + * @since 8 + */ + isRemoteWakeup: boolean; + + /** + * 检查当前配置是否支持独立电源 + * + * @since 8 + */ + isSelfPowered: boolean; + + /** + * 配置支持的接口属性{@link USBInterface} + * + * @since 8 + */ + interfaces: Array; + } + + /** + * USB设备信息。 + * + * @since 8 + */ + interface USBDevice { + /** + * 总线地址 + * + * @since 8 + */ + busNum: number; + /** + * 设备地址 + * + * @since 8 + */ + devAddress: number; + /** + * 序列号 + * + * @since 8 + */ + serial: string; + /** + * 设备名字 + * + * @since 8 + */ + name: string; + /** + * 产商信息 + * + * @since 8 + */ + manufacturerName: string; + /** + * 产品信息 + * + * @since 8 + */ + productName: string; + /** + * 版本 + * + * @since 8 + */ + version: string; + /** + * 厂商ID + * + * @since 8 + */ + vendorId: number; + /** + * 产品ID + * + * @since 8 + */ + productId: number; + /** + * 设备类 + * + * @since 8 + */ + clazz: number; + /** + * 设备子类 + * + * @since 8 + */ + subClass: number; + /** + * 设备协议码 + * + * @since 8 + */ + protocol: number; + /** + * 设备配置描述符信息 {@link USBConfig}. + * + * @since 8 + */ + configs: Array; + } + + /** + * USB设备消息控制通道,用于确定设备 + * + * @since 8 + */ + interface USBDevicePipe { + /** + * 总线地址 + * + * @since 8 + */ + busNum: number; + /** + * 设备地址 + * + * @since 8 + */ + devAddress: number; + } + + /** + * 电源角色类型 + * + * @since 8 + */ + enum PowerRoleType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * 外部供电 + * + * @since 8 + */ + SOURCE, + /** + * 内部供电 + * + * @since 8 + */ + SINK + } + + /** + * 数据角色类型 + * + * @since 8 + */ + enum DataRoleType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * host模式,主设备模式 + * + * @since 8 + */ + HOST, + /** + * device模式,从设备模式 + * + * @since 8 + */ + DEVICE + } + + /** + * port模式类型 + * + * @since 8 + */ + enum PortModeType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * host 数据下行,对外提供电源 + * + * @since 8 + */ + DFP, + /** + * device 数据上行,需要外部供电 + * + * @since 8 + */ + UFP + } + + /** + * USB设备端口角色信息 + * + * @since 8 + */ + interface USBPortStatus { + /** + * 当前的USB模式 + * + * @since 8 + */ + currentMode: number; + + /** + * 当前设备充电模式 + * + * @since 8 + */ + currentPowerRole: number; + + /** + * 当前设备数据传输模式 + * + * @since 8 + */ + currentDataRole: number; + } + + /** + * USB设备端口信息 + * + * @since 8 + */ + interface USBPort { + /** + * USB端口信息唯一标识 + * + * @since 8 + */ + id: number; + + /** + * 当前端口支持的模式列表的组合掩码 + * + * @since 8 + */ + supportedModes: PortModeType; + + /** + * 当前端口角色信息 {@link USBPortStatus} + * + * @since 8 + */ + status: USBPortStatus; + } + + /** + * 控制传输参数 + * + * @since 8 + */ + interface USBControlParams { + /** + * 请求类型 + * + * @since 8 + */ + request: number; + /** + * 请求目标类型 + * + * @since 8 + */ + target: USBRequestTargetType; + /** + * 控制请求类型 + * + * @since 8 + */ + reqType: USBControlRequestType; + /** + * 请求参数 + * + * @since 8 + */ + value: number; + /** + * 根据请求参数value的不同有所不同 + * + * @since 8 + */ + index: number; + /** + * @用于写入或读取的缓冲区 + * @since 8 + */ + data: Uint8Array; + } + + /** + * 请求目标类型 + * + * @since 8 + */ + enum USBRequestTargetType { + /** + * 设备 + * + * @since 8 + */ + USB_REQUEST_TARGET_DEVICE = 0, + /** + * 接口 + * + * @since 8 + */ + USB_REQUEST_TARGET_INTERFACE, + /** + * 端点 + * + * @since 8 + */ + USB_REQUEST_TARGET_ENDPOINT, + /** + * 其他 + * + * @since 8 + */ + USB_REQUEST_TARGET_OTHER + } + + /** + * 控制请求类型 + * @since 8 + */ + enum USBControlRequestType { + /** + * 标准 + * + * @since 8 + */ + USB_REQUEST_TYPE_STANDARD = 0, + /** + * 类 + * + * @since 8 + */ + USB_REQUEST_TYPE_CLASS, + /** + * 厂商 + * + * @since 8 + */ + USB_REQUEST_TYPE_VENDOR + } + + /** + * 请求方向 + * @since 8 + */ + enum USBRequestDirection { + /** + * 写数据,主设备往从设备 + * + * @since 8 + */ + USB_REQUEST_DIR_TO_DEVICE = 0, + /** + * 读数据,从设备往主设备 + * + * @since 8 + */ + USB_REQUEST_DIR_FROM_DEVICE = 0x80 + } + + + /** + * function 模式 + * + * @since 8 + */ + enum FunctionType { + /** + * 无 + * + * @since 8 + */ + NONE = 0, + /** + * 串口设备 + * + * @since 8 + */ + ACM = 1, + /** + * 网口设备 + * + * @since 8 + */ + ECM = 2, + /** + * HDC设备 + * + * @since 8 + */ + HDC = 4 + } + +} + +export default usb; diff --git a/interfaces/kits/js/napi/BUILD.gn b/interfaces/kits/js/napi/BUILD.gn new file mode 100644 index 00000000..cc25288f --- /dev/null +++ b/interfaces/kits/js/napi/BUILD.gn @@ -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. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("usbnapi_private_config") { + include_dirs = [ + "//foundation/ace/napi/native_engine", + "//foundation/ace/napi/interfaces/kits", + "//utils/system/safwk/native/include", + "//third_party/node/src", + "//base/usbmgr/usb_manager/interfaces/innerkits/native/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include", + ] +} + +ohos_shared_library("usb") { + sources = [ "usb_info.cpp" ] + configs = [ + "${utils_path}:utils_config", + ":usbnapi_private_config", + ] + deps = [ + "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "//foundation/ace/napi:ace_napi", + "//utils/native/base:utils", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + + subsystem_name = "usb" + part_name = "usb_manager_native" +} diff --git a/interfaces/kits/js/napi/usb_async_context.h b/interfaces/kits/js/napi/usb_async_context.h new file mode 100644 index 00000000..3af6ae6d --- /dev/null +++ b/interfaces/kits/js/napi/usb_async_context.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "napi/native_api.h" +#include "napi/native_node_api.h" +#include "usb_device_pipe.h" +#include "usb_endpoint.h" +#include "usb_request.h" + +namespace OHOS { +namespace USB { + +struct USBAsyncContext { + napi_env env; + napi_async_work work; + + napi_deferred deferred; + napi_status status; +}; + +struct USBRightAsyncContext : USBAsyncContext { + std::string deviceName; + bool hasRight = false; +}; + +struct USBFunctionAsyncContext : USBAsyncContext { + int32_t functions; +}; + +struct USBPortRoleAsyncContext : USBAsyncContext { + int32_t portId; + int32_t powerRole; + int32_t dataRole; +}; + +struct USBControlTransferAsyncContext : USBAsyncContext { + USBDevicePipe pipe; + int32_t request; + int32_t target; + int32_t reqType; + int32_t directon; + int32_t value; + int32_t index; + uint8_t *buffer; + uint32_t bufferLength; + int32_t timeout = 0; +}; + +struct USBBulkTransferAsyncContext : USBAsyncContext { + uint8_t *buffer; + uint32_t bufferLength; + int32_t timeout = 0; + USBDevicePipe pipe; + USBEndpoint endpoint; +}; + +struct USBQueueAsyncContext : USBAsyncContext { + UsbRequest req; + uint8_t *buffer; + uint32_t bufferLength; +}; +} // namespace USB +} // namespace OHOS diff --git a/interfaces/kits/js/napi/usb_info.cpp b/interfaces/kits/js/napi/usb_info.cpp new file mode 100644 index 00000000..8ce73cbc --- /dev/null +++ b/interfaces/kits/js/napi/usb_info.cpp @@ -0,0 +1,1459 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 +#include +#include +#include "hilog_wrapper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "securec.h" +#include "usb_async_context.h" +#include "usb_device_pipe.h" +#include "usb_endpoint.h" +#include "usb_srv_client.h" + +using namespace OHOS; +using namespace OHOS::USB; +const int32_t MSEC_TIME = 1000; +const int32_t INDEX_0 = 0; +const int32_t INDEX_1 = 1; +const int32_t INDEX_2 = 2; +const int32_t INDEX_3 = 3; +const int32_t PARAM_COUNT_1 = 1; +const int32_t PARAM_COUNT_2 = 2; +const int32_t PARAM_COUNT_3 = 3; +const int32_t PARAM_COUNT_4 = 4; +const int32_t STR_DEFAULT_SIZE = 256; + +static void ParseUsbDevicePipe(napi_env env, napi_value &obj, USBDevicePipe &pip); + +static void JsValueToString(const napi_env &env, const napi_value &value, const int bufLen, std::string &target) +{ + char *buf = (char *)malloc(bufLen); + + if (buf == nullptr) { + USB_HILOGE(MODULE_JS_NAPI, "%{public}s nullptr js object to string malloc failed", __func__); + } + (void)memset_s(buf, bufLen, 0, bufLen); + size_t result = 0; + napi_get_value_string_utf8(env, value, buf, bufLen, &result); + + target = buf; + free(buf); + buf = nullptr; +} +static void JsObjectToString(const napi_env &env, + const napi_value &object, + const char *fieldStr, + const int bufLen, + std::string &fieldRef) +{ + if (bufLen <= 0) + return; + + bool hasProperty = false; + napi_has_named_property(env, object, fieldStr, &hasProperty); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + napi_typeof(env, field, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_string, "Wrong argument type. String expected."); + char *buf = (char *)malloc(bufLen); + if (buf == nullptr) { + USB_HILOGE(MODULE_JS_NAPI, "%{public}s nullptr js object to string malloc failed", __func__); + } + (void)memset_s(buf, bufLen, 0, bufLen); + size_t result = 0; + napi_get_value_string_utf8(env, field, buf, bufLen, &result); + fieldRef = buf; + free(buf); + buf = nullptr; + } else { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s js to str no property: %{public}s", __func__, fieldStr); + } +} + +static bool JsObjectGetProperty(const napi_env &env, const napi_value &object, const char *fieldStr, napi_value *value) +{ + bool hasProperty = false; + napi_has_named_property(env, object, fieldStr, &hasProperty); + if (hasProperty) { + napi_get_named_property(env, object, fieldStr, value); + } else { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s js object has no property: %{public}s", __func__, fieldStr); + } + return hasProperty; +} + +static void JsObjectToInt(const napi_env &env, const napi_value &object, const char *fieldStr, int &fieldRef) +{ + bool hasProperty = false; + napi_has_named_property(env, object, fieldStr, &hasProperty); + if (hasProperty) { + napi_value field; + napi_valuetype valueType; + + napi_get_named_property(env, object, fieldStr, &field); + napi_typeof(env, field, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, field, &fieldRef); + } else { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s js to int no property: %{public}s", __func__, fieldStr); + } +} + +static bool JsUint8ArrayParse(const napi_env &env, + const napi_value &object, + uint8_t **uint8Buffer, + size_t &bufferSize, + size_t &offset) +{ + bool isTypedArray = false; + if (napi_is_typedarray(env, object, &isTypedArray) != napi_ok || !isTypedArray) { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s invalid type", __func__); + return false; + } + + napi_typedarray_type type; + napi_value buffer; + + napi_status infoStatus = + napi_get_typedarray_info(env, object, &type, &bufferSize, (void **)uint8Buffer, &buffer, &offset); + if (infoStatus != napi_ok) { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s get typedarray info failed, status: %{public}d", __func__, infoStatus); + return false; + } + + if (type != napi_uint8_array) { + USB_HILOGW(MODULE_JS_NAPI, "%{public}s not Uint8Array type: %{public}d", __func__, type); + return false; + } + + return true; +} + +static void ProcessPromise(napi_env env, USBAsyncContext *asyncContext, napi_value result) +{ + if (asyncContext->deferred) { + if (asyncContext->status == napi_ok) { + napi_resolve_deferred(env, asyncContext->deferred, result); + } else { + napi_reject_deferred(env, asyncContext->deferred, result); + } + } +} + +static void Uint8ArrayToJsValue(const napi_env &env, uint8_t *uint8Buffer, size_t bufferSize, napi_value &result) +{ + if (uint8Buffer == nullptr || bufferSize < 0) { + napi_get_undefined(env, &result); + return; + } + + uint8_t *nativeArraybuffer = new uint8_t[bufferSize]; + napi_value nativeValue = nullptr; + napi_create_arraybuffer(env, bufferSize, (void **)&nativeArraybuffer, &nativeValue); + memcpy_s(nativeArraybuffer, bufferSize, uint8Buffer, bufferSize); + napi_create_typedarray(env, napi_uint8_array, bufferSize, nativeValue, 0, &result); +} + +static void SetValueUtf8String(const napi_env &env, const char *fieldStr, const char *str, napi_value &result) +{ + napi_value value; + napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, fieldStr, value); +} + +static void SetValueInt32(const napi_env &env, const char *fieldStr, const int intValue, napi_value &result) +{ + napi_value value; + napi_create_int32(env, intValue, &value); + napi_set_named_property(env, result, fieldStr, value); +} + +static void SetValueBool(const napi_env &env, const char *fieldStr, const bool boolValue, napi_value &result) +{ + napi_value value; + napi_get_boolean(env, boolValue, &value); + napi_set_named_property(env, result, fieldStr, value); +} + +static void CreateUsbDevicePipe(napi_env env, napi_value &obj, const USBDevicePipe &pip) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "busNum", pip.GetBusNum(), obj); + SetValueInt32(env, "devAddress", pip.GetDevAddr(), obj); +} + +static void CtoJSUsbEndpoint(const napi_env &env, napi_value &obj, USBEndpoint &usbEndpoint) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "address", usbEndpoint.GetAddress(), obj); + SetValueInt32(env, "attributes", usbEndpoint.GetAttributes(), obj); + SetValueInt32(env, "interval", usbEndpoint.GetInterval(), obj); + SetValueInt32(env, "maxPacketSize", usbEndpoint.GetMaxPacketSize(), obj); + SetValueInt32(env, "direction", usbEndpoint.GetDirection(), obj); + SetValueInt32(env, "number", usbEndpoint.GetEndpointNumber(), obj); + SetValueInt32(env, "type", usbEndpoint.GetType(), obj); + SetValueInt32(env, "interfaceId", usbEndpoint.GetInterfaceId(), obj); +} + +static void CtoJSUsbInterface(const napi_env &env, napi_value &obj, UsbInterface &usbInterface) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "id", usbInterface.GetId(), obj); + SetValueInt32(env, "protocol", usbInterface.GetProtocol(), obj); + SetValueInt32(env, "clazz", usbInterface.GetClass(), obj); + SetValueInt32(env, "subclass", usbInterface.GetSubClass(), obj); + SetValueInt32(env, "alternateSetting", usbInterface.GetAlternateSetting(), obj); + SetValueUtf8String(env, "name", usbInterface.GetName().c_str(), obj); + napi_value arr; + napi_create_array(env, &arr); + for (int32_t i = 0; i < usbInterface.GetEndpointCount(); ++i) { + USBEndpoint usbEndpoint; + usbInterface.GetEndpoint(i, usbEndpoint); + napi_value obj; + CtoJSUsbEndpoint(env, obj, usbEndpoint); + napi_set_element(env, arr, i, obj); + } + napi_set_named_property(env, obj, "endpoints", arr); +} + +static void CtoJSUsbConfig(const napi_env &env, napi_value &obj, USBConfig &usbConfig) +{ + napi_create_object(env, &obj); + SetValueInt32(env, "id", usbConfig.GetId(), obj); + SetValueInt32(env, "attributes", usbConfig.GetAttributes(), obj); + SetValueBool(env, "isRemoteWakeup", usbConfig.IsRemoteWakeup(), obj); + SetValueBool(env, "isSelfPowered", usbConfig.IsSelfPowered(), obj); + SetValueInt32(env, "maxPower", usbConfig.GetMaxPower(), obj); + SetValueUtf8String(env, "name", usbConfig.GetName().c_str(), obj); + napi_value arr; + napi_create_array(env, &arr); + for (int32_t i = 0; i < usbConfig.GetInterfaceCount(); ++i) { + UsbInterface usbInterface; + usbConfig.GetInterface(i, usbInterface); + napi_value obj; + CtoJSUsbInterface(env, obj, usbInterface); + napi_set_element(env, arr, i, obj); + } + napi_set_named_property(env, obj, "interfaces", arr); +} + +static void CtoJSUsbDevice(const napi_env &env, napi_value &obj, UsbDevice *usbDevice) +{ + napi_create_object(env, &obj); + SetValueUtf8String(env, "name", usbDevice->GetName().c_str(), obj); + SetValueUtf8String(env, "serial", usbDevice->GetmSerial().c_str(), obj); + SetValueUtf8String(env, "manufacturerName", usbDevice->GetManufacturerName().c_str(), obj); + SetValueUtf8String(env, "productName", usbDevice->GetProductName().c_str(), obj); + SetValueUtf8String(env, "version", usbDevice->GetVersion().c_str(), obj); + SetValueInt32(env, "vendorId", usbDevice->GetVendorId(), obj); + SetValueInt32(env, "productId", usbDevice->GetProductId(), obj); + SetValueInt32(env, "clazz", usbDevice->GetClass(), obj); + SetValueInt32(env, "subclass", usbDevice->GetSubclass(), obj); + SetValueInt32(env, "protocol", usbDevice->GetProtocol(), obj); + SetValueInt32(env, "devAddress", usbDevice->GetDevAddr(), obj); + SetValueInt32(env, "busNum", usbDevice->GetBusNum(), obj); + napi_value arr; + napi_create_array(env, &arr); + for (int32_t i = 0; i < usbDevice->GetConfigCount(); ++i) { + USBConfig usbConfig; + usbDevice->GetConfig(i, usbConfig); + napi_value obj; + CtoJSUsbConfig(env, obj, usbConfig); + napi_set_element(env, arr, i, obj); + } + napi_set_named_property(env, obj, "configs", arr); +} + +static UsbSrvClient &g_usbClient = UsbSrvClient::GetInstance(); + +/* ============================================= Parsers ============================================= */ +// js to c +static void ParseEndpointObj(napi_env env, napi_value endpointObj, USBEndpoint &ep) +{ + int32_t address, attributes, interval, maxPacketSize, interfaceId = 0; + JsObjectToInt(env, endpointObj, "address", address); + JsObjectToInt(env, endpointObj, "attributes", attributes); + JsObjectToInt(env, endpointObj, "interval", interval); + JsObjectToInt(env, endpointObj, "maxPacketSize", maxPacketSize); + JsObjectToInt(env, endpointObj, "interfaceId", interfaceId); + ep = USBEndpoint(address, attributes, interval, maxPacketSize); + ep.SetInterfaceId(interfaceId); +} + +static bool ParseEndpointsObjs(napi_env env, napi_value interfaceObj, std::vector &eps) +{ + // Get the array. + bool result = false; + napi_status status = napi_is_array(env, interfaceObj, &result); + if (result && status == napi_ok) { + napi_value endpointsObjs; + bool isGetObjSuccess = JsObjectGetProperty(env, interfaceObj, "endpoints", &endpointsObjs); + if (!isGetObjSuccess) { + return false; + } + + uint32_t endpointCount = 0; + status = napi_get_array_length(env, endpointsObjs, &endpointCount); + + for (uint32_t k = 0; k < endpointCount; ++k) { + napi_value endpointObj; + napi_status status = napi_get_element(env, endpointsObjs, k, &endpointObj); + if (status != napi_ok) { + return false; + } + USBEndpoint ep; + ParseEndpointObj(env, endpointObj, ep); + eps.push_back(ep); + } + } + + return false; +} + +struct PipeControlParam { + int32_t request; + int32_t target; + int32_t reqType; + int32_t value; + int32_t index; + uint8_t *data; + size_t dataLength; +}; + +static void ParsePipeControlParam(napi_env env, napi_value jsObj, PipeControlParam &controlParam) +{ + int32_t request, target, reqType, value, index = 0; + JsObjectToInt(env, jsObj, "request", request); + JsObjectToInt(env, jsObj, "target", target); + JsObjectToInt(env, jsObj, "reqType", reqType); + JsObjectToInt(env, jsObj, "value", value); + JsObjectToInt(env, jsObj, "index", index); + + napi_value dataValue; + JsObjectGetProperty(env, jsObj, "data", &dataValue); + + uint8_t *data = nullptr; + size_t dataLength = 0; + size_t offset = 0; + JsUint8ArrayParse(env, dataValue, &data, dataLength, offset); + controlParam.request = request; + controlParam.target = target; + controlParam.reqType = reqType; + controlParam.value = value; + controlParam.index = index; + controlParam.data = data; + controlParam.dataLength = dataLength; +} + +static void ParseInterfaceObj(napi_env env, napi_value interfaceObj, UsbInterface &interface) +{ + int32_t mId, mProtocol, mClass, mSubClass, mAlternateSetting = 0; + std::string mName; + JsObjectToInt(env, interfaceObj, "id", mId); + JsObjectToInt(env, interfaceObj, "protocol", mProtocol); + JsObjectToInt(env, interfaceObj, "clazz", mClass); + JsObjectToInt(env, interfaceObj, "subclass", mSubClass); + JsObjectToInt(env, interfaceObj, "alternateSetting", mAlternateSetting); + JsObjectToString(env, interfaceObj, "name", 32, mName); + std::vector eps; + ParseEndpointsObjs(env, interfaceObj, eps); + interface = UsbInterface(mId, mProtocol, mClass, mSubClass, mAlternateSetting, mName, eps); +} + +static bool ParseInterfacesObjs(napi_env env, napi_value configObj, std::vector &interfaces) +{ + bool result = false; + napi_status status = napi_is_array(env, configObj, &result); + if (result && status == napi_ok) { + napi_value interfacesObjs; + bool isGetObjSuccess = JsObjectGetProperty(env, configObj, "interfaces", &interfacesObjs); + if (!isGetObjSuccess) { + return false; + } + uint32_t interfaceCount = 0; + status = napi_get_array_length(env, interfacesObjs, &interfaceCount); + for (uint32_t i = 0; i < interfaceCount; ++i) { + napi_value interfaceObj; + napi_status status = napi_get_element(env, interfacesObjs, i, &interfaceObj); + if (status != napi_ok) { + return false; + } + UsbInterface interface; + ParseInterfaceObj(env, interfaceObj, interface); + interfaces.push_back(interface); + } + } + + return false; +} + +static void ParseConfigObj(napi_env env, napi_value configObj, USBConfig &config) +{ + int32_t id, attributes, maxPower = 0; + std::string name; + JsObjectToInt(env, configObj, "id", id); + JsObjectToInt(env, configObj, "attributes", attributes); + JsObjectToInt(env, configObj, "maxPower", maxPower); + JsObjectToString(env, configObj, "name", 32, name); + + std::vector interfaces; + ParseInterfacesObjs(env, configObj, interfaces); + config = USBConfig(id, attributes, name, maxPower, interfaces); +} + +static void ParseConfigsObjs(napi_env env, napi_value deviceObj, std::vector &configs) +{ + napi_value configsObj; + JsObjectGetProperty(env, deviceObj, "configs", &configsObj); + napi_valuetype valueType; + napi_typeof(env, configsObj, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_object, "Wrong argument type. object expected."); + + uint32_t configCount = 0; + napi_get_array_length(env, configsObj, &configCount); + for (uint32_t i = 0; i < configCount; ++i) { + napi_value configObj; + napi_get_element(env, configsObj, i, &configObj); + USBConfig config; + ParseConfigObj(env, configObj, config); + configs.push_back(config); + } +} + +static void ParseUsbDevicePipe(napi_env env, napi_value &obj, USBDevicePipe &pip) +{ + napi_valuetype valueType; + napi_typeof(env, obj, &valueType); + NAPI_ASSERT_RETURN_VOID(env, valueType == napi_object, "Wrong argument type. object expected."); + + int32_t busNum = 0; + JsObjectToInt(env, obj, "busNum", busNum); + pip.SetBusNum((uint8_t)busNum); + int32_t devAddr = 0; + JsObjectToInt(env, obj, "devAddress", devAddr); + pip.SetDevAddr((uint8_t)devAddr); +} + +static long getTimeDiff(timeval startTime, timeval endTime) +{ + return (endTime.tv_sec - startTime.tv_sec) * MSEC_TIME + (endTime.tv_usec - startTime.tv_usec) / MSEC_TIME; +} + +/* ============================================= Usb Core ============================================= */ + +static napi_value CoreGetDevices(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + + std::vector deviceList; + int32_t ret = g_usbClient.GetDevices(deviceList); + napi_value result; + if (ret != ERR_OK) { + napi_get_undefined(env, &result); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, get device faild ret : %{public}d", __func__, ret); + return result; + } + + napi_create_array(env, &result); + int32_t i = 0; + for (auto &ent1 : deviceList) { + napi_value element; + napi_create_object(env, &element); + napi_value device; + CtoJSUsbDevice(env, device, &ent1); + napi_set_element(env, result, i, device); + ++i; + } + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreConnectDevice(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_value deviceObj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, deviceObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + UsbDevice dev; + std::string mName, mManufacturerName, mProductName, mVersion; + int32_t devAddr, busNum, mVendorId, mProductId, mClass, mSubclass, mProtocol = 0; + JsObjectToString(env, deviceObj, "name", 32, mName); /* manufacturer max length is 32 + '\0' */ + JsObjectToString(env, deviceObj, "manufacturerName", 32, + mManufacturerName); /* manufacturer max length is 32 + '\0' */ + JsObjectToString(env, deviceObj, "productName", 32, mProductName); + JsObjectToString(env, deviceObj, "version", 32, mVersion); + JsObjectToInt(env, deviceObj, "devAddress", devAddr); + JsObjectToInt(env, deviceObj, "busNum", busNum); + JsObjectToInt(env, deviceObj, "vendorId", mVendorId); + JsObjectToInt(env, deviceObj, "productId", mProductId); + JsObjectToInt(env, deviceObj, "clazz", mClass); + JsObjectToInt(env, deviceObj, "subclass", mSubclass); + JsObjectToInt(env, deviceObj, "protocol", mProtocol); + std::vector configs; + ParseConfigsObjs(env, deviceObj, configs); + dev = UsbDevice(mName, mManufacturerName, mProductName, mVersion, devAddr, busNum, mVendorId, mProductId, mClass, + mSubclass, mProtocol, configs); + USBDevicePipe pip; + int32_t ret = g_usbClient.OpenDevice(dev, pip); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms, ret : %{public}d", __func__, + getTimeDiff(start, end), ret); + napi_value pipObj = nullptr; + if (ret == ERR_OK) { + CreateUsbDevicePipe(env, pipObj, pip); + return pipObj; + } else if (ret == ERR_PERMISSION_DENIED) { + napi_throw_error(env, nullptr, "permission denied, need call requestRight to get permission"); + return pipObj; + } else { + napi_get_undefined(env, &pipObj); + return pipObj; + } +} + +static napi_value CoreHasRight(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value args[PARAM_COUNT_1] = {0}; + napi_value jsthis; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + + NAPI_ASSERT(env, type == napi_string, "Wrong argument type. String expected."); + + std::string deviceName; + JsValueToString(env, args[INDEX_0], STR_DEFAULT_SIZE, deviceName); + int32_t result = g_usbClient.HasRight(deviceName); + USB_HILOGD(MODULE_JS_NAPI, "client called result %{public}d", result); + + napi_value napiValue = nullptr; + napi_get_boolean(env, result == ERR_OK, &napiValue); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return napiValue; +} + +static napi_value CoreRequestRight(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value args[PARAM_COUNT_1] = {0}; + napi_value jsthis; + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + NAPI_ASSERT(env, type == napi_string, "Wrong argument type. String expected."); + std::string deviceName; + JsValueToString(env, args[INDEX_0], STR_DEFAULT_SIZE, deviceName); + + auto *asyncContext = new USBRightAsyncContext(); + asyncContext->env = env; + asyncContext->deviceName = deviceName; + + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "RequestRight", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBRightAsyncContext *asyncContext = (USBRightAsyncContext *)data; + int32_t ret = g_usbClient.RequestRight(asyncContext->deviceName); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call CoreRequestRight async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBRightAsyncContext *asyncContext = (USBRightAsyncContext *)data; + napi_value queryResult = nullptr; + napi_get_boolean(env, asyncContext->status == napi_ok, &queryResult); + + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreUsbFunctionsFromString(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_string, "Wrong argument type. String expected."); + + // get value string argument of napi converted. + std::string funcs; + JsValueToString(env, argv[INDEX_0], STR_DEFAULT_SIZE, funcs); + + int32_t numFuncs = g_usbClient.UsbFunctionsFromString(funcs); + + napi_value result; + napi_create_int32(env, numFuncs, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreUsbFunctionsToString(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. String expected."); + + int32_t funcs; + napi_get_value_int32(env, argv[INDEX_0], &funcs); + std::string strFuncs = g_usbClient.UsbFunctionsToString(funcs); + + napi_value result; + napi_create_string_utf8(env, strFuncs.c_str(), NAPI_AUTO_LENGTH, &result); + + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreSetCurrentFunctions(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + + int32_t funcs = 0; + napi_get_value_int32(env, argv[INDEX_0], &funcs); + + auto *asyncContext = new USBFunctionAsyncContext(); + asyncContext->env = env; + asyncContext->functions = funcs; + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "SetCurrentFunctions", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBFunctionAsyncContext *asyncContext = (USBFunctionAsyncContext *)data; + int32_t ret = g_usbClient.SetCurrentFunctions(asyncContext->functions); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call CoreSetCurrentFunctions async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBFunctionAsyncContext *asyncContext = (USBFunctionAsyncContext *)data; + napi_value queryResult = nullptr; + napi_get_boolean(env, asyncContext->status == napi_ok, &queryResult); + + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreGetCurrentFunctions(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + int32_t cfuncs; + int32_t ret = g_usbClient.GetCurrentFunctions(cfuncs); + napi_value result; + if (ret != ERR_OK) { + napi_get_undefined(env, &result); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, get ports faild ret : %{public}d", __func__, ret); + return result; + } + napi_create_int32(env, cfuncs, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value CoreGetPorts(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + + std::vector ports; + + int32_t ret = g_usbClient.GetPorts(ports); + napi_value result; + if (ret != ERR_OK) { + napi_get_undefined(env, &result); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, get ports faild ret : %{public}d", __func__, ret); + return result; + } + + napi_create_array(env, &result); + for (uint32_t i = 0; i < ports.size(); ++i) { + napi_value port; + napi_create_object(env, &port); + SetValueInt32(env, "id", ports[i]->id, port); + SetValueInt32(env, "supportedModes", ports[i]->supportedModes, port); + napi_value usbPortStatus; + napi_create_object(env, &usbPortStatus); + SetValueInt32(env, "currentMode", ports[i]->usbPortStatus->currentMode, usbPortStatus); + SetValueInt32(env, "currentPowerRole", ports[i]->usbPortStatus->currentPowerRole, usbPortStatus); + SetValueInt32(env, "currentDataRole", ports[i]->usbPortStatus->currentDataRole, usbPortStatus); + napi_set_named_property(env, port, "status", usbPortStatus); + napi_set_element(env, result, i, port); + } + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +/* ============================================= Usb Port ============================================= */ + +static napi_value PortGetSupportedModes(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value args[PARAM_COUNT_1] = {0}; + napi_value jsthis; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + + int32_t id = 0; + int32_t result = 0; + napi_get_value_int32(env, args[INDEX_0], &id); + int32_t ret = g_usbClient.GetSupportedModes(id, result); + if (ret) { + USB_HILOGD(MODULE_JS_NAPI, "%{public}s:false ret = %{public}d", __func__, ret); + } + napi_value napiValue = nullptr; + NAPI_CALL(env, napi_create_int32(env, result, &napiValue)); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, result : %{public}d, takes : %{public}ld ms", __func__, result, + getTimeDiff(start, end)); + return napiValue; +} + +static napi_value PortSetPortRole(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_3; + napi_value args[PARAM_COUNT_3] = {0}; + napi_value jsthis; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, args, &jsthis, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_valuetype type; + NAPI_CALL(env, napi_typeof(env, args[INDEX_0], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + NAPI_CALL(env, napi_typeof(env, args[INDEX_1], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + NAPI_CALL(env, napi_typeof(env, args[INDEX_2], &type)); + NAPI_ASSERT(env, type == napi_number, "Wrong argument type. Number expected."); + + int32_t id, powerRole, dataRole = 0; + napi_get_value_int32(env, args[INDEX_0], &id); + napi_get_value_int32(env, args[INDEX_1], &powerRole); + napi_get_value_int32(env, args[INDEX_2], &dataRole); + + auto *asyncContext = new USBPortRoleAsyncContext(); + asyncContext->env = env; + asyncContext->portId = id; + asyncContext->dataRole = dataRole; + asyncContext->powerRole = powerRole; + + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "PortSetPortRole", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBPortRoleAsyncContext *asyncContext = (USBPortRoleAsyncContext *)data; + int32_t ret = + g_usbClient.SetPortRole(asyncContext->portId, asyncContext->powerRole, asyncContext->dataRole); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call PortSetPortRole async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBPortRoleAsyncContext *asyncContext = (USBPortRoleAsyncContext *)data; + napi_value queryResult = nullptr; + + napi_get_boolean(env, asyncContext->status == napi_ok, &queryResult); + + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeClaimInterface(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_3; + napi_value argv[PARAM_COUNT_3] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + + UsbInterface interface; + napi_value obj2 = argv[INDEX_1]; + napi_typeof(env, obj2, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + ParseInterfaceObj(env, obj2, interface); + + bool isForce = false; + if (argc >= PARAM_COUNT_3) { + napi_typeof(env, argv[INDEX_2], &type); + NAPI_ASSERT(env, type == napi_boolean, "Wrong argument type. Object expected."); + napi_get_value_bool(env, argv[INDEX_2], &isForce); + } + + int32_t ret = pip.ClaimInterface(interface, isForce); + USB_HILOGD(MODULE_JS_NAPI, "pip call ClaimInterface ret: %{public}d", ret); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeReleaseInterface(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_2; + napi_value argv[PARAM_COUNT_2] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + + UsbInterface interface; + napi_value obj2 = argv[INDEX_1]; + ParseInterfaceObj(env, obj2, interface); + int32_t ret = pip.ReleaseInterface(interface); + USB_HILOGD(MODULE_JS_NAPI, "pip call PipeReleaseInterface ret: %{public}d", ret); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeSetInterface(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_2; + napi_value argv[PARAM_COUNT_2] = {0}; + napi_value thiz; + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_value pipeObj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, pipeObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, pipeObj, pip); + + napi_value interfaceObj = argv[INDEX_1]; + napi_typeof(env, interfaceObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + UsbInterface interface; + ParseInterfaceObj(env, interfaceObj, interface); + int32_t ret = g_usbClient.SetInterface(pip, interface); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeSetConfiguration(napi_env env, napi_callback_info info) +{ + struct timeval start; + gettimeofday(&start, nullptr); + + size_t argc = PARAM_COUNT_2; + napi_value argv[PARAM_COUNT_2] = {0}; + napi_value thiz; + void *data = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + napi_valuetype type; + napi_value pipeObj = argv[INDEX_0]; + + napi_typeof(env, pipeObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + USBDevicePipe pip; + ParseUsbDevicePipe(env, pipeObj, pip); + + napi_value configObj = argv[INDEX_1]; + napi_typeof(env, configObj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + USBConfig config; + ParseConfigObj(env, configObj, config); + + int32_t ret = g_usbClient.SetConfiguration(pip, config); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d, takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeGetRawDescriptors(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + + napi_value result; + int32_t ret = g_usbClient.GetRawDescriptors(nullptr, 0); + if (ret == ERR_OK) { + Uint8ArrayToJsValue(env, nullptr, 0, result); + } else { + napi_get_undefined(env, &result); + } + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, ret: %{public}d takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value PipeGetFileDescriptor(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + int32_t fd = g_usbClient.GetFileDescriptor(); + napi_value result; + SetValueInt32(env, "fd", fd, result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeControlTransfer(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + + size_t argc = PARAM_COUNT_3; + napi_value argv[PARAM_COUNT_3] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_2), "Failed to get cb info"); + + // pipe param + napi_value pipeObj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, pipeObj, &type); + NAPI_ASSERT(env, type == napi_object, "argv[INDEX_0] wrong argument type, object expected."); + USBDevicePipe pipe; + ParseUsbDevicePipe(env, pipeObj, pipe); + + // control params + PipeControlParam controlParam; + ParsePipeControlParam(env, argv[INDEX_1], controlParam); + + // timeout param + int32_t timeout = 0; + if (argc >= PARAM_COUNT_3) { + napi_get_value_int32(env, argv[INDEX_2], &timeout); + } + + auto *asyncContext = new USBControlTransferAsyncContext(); + asyncContext->env = env; + asyncContext->pipe = pipe; + asyncContext->request = controlParam.request; + asyncContext->target = controlParam.target; + asyncContext->reqType = controlParam.reqType; + asyncContext->value = controlParam.value; + asyncContext->index = controlParam.index; + + if ((asyncContext->reqType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT) { + uint8_t *nativeArraybuffer = new uint8_t[controlParam.dataLength]; + memcpy_s(nativeArraybuffer, controlParam.dataLength, controlParam.data, controlParam.dataLength); + asyncContext->buffer = nativeArraybuffer; + } else { + asyncContext->buffer = controlParam.data; + } + + asyncContext->bufferLength = controlParam.dataLength; + asyncContext->timeout = timeout; + napi_value result = nullptr; + napi_create_promise(env, &asyncContext->deferred, &result); + + napi_value resource = nullptr; + napi_create_string_utf8(env, "PipeControlTransfer", NAPI_AUTO_LENGTH, &resource); + + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + USBControlTransferAsyncContext *asyncContext = (USBControlTransferAsyncContext *)data; + int32_t ret = asyncContext->pipe.ControlTransfer( + asyncContext->reqType, asyncContext->request, asyncContext->value, asyncContext->index, + asyncContext->buffer, asyncContext->bufferLength, asyncContext->timeout); + if ((asyncContext->reqType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT) { + delete asyncContext->buffer; + asyncContext->buffer = nullptr; + } + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call PipeControlTransfer async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBControlTransferAsyncContext *asyncContext = (USBControlTransferAsyncContext *)data; + napi_value queryResult = nullptr; + + if (asyncContext->status == napi_ok) { + napi_create_int32(env, asyncContext->bufferLength, &queryResult); + } else { + napi_value message = nullptr; + napi_create_string_utf8(env, "PipeControlTransfer failed", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &queryResult); + } + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeBulkTransfer(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_4; + napi_value argv[PARAM_COUNT_4] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_3), "Failed to get cb info"); + + napi_valuetype type; + + USBDevicePipe pip; + napi_typeof(env, argv[INDEX_0], &type); + NAPI_ASSERT(env, type == napi_object, "argv[INDEX_0] wrong argument type, object expected"); + ParseUsbDevicePipe(env, argv[INDEX_0], pip); + + USBEndpoint ep; + napi_typeof(env, argv[INDEX_1], &type); + NAPI_ASSERT(env, type == napi_object, "argv[INDEX_1] Wrong argument type. Object expected."); + ParseEndpointObj(env, argv[INDEX_1], ep); + + uint8_t *buffer = nullptr; + size_t offset; + size_t bufferSize; + bool hasBuffer = JsUint8ArrayParse(env, argv[INDEX_2], &buffer, bufferSize, offset); + int32_t timeout = 0; + if (argc > PARAM_COUNT_3) { + napi_get_value_int32(env, argv[INDEX_3], &timeout); + } + + napi_value result = nullptr; + auto *asyncContext = new USBBulkTransferAsyncContext(); + napi_create_promise(env, &asyncContext->deferred, &result); + if (!hasBuffer) { + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s %{public}d : failed buffer is null", __func__, __LINE__); + asyncContext->status = napi_invalid_arg; + napi_value queryResult = nullptr; + napi_value message = nullptr; + napi_create_string_utf8(env, "Bulk transfer invalid arg", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &queryResult); + ProcessPromise(env, asyncContext, queryResult); + delete asyncContext; + return result; + } + + asyncContext->env = env; + asyncContext->pipe = pip; + asyncContext->endpoint = ep; + + if (ep.GetDirection() == USB_ENDPOINT_DIR_OUT) { + uint8_t *nativeArraybuffer = new uint8_t[bufferSize]; + memcpy_s(nativeArraybuffer, bufferSize, buffer, bufferSize); + asyncContext->buffer = nativeArraybuffer; + } else { + asyncContext->buffer = buffer; + } + + asyncContext->bufferLength = bufferSize; + asyncContext->timeout = timeout; + + napi_value resource = nullptr; + napi_create_string_utf8(env, "PipeBulkTransfer", NAPI_AUTO_LENGTH, &resource); + + status = napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + struct timeval beginAsync; + gettimeofday(&beginAsync, nullptr); + + USBBulkTransferAsyncContext *asyncContext = (USBBulkTransferAsyncContext *)data; + int32_t ret = asyncContext->pipe.BulkTransfer(asyncContext->endpoint, asyncContext->buffer, + asyncContext->bufferLength, asyncContext->timeout); + + if (asyncContext->endpoint.GetDirection() == USB_ENDPOINT_DIR_OUT) { + delete asyncContext->buffer; + asyncContext->buffer = nullptr; + } + + USB_HILOGD(MODULE_JS_NAPI, "call pipe result %{public}d", ret); + if (ret == ERR_OK) { + asyncContext->status = napi_ok; + } else { + asyncContext->status = napi_generic_failure; + } + struct timeval endAsync; + gettimeofday(&endAsync, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call PipeBulkTransfer async work finished, takes : %{public}ld ms", + getTimeDiff(beginAsync, endAsync)); + }, + [](napi_env env, napi_status status, void *data) { + USBBulkTransferAsyncContext *asyncContext = (USBBulkTransferAsyncContext *)data; + napi_value queryResult = nullptr; + if (asyncContext->status == napi_ok) { + napi_create_int32(env, asyncContext->bufferLength, &queryResult); + } else { + napi_value message = nullptr; + napi_create_string_utf8(env, "PipeBulkTransfer failed", NAPI_AUTO_LENGTH, &message); + napi_create_error(env, nullptr, message, &queryResult); + } + ProcessPromise(env, asyncContext, queryResult); + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + struct timeval end; + gettimeofday(&end, nullptr); + if (status != napi_ok) { + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, create async work failed, takes : %{public}ld ms", __func__, + getTimeDiff(start, end)); + return result; + } + napi_queue_async_work(env, asyncContext->work); + gettimeofday(&end, nullptr); + + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, takes : %{public}ld ms", __func__, getTimeDiff(start, end)); + return result; +} + +static napi_value PipeClose(napi_env env, napi_callback_info info) +{ + USB_HILOGD(MODULE_JS_NAPI, "begin call %{public}s", __func__); + struct timeval start; + gettimeofday(&start, nullptr); + size_t argc = PARAM_COUNT_1; + napi_value argv[PARAM_COUNT_1] = {0}; + napi_value thiz; + void *data = nullptr; + + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thiz, &data); + NAPI_ASSERT(env, (status == napi_ok) && (argc >= PARAM_COUNT_1), "Failed to get cb info"); + + napi_value obj = argv[INDEX_0]; + napi_valuetype type; + napi_typeof(env, obj, &type); + NAPI_ASSERT(env, type == napi_object, "Wrong argument type. Object expected."); + + USBDevicePipe pip; + ParseUsbDevicePipe(env, obj, pip); + int32_t ret = pip.Close(); + napi_value result; + napi_create_int32(env, ret, &result); + struct timeval end; + gettimeofday(&end, nullptr); + USB_HILOGD(MODULE_JS_NAPI, "end call %{public}s, result %{public}d, takes : %{public}ld ms", __func__, ret, + getTimeDiff(start, end)); + return result; +} + +static napi_value GetVersion(napi_env env, napi_callback_info info) +{ + std::string version = g_usbClient.GetVersion(); + USB_HILOGD(MODULE_JS_NAPI, "call %{public}s, version is %{public}s", __func__, version.c_str()); + napi_value result; + napi_create_string_utf8(env, version.c_str(), NAPI_AUTO_LENGTH, &result); + return result; +} + +EXTERN_C_START +/* + * function for module exports + */ +static napi_value UsbInit(napi_env env, napi_value exports) +{ + USB_HILOGD(MODULE_JS_NAPI, "enter"); + + napi_property_descriptor desc[] = { + /* usb core */ + DECLARE_NAPI_FUNCTION("getDevices", CoreGetDevices), DECLARE_NAPI_FUNCTION("connectDevice", CoreConnectDevice), + DECLARE_NAPI_FUNCTION("hasRight", CoreHasRight), DECLARE_NAPI_FUNCTION("requestRight", CoreRequestRight), + DECLARE_NAPI_FUNCTION("usbFunctionsFromString", CoreUsbFunctionsFromString), + DECLARE_NAPI_FUNCTION("usbFunctionsToString", CoreUsbFunctionsToString), + DECLARE_NAPI_FUNCTION("setCurrentFunctions", CoreSetCurrentFunctions), + DECLARE_NAPI_FUNCTION("getCurrentFunctions", CoreGetCurrentFunctions), + DECLARE_NAPI_FUNCTION("getPorts", CoreGetPorts), + + /* usb port */ + DECLARE_NAPI_FUNCTION("getSupportedModes", PortGetSupportedModes), + DECLARE_NAPI_FUNCTION("setPortRoles", PortSetPortRole), + + /* usb device pipe */ + DECLARE_NAPI_FUNCTION("claimInterface", PipeClaimInterface), + DECLARE_NAPI_FUNCTION("releaseInterface", PipeReleaseInterface), + DECLARE_NAPI_FUNCTION("bulkTransfer", PipeBulkTransfer), + DECLARE_NAPI_FUNCTION("controlTransfer", PipeControlTransfer), + DECLARE_NAPI_FUNCTION("setInterface", PipeSetInterface), + DECLARE_NAPI_FUNCTION("setConfiguration", PipeSetConfiguration), + DECLARE_NAPI_FUNCTION("getRawDescriptor", PipeGetRawDescriptors), + DECLARE_NAPI_FUNCTION("getFileDescriptor", PipeGetFileDescriptor), + DECLARE_NAPI_FUNCTION("closePipe", PipeClose), + + /* fort test get usb service version */ + DECLARE_NAPI_FUNCTION("getVersion", GetVersion)}; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + + USB_HILOGD(MODULE_JS_NAPI, "return"); + + return exports; +} +EXTERN_C_END + +/* + * Module definition + */ +static napi_module g_module = {.nm_version = 1, + .nm_flags = 0, + .nm_filename = "usb", + .nm_register_func = UsbInit, + .nm_modname = "usb", + .nm_priv = ((void *)0), + .reserved = {0}}; + +/* + * Module registration + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&g_module); +} diff --git a/interfaces/kits/js/test/CheckEmptyUtils.js b/interfaces/kits/js/test/CheckEmptyUtils.js new file mode 100644 index 00000000..cc244d5a --- /dev/null +++ b/interfaces/kits/js/test/CheckEmptyUtils.js @@ -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. + */ + +export default { + + /** + * Check obj is empty. + * + * @param {object} obj + * @return {boolean} true(empty) + */ + isEmpty(obj) { + return (typeof obj == 'undefined' || obj == null || JSON.stringify(obj) == '{}' || JSON.stringify(obj) == 'undefined'); + }, + + /** + * Check str is empty. + * + * @param {string} str + * @return {boolean} true(empty) + */ + checkStrIsEmpty(str) { + return str.trim().length == 0; + }, + + /** + * Check array is empty. + * + * @param {Array}arr + * @return {boolean} true(empty) + */ + isEmptyArr(arr) { + return arr.length == 0; + }, + + // ArrayBuffer转为字符串,参数为ArrayBuffer对象 + ab2str(buf) { + return String.fromCharCode.apply(null, new Uint8Array(buf)); + }, + + // 字符串转为ArrayBuffer对象,参数为字符串 + str2ab(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpUint8Array = new Uint8Array(arr); + return tmpUint8Array; + }, + + // 简单阻塞的粗暴实现 + sleep(delay) { + for (var t = Date.now(); Date.now() - t <= delay;); + } +} + \ No newline at end of file diff --git a/interfaces/kits/js/test/DateAndTimeUtil.js b/interfaces/kits/js/test/DateAndTimeUtil.js new file mode 100644 index 00000000..09ab1bdb --- /dev/null +++ b/interfaces/kits/js/test/DateAndTimeUtil.js @@ -0,0 +1,114 @@ +/** + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const twelve = 12; +/** + * date package tool class + */ +export default class DateAndTimeUtil{ + constructor() { + }; + /** + * + * Get the current time + */ + now() { + const datetime = new Date(); + const hours = datetime.getHours(); + const minutes = datetime.getMinutes(); + return this.concatTime(hours, minutes); + }; + + /** + * + * Get the current time + */ + nowWithSeconds() { + const datetime = new Date(); + const hours = datetime.getHours(); + const minutes = datetime.getMinutes(); + const seconds = datetime.getMilliseconds() + console.info("now: " + hours + ":" + minutes + ":" + seconds) + var now = this.concatTimeWithSeconds(hours, minutes, seconds); + console.info("now concat: " + now); + return now; + }; + + /** + * format + * @param value + * @return + */ + fill(value) { + return (value > 9 ? "" : "0") + value; + }; + /** + * concat date + * @param year m d + * @return + */ + concatDate(year, month, date) { + return year + this.year + month + this.month + date + this.day; + }; + + concatTime(hours, minutes) { + return `${this.fill(hours)}:${this.fill(minutes)}`; + }; + + concatTimeWithSeconds(hours, minutes, milliseconds) { + return `${this.fill(hours)}:${this.fill(minutes)}:${this.fill(milliseconds)}`; + }; + /** + * Turn to 24-hour clock + * @param str + * @return + */ + transform24(str) { + const timeFlag = str.substr(0, 2); + if (timeFlag == this.morning) { + const h = str.substr(2).split(":")[0]; + if (h == twelve) { + const time = "0" + ":" + str.substr(2).split(":")[1]; + return time; + } else { + return h + ":" + str.substr(2).split(":")[1]; + } + } else { + const h = str.substr(2).split(":")[0]; + const h1 = parseInt(h) + twelve; + if (h != twelve) { + const time = h1 + ":" + str.substr(2).split(":")[1]; + return time; + } + } + }; + /** + * Turn to 12-hour clock + * @param str + * @return + */ + transform12(str) { + const hours = str.substring(0, str.indexOf(":")); + const minutes = str.split(":")[1]; + if (hours < twelve) { + return this.morning.concat(`${hours}:${minutes}`); + } + if (hours == twelve) { + return this.afternoon.concat(`${hours}:${minutes}`); + } else { + const reduceHours = parseInt(hours) - twelve; + return this.afternoon.concat(`${reduceHours}:${minutes}`); + } + }; +} diff --git a/interfaces/kits/js/test/EventConstants.js b/interfaces/kits/js/test/EventConstants.js new file mode 100644 index 00000000..728c4fa2 --- /dev/null +++ b/interfaces/kits/js/test/EventConstants.js @@ -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. + */ + +/** + * Constants of events that will be registered to system. + */ +const EventConstants = { + /** + * Bitmask used for extracting the USBEndpoint type from it's address + */ + USB_ENDPOINT_XFERTYPE_MASK : 0x03, + + /** + * Control USBEndpoint type + */ + USB_ENDPOINT_XFER_CONTROL : 0, + + /** + * Isochronous USBEndpoint type + */ + USB_ENDPOINT_XFER_ISOC : 1, + + /** + * Bulk USBEndpoint type + */ + USB_ENDPOINT_XFER_BULK : 2, + + /** + * Interrupt USBEndpoint type + */ + USB_ENDPOINT_XFER_INT : 3, + + /** + * Bitmask used for extracting the USBEndpoint number from it's address + */ + USB_ENDPOINT_NUMBER_MASK : 0x0f, + + /** + * Bitmask used for extracting the USBEndpoint direction from it's address + */ + USB_ENDPOINT_DIR_MASK : 0x80, + + /** + * Used to signify direction of data for USBEndpoint is OUT, host to device + */ + USB_ENDPOINT_DIR_OUT : 0, + + /** + * Used to signify direction of data for USBEndpoint is IN, device to host + */ + USB_ENDPOINT_DIR_IN : 0x80 +} + +export default EventConstants; \ No newline at end of file diff --git a/interfaces/kits/js/test/ListUsb.test.js b/interfaces/kits/js/test/ListUsb.test.js new file mode 100644 index 00000000..0fb646b7 --- /dev/null +++ b/interfaces/kits/js/test/ListUsb.test.js @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +/* host test case */ +require('./UsbCoreJsunit.test.js') +require('./UsbDevicePipeJsunit.test.js') + +/* device test case */ +require('./UsbFunctionsJsunit.test.js') + +/* device and host test case */ +require('./UsbPortJsunit.test.js') diff --git a/interfaces/kits/js/test/UsbCoreJsunit.test.js b/interfaces/kits/js/test/UsbCoreJsunit.test.js new file mode 100644 index 00000000..73b0b7b0 --- /dev/null +++ b/interfaces/kits/js/test/UsbCoreJsunit.test.js @@ -0,0 +1,254 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + + +/* usb core functions test */ +describe('UsbCoreJsFunctionsTest', function () { + + beforeAll(function () { + console.log("*************Usb Unit UsbCoreJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("begin test getversion :" + Version) + // 切换为host + var usbPortList = usb.getPorts() + if (usbPortList.length > 0){ + if (usbPortList[0].status.currentMode == 2){ + usb.setPortRoles(usbPortList[0].id, 1, 1).then(data => { + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + }); + console.log("*************Usb Unit Begin switch to host*************"); + } + } + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + console.log("*************Usb Unit UsbCoreJsFunctionsTest End*************"); + }) + + var g_device_list + + /* * + * @tc.number : get_devices_test_01 + * @tc.name : getDevices + * @tc.desc : 获取设备列表 + */ + it('get_devices_test_01', 0, function () { + console.info('usb get_device_01 begin'); + g_device_list = usb.getDevices(); + if (g_device_list.length == 0) { + console.info("usb case get_devices list is null") + expect(false).assertTrue(); + return + } + console.info('usb get_devices_test_01: PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : connect_device_01 + * @tc.name : connectDevice + * @tc.desc : 打开设备 关闭设备 + */ + it('connect_device_01', 0, function () { + console.info('usb connect_device_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var usbDevicePipe = usb.connectDevice(g_device_list[i]) + var isPipClose = usb.closePipe(usbDevicePipe); + expect(isPipClose == 0).assertTrue(); + } + + console.info('usb connect_device_01 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : connect_device_02 + * @tc.name : connectDevice + * @tc.desc : 反向测试 错误参数 打开设备失败 即通过 + */ + it('connect_device_02', 0, function () { + console.info('usb connect_device_02 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var device = g_device_list[i] + device.busNum = i + 1000 + device.devAddress = i + 10000 + var usbDevicePipe = usb.connectDevice(device) + expect(CheckEmptyUtils.isEmpty(usbDevicePipe)).assertTrue(); + } + + console.info('usb connect_device_02 : PASS'); + }) + + /* * + * @tc.number : has_right_01 + * @tc.name : hasRight + * @tc.desc : 权限查询 连接设备 关闭设备 + */ + it('has_right_01', 0, function () { + console.info('usb has_right_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var hasRight = usb.hasRight(g_device_list[i].name) + expect(hasRight).assertTrue(); + if (hasRight){ + var pip = usb.connectDevice(g_device_list[i]); + expect(CheckEmptyUtils.isEmpty(pip)).assertTrue(); + if (!CheckEmptyUtils.isEmpty(pip)){ + var isPipClose = usb.closePipe(pip); + expect(isPipClose == 0).assertTrue(); + } + } + } + + console.info('usb has_right_01 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : has_right_02 + * @tc.name : hasRight + * @tc.desc : 反向测试 给错误设备名字 + */ + + it('has_right_02', 0, function () { + console.info('usb has_right_02 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var deviceName = g_device_list[i].name + deviceName = deviceName + "$#" + var hasRight = usb.hasRight(deviceName) + expect(hasRight == false).assertTrue(); + } + + console.info('usb has_right_02 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : request_right_01 + * @tc.name : requestRight + * @tc.desc : 请求权限 + */ + it('request_right_01', 0, function () { + console.info('usb request_right_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + usb.requestRight(g_device_list[i].name).then(hasRight=>{ + expect(hasRight).assertTrue(); + console.info('usb request_right_01 : PASS'); + }).catch(error=>{ + console.info("usb case device request right failed : " + error + ' :' + g_device_list[i].name); + expect(false).assertTrue(); + }); + } + }) + + /* * + * @tc.number : request_right_02 + * @tc.name : requestRight + * @tc.desc : 反向测试 错误设备名字 请求权限 + */ + it('request_right_02', 0, function () { + console.info('usb request_right_02 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + for (var i = 0; i < g_device_list.length; i++){ + var diviceName = g_device_list[i].name + diviceName = diviceName + "@#" + usb.requestRight(diviceName).then(hasRight=>{ + expect(hasRight).assertFalse(); + console.info('usb request_right_02 : PASS'); + }).catch(error=>{ + expect(error).assertFalse(); + console.info('usb request_right_02 error: ' + error); + }); + } + }) + + + /* * + * @tc.number : get_file_descriptor_test_01 + * @tc.name : get_file_descriptor + * @tc.desc : 获取文件描述符 + */ + it('get_file_descriptor_test_01', 0, function () { + console.info('usb get_file_descriptor_test_01 begin'); + if (g_device_list.length == 0) { + console.info("usb get_device_list is null") + return; + } + + for (var i = 0; i < g_device_list.length; i++) { + console.info("usb get_devices device: " + JSON.stringify(g_device_list[i])); + var usbDevicePipe = usb.connectDevice(g_device_list[i]) + console.info("usb connect return usbDevicePipe: " + JSON.stringify(usbDevicePipe)); + + if (!CheckEmptyUtils.isEmpty(usbDevicePipe)){ + var retFileDescriptor = usb.getFileDescriptor(usbDevicePipe) + console.info("usb getFileDescriptor return: " + retFileDescriptor); + expect(retFileDescriptor >= 0).assertTrue() + + var ret = usb.closePipe(usbDevicePipe) + console.info("usb closePipe return code: " + ret); + expect(ret == 0).assertTrue() + } + } + + console.info('usb get_file_descriptor_test_01 : PASS'); + }) + +}) diff --git a/interfaces/kits/js/test/UsbDevicePipeJsunit.test.js b/interfaces/kits/js/test/UsbDevicePipeJsunit.test.js new file mode 100644 index 00000000..56206be4 --- /dev/null +++ b/interfaces/kits/js/test/UsbDevicePipeJsunit.test.js @@ -0,0 +1,358 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import EventConstants from './EventConstants.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +/* usb device pipe test */ +describe('UsbDevicePipeJsFunctionsTest', function () { + var g_device_list + var g_pipe + + beforeAll(function () { + console.log("*************Usb Unit UsbDevicePipeJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("usb unit begin test getversion :" + Version) + + // 切换为host + var usbPortList = usb.getPorts() + if (usbPortList.length > 0){ + if (usbPortList[0].status.currentMode == 2){ + usb.setPortRoles(usbPortList[0].id, 1, 1).then(data => { + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + }); + console.log("*************Usb Unit switch to host Begin*************"); + } + } + + g_device_list = usb.getDevices(); + g_pipe = usb.connectDevice(g_device_list[0]) + console.info("usb unit connectDevice g_pipe ret : " + JSON.stringify(g_pipe)); + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + var isPipClose = usb.closePipe(g_pipe) + console.info("usb unit close g_pipe ret : " + isPipClose); + console.log("*************Usb Unit UsbDevicePipeJsFunctionsTest End*************"); + }) + + // 预制传输相关参数 + function getTransferTestParam() { + var testParam = { + device: null, + config: null, + pip: null, + inEndpoint: null, + outEndpoint: null, + interface: null, + usbRequest: null, + sendData:"", + isClaimed: 0, + maxInSize: 1024, + maxOutSize:1024 + } + + console.info("usb case g_device_list.length: " + g_device_list.length); + for (var i = 0; i < g_device_list.length; i++) + { + testParam.device = g_device_list[i] + testParam.config = testParam.device.configs[0] + testParam.pip = g_pipe + for (var j = 0; j < testParam.config.interfaces.length; j++){ + if (testParam.config.interfaces[j].endpoints.length == 0){ + continue + } + + var bfind = false + for (var k = 0; k < testParam.config.interfaces[j].endpoints.length; k++){ + var endpoint = testParam.config.interfaces[j].endpoints[k]; + if (endpoint.type == EventConstants.USB_ENDPOINT_XFER_BULK) { + bfind = true + if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_OUT) { + testParam.outEndpoint = endpoint; + testParam.maxOutSize = endpoint.maxPacketSize; + } else if (endpoint.direction == EventConstants.USB_ENDPOINT_DIR_IN) { + testParam.inEndpoint = endpoint + testParam.maxInSize = endpoint.maxPacketSize; + } + } + } + if (bfind){ + testParam.interface = testParam.config.interfaces[j] + break + } + } + } + + return testParam + } + + /* * + * @tc.number : bulk_transfer_test_01 + * @tc.name : bulkTransfer + * @tc.desc : 批量传输 收数据 + */ + it('bulk_transfer_test_01', 0, function () { + console.info('usb bulk_transfer_test_01 begin'); + var testParam = getTransferTestParam() + if (testParam.interface == null || testParam.inEndpoint == null ){ + expect(false).assertTrue(); + return + } + + testParam.isClaimed = usb.releaseInterface(testParam.pip, testParam.interface) + expect(testParam.isClaimed).assertTrue(); + testParam.isClaimed = usb.claimInterface(testParam.pip, testParam.interface, true); + expect(testParam.isClaimed).assertTrue(); + + console.info("usb case readData begin"); + var tmpUint8Array = new Uint8Array(testParam.maxInSize); + usb.bulkTransfer(testParam.pip, testParam.inEndpoint, tmpUint8Array,5000).then(data =>{ + console.info("usb case readData tmpUint8Array buffer : " + CheckEmptyUtils.ab2str(tmpUint8Array)); + console.info('usb case bulk_transfer_test_01 : PASS'); + expect(true).assertTrue(); + }).catch(error=>{ + console.info("usb case readData error : " + JSON.stringify(error)); + expect(false).assertTrue(); + }); + }) + + /* * + * @tc.number : bulk_transfer_test_02 + * @tc.name : bulkTransfer + * @tc.desc : 批量传输 发数据 + */ + it('bulk_transfer_test_02', 0, function () { + console.info('usb bulk_transfer_test_02 begin'); + var testParam = getTransferTestParam() + if (testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + testParam.isClaimed = usb.releaseInterface(testParam.pip, testParam.interface) + expect(testParam.isClaimed).assertTrue(); + testParam.isClaimed = usb.claimInterface(testParam.pip, testParam.interface, true); + expect(testParam.isClaimed).assertTrue(); + + testParam.sendData = "send time 13213213 wzy"; + var tmpUint8Array = CheckEmptyUtils.str2ab(testParam.sendData); + usb.bulkTransfer(testParam.pip, testParam.outEndpoint, tmpUint8Array,5000).then(data =>{ + console.info("usb case write length : " + data); + console.info("usb case readData tmpUint8Array buffer : " + CheckEmptyUtils.ab2str(tmpUint8Array)); + console.info('usb case bulk_transfer_test_02 : PASS'); + expect(true).assertTrue(); + }).catch(error=>{ + console.info("usb write error : " + JSON.stringify(error)); + expect(false).assertTrue(); + }); + + }) + + /* * + * @tc.number : claim_interface_test_01 + * @tc.name : claimInterface + * @tc.desc : 获取接口 并释放 + */ + it('claim_interface_test_01', 0, function () { + console.info('usb claim_interface_test_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + + if(g_device_list[0].configs.length == 0){ + console.info("usb case current device.configs.length = 0"); + expect(false).assertTrue(); + return + } + + for (var j = 0; j < g_device_list[0].configs.length; j++){ + if(g_device_list[0].configs[j].interfaces.length == 0){ + console.info("usb case current device.configs.interfaces.length = 0"); + } + for (var k = 0; k < g_device_list[0].configs[j].interfaces.length; k++){ + var isClaim = usb.claimInterface(g_pipe, g_device_list[0].configs[j].interfaces[k], true) + console.info("usb case claimInterface function return: " + isClaim); + expect(isClaim).assertTrue(); + if (isClaim){ + isClaim = usb.releaseInterface(g_pipe, g_device_list[0].configs[j].interfaces[k]) + console.info("usb case releaseInterface function return: " + isClaim); + expect(isClaim).assertTrue(); + } + } + } + + console.info('usb claim_interface_test_01 : PASS'); + expect(true).assertTrue(); + }) + + function getTransferParam(iCmd, iReqType, iValue, iIndex) { + var tmpUint8Array = new Uint8Array(512); + var requestCmd = iCmd + var requestType = iReqType + var value = iValue; + var index = iIndex; + var controlParam = { + request: requestCmd, + reqType: requestType, + value: value, + index: index, + data: tmpUint8Array + } + return controlParam + } + + /* * + * @tc.number : set_interface_test_01 + * @tc.name : setInterface + * @tc.desc : 设置设备接口 + */ + it('set_interface_test_01', 0, function () { + console.info('usb set_interface_test_01 begin'); + if (g_device_list.length == 0) { + console.info("usb case get_device_list is null") + expect(false).assertTrue(); + return + } + var timeout = 5000; + // SetInterface cmd 11 reqType 0 value 1 index 0 + var controlParam = getTransferParam(1, 0, 1, 0) + + for (var j = 0; j < g_device_list[0].configs.length; j++){ + var ret = usb.setInterface(g_pipe, g_device_list[0].configs[j].interfaces[1]) + console.info("usb case setInterface return : " + ret); + expect(ret).assertTrue(); + } + + console.info('usb set_interface_test_01 : PASS'); + expect(true).assertTrue(); + }) + + + function callControlTransfer(pip, controlParam, timeout, caseName) { + usb.controlTransfer(pip, controlParam, timeout).then(data =>{ + console.info("usb controlTransfer ret data : " + data + " " + caseName); + console.info("usb controlTransfer controlParam.data buffer : " + controlParam.data + " " + caseName); + console.info('usb' + caseName + ': PASS'); + expect(true).assertTrue(); + }).catch(error=>{ + console.info("usb controlTransfer error : " + JSON.stringify(error)); + console.info('usb' + caseName + ': PASS'); + expect(false).assertTrue(); + }); + } + + /* * + * @tc.number : control_transfer_test_01 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetDescriptor: cmd 6 reqType 128 value 512 index 0 + */ + it('control_transfer_test_01', 0, function () { + console.info('usb control_transfer_test_01 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(6, ((1 << 7) | (0 << 5) | (0 & 0x1f)), (2 << 8), 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_01 GetDescriptor") + }) + + /* * + * @tc.number : control_transfer_test_02 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetStatus: cmd 0 reqType 128 value 0 index 0 + */ + it('control_transfer_test_02', 0, function () { + console.info('usb control_transfer_test_02 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(0, 128, 0, 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_02 GetStatus") + }) + + /* * + * @tc.number : control_transfer_test_03 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetConfiguration: cmd 8 reqType 128 value 0 index 0 + */ + it('control_transfer_test_03', 0, function () { + console.info('usb control_transfer_test_03 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(8, 128, 0, 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_03 GetConfiguration") + }) + + /* * + * @tc.number : control_transfer_test_04 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 GetInterface: cmd 10 reqType 129 value 0 index 1 + */ + it('control_transfer_test_04', 0, function () { + console.info('usb control_transfer_test_04 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(10, 129, 0, 1) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_04 GetInterface") + }) + + /* * + * @tc.number : control_transfer_test_05 + * @tc.name : controlTransfer + * @tc.desc : 控制传输 ClearFeature: cmd 1 reqType 0 value 0 index 0 + */ + it('control_transfer_test_05', 0, function () { + console.info('usb control_transfer_test_05 begin'); + var testParam = getTransferTestParam() + if (testParam.inEndpoint == null || testParam.interface == null || testParam.outEndpoint == null){ + expect(false).assertTrue(); + return + } + + var timeout = 5000; + var controlParam = getTransferParam(1, 0, 0, 0) + callControlTransfer(testParam.pip, controlParam, timeout, "control_transfer_test_05 ClearFeature") + }) + +}) diff --git a/interfaces/kits/js/test/UsbFunctionsJsunit.test.js b/interfaces/kits/js/test/UsbFunctionsJsunit.test.js new file mode 100644 index 00000000..933c3e71 --- /dev/null +++ b/interfaces/kits/js/test/UsbFunctionsJsunit.test.js @@ -0,0 +1,218 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + + +/* usb core functions test */ +describe('UsbFunctionsJsFunctionsTest', function () { + + beforeAll(function () { + console.log("*************Usb Unit UsbFunctionsJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("begin test getversion :" + Version) + // 切换到 device + var usbPortList = usb.getPorts() + if (usbPortList.length > 0){ + if (usbPortList[0].status.currentMode == 1){ + console.info("usb case set data role 1, data role 1"); + usb.setPortRoles(usbPortList[0].id, 1, 1).then(data => { + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + }); + console.log("*************Usb Unit switch to device Begin*************"); + } + } + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + console.log("*************Usb Unit UsbFunctionsJsFunctionsTest End*************"); + }) + + /* * + * @tc.number : get_current_functions_test_01 + * @tc.name : getCurrentFunctions + * @tc.desc : 获取当前设备模式 掩码与描述字符转换 + */ + it('get_current_functions_test_01', 0, function () { + console.info('usb get_current_functions_test_01 begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + + var strMaskCode = usb.usbFunctionsToString(maskCode) + console.info("usb case usbFunctionsToString return str: " + strMaskCode); + var nMaskCode = usb.usbFunctionsFromString(strMaskCode) + console.info("usb case strMaskCode usbFunctionsFromString return int: " + nMaskCode); + expect(nMaskCode).assertEqual(maskCode); + console.info('usb get_current_functions_test_01 : PASS'); + expect(true).assertTrue(); + }) + + + /* * + * @tc.number : get_current_functions_test_02 + * @tc.name : usbFunctionString + * @tc.desc : 反向测试 获取当前设备模式 掩码与描述字符转换 + */ + it('get_current_functions_test_02', 0, function () { + console.info('usb get_current_functions_test_02 begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + + var strMaskCode = usb.usbFunctionsToString(maskCode) + console.info("usb case usbFunctionsToString return str: " + strMaskCode); + var nMaskCode = usb.usbFunctionsFromString(strMaskCode) + console.info("usb case strMaskCode usbFunctionsFromString return int: " + nMaskCode); + + var errmaskCode = -1 + var strMaskCode = usb.usbFunctionsToString(errmaskCode) + expect(CheckEmptyUtils.isEmpty(strMaskCode)).assertFalse(); + console.info("usb case errMaskCode usbFunctionsToString return str: " + strMaskCode); + + var errnStrMaskCode = "HDC" + var nMaskCode = usb.usbFunctionsFromString(errnStrMaskCode) + expect(nMaskCode).assertEqual(-1); + console.info("usb case errnStrMaskCode usbFunctionsFromString return int: " + nMaskCode); + + console.info('usb get_current_functions_test_02 : PASS'); + }) + + function callSetCurFunction(caseName, iValue) { + CheckEmptyUtils.sleep(3000) + console.info("usb case param case name:" + caseName); + console.info("usb case param iValue:" + iValue); + usb.setCurrentFunctions(iValue).then(data => { + console.info("usb case return: " + data); + expect(data).assertTrue(); + console.info("usb " + caseName + ": PASS"); + }).catch(error => { + console.info("usb case " + caseName + " error : " + error); + expect(false).assertTrue(); + }); + } + +// /* * +// * @tc.number : set_current_functions_test_01 +// * @tc.name : setCurrentFunctions +// * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 0 取消所有function功能 +// */ +// it('set_current_functions_test_01', 0, function () { +// console.info('usb set_current_functions_test_01 begin'); +// var maskCode = usb.getCurrentFunctions(); +// console.info("usb case getCurrentFunctions return: " + maskCode); +// var funcString = usb.usbFunctionsToString(maskCode); +// console.info("usb case funcString:" + funcString); +// callSetCurFunction("set_current_functions_test_01 cancle all 0", 0) +// }) + + /* * + * @tc.number : set_current_functions_test_02 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 1 设置为ACM功能 + */ + it('set_current_functions_test_02', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_02 set ACM begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_02 ACM 1", 1) + }) + + /* * + * @tc.number : set_current_functions_test_03 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 2 设置为ECM功能 + */ + it('set_current_functions_test_03', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_03 set ECM begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_03 ECM 2", 2) + }) + + /* * + * @tc.number : set_current_functions_test_04 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 3 设置为ACM、ECM功能 + */ + it('set_current_functions_test_04', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_04 set ACM ECM begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_04 ACM ECM 3", 3) + }) + + /* * + * @tc.number : set_current_functions_test_05 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 4 设置为HDC功能 + */ + it('set_current_functions_test_05', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_05 set HDC begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_05 HDC 4", 4) + }) + + /* * + * @tc.number : set_current_functions_test_06 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 5 设置为ACM、HDC功能 + */ + it('set_current_functions_test_06', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_06 set ACM HDC begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_06 ACM HDC 5", 5) + }) + + /* * + * @tc.number : set_current_functions_test_07 + * @tc.name : functions_test + * @tc.desc : 在设备模式下设置当前的USB功能列表 Set 6 设置为ECM、HDC功能 + */ + it('set_current_functions_test_07', 0, function () { + CheckEmptyUtils.sleep(3000) + console.info('usb set_current_functions_test_07 set ECM HDC begin'); + var maskCode = usb.getCurrentFunctions(); + console.info("usb case getCurrentFunctions return: " + maskCode); + var funcString = usb.usbFunctionsToString(maskCode); + console.info("usb case funcString:" + funcString); + callSetCurFunction("set_current_functions_test_07 ECM HDC 6", 6) + }) + +}) diff --git a/interfaces/kits/js/test/UsbPortJsunit.test.js b/interfaces/kits/js/test/UsbPortJsunit.test.js new file mode 100644 index 00000000..3845ee4f --- /dev/null +++ b/interfaces/kits/js/test/UsbPortJsunit.test.js @@ -0,0 +1,141 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 usb from '@ohos.usb'; +import CheckEmptyUtils from './CheckEmptyUtils.js'; +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +/* usb core functions test */ +describe('UsbPortJsFunctionsTest', function () { + + beforeAll(function () { + console.log("*************Usb Unit UsbPortJsFunctionsTest Begin*************"); + var Version = usb.getVersion() + console.info("begin test getversion :" + Version) + }) + beforeEach(function () { + console.info('beforeEach: *************Usb Unit Test Case*************'); + }) + afterEach(function () { + console.info('afterEach: *************Usb Unit Test Case*************'); + }) + afterAll(function () { + console.log("*************Usb Unit UsbPortJsFunctionsTest End*************"); + }) + + + /* * + * @tc.number : get_ports_test_01 + * @tc.name : getPorts + * @tc.desc : 获取USB端口描述信息列表 + */ + it('get_ports_test_01', 0, function () { + console.info('usb get_ports_test_01 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb get_ports_test_01 usbPortList is null'); + expect(false).assertTrue(); + return + } + expect(usbPortList.length > 0).assertTrue(); + console.info('usb get_ports_test_01 : PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : get_supported_modes_test_01 + * @tc.name : getSupportedModes + * @tc.desc : 获取指定的端口支持的模式列表的组合掩码 + */ + it('get_supported_modes_test_01', 0, function () { + console.info('usb get_supported_modes_test_01 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb get_supported_modes_test_01 usbPortList is null'); + expect(false).assertTrue(); + return + } + + expect(usbPortList.length > 0).assertTrue(); + for (var i = 0; i < usbPortList.length; i++){ + var maskCode = usb.getSupportedModes(usbPortList[i].id) + expect(maskCode).assertEqual(usbPortList[i].supportedModes); + } + + console.info('usb get_supported_modes_test_01 : PASS'); + expect(true).assertTrue(); + }) + + + /* * + * @tc.number : set_port_roles_test_01 + * @tc.name : setPortRoles + * @tc.desc : 切换为Device set powerRole 2 DataRole 2 + */ + it('set_port_roles_test_01', 0, function () { + console.info('usb set_port_roles_test_01 device 2 2 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb set_port_roles_test_01 device 2 2 usbPortList is null'); + expect(false).assertTrue(); + return + } + + for (var i = 0; i < usbPortList.length; i++){ + console.info("usb case set data role 2, data role 2"); + usb.setPortRoles(usbPortList[i].id, 2, 2).then(data => { + console.info("usb case setPortRoles return: " + data); + expect(data).assertTrue(); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + expect(false).assertTrue(); + }); + } + + console.info('usb set_port_roles_test_01 device 2 2: PASS'); + expect(true).assertTrue(); + }) + + /* * + * @tc.number : set_port_roles_test_02 + * @tc.name : setPortRoles + * @tc.desc : 切换为host set powerRole 1 DataRole 1 + */ + it('set_port_roles_test_02', 0, function () { + console.info('usb set_port_roles_test_02 host 1 1 begin'); + var usbPortList = usb.getPorts() + if(usbPortList.length == 0){ + console.info('usb set_port_roles_test_02 host 1 1 usbPortList is null'); + expect(false).assertTrue(); + return + } + + for (var i = 0; i < usbPortList.length; i++){ + console.info("usb case set data role 1, data role 1"); + CheckEmptyUtils.sleep(5000) + usb.setPortRoles(usbPortList[i].id, 1, 1).then(data => { + expect(data).assertTrue(); + console.info("usb case setPortRoles return: " + data); + }).catch(error => { + console.info("usb case setPortRoles error : " + error); + expect(false).assertTrue(); + }); + } + + console.info('usb set_port_roles_test_02 host 1 1: PASS'); + expect(true).assertTrue(); + }) + +}) diff --git a/interfaces/kits/js/test/usb_unit.test.js b/interfaces/kits/js/test/usb_unit.test.js new file mode 100644 index 00000000..c179a733 --- /dev/null +++ b/interfaces/kits/js/test/usb_unit.test.js @@ -0,0 +1,495 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import app from '@system.app' +import Context from '@ohos.napi_context' +import usb from '@ohos.usb'; + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe('appInfoTest', function () { + console.log("*************Usb Unit Test Begin*************"); + /* usb core functions test */ + it('get_devices_test', 0, function () { + var result = usb.getDevices(); + console.info('getDevices = ' + result); + expect(result.size() > 0).assertEqual('1'); + }) + it('connect_devices_test', 0, function () { + var device = { + busNum = 1, + devAddr = 1, + name = "", + manufacturerName = "", + productName = "", + version = "", + vendorId = 1, + productId = 1, + clazz = 1, + subclass = 1, + protocol = 1, + hasAudioPlayback = false, + hasAudioCapture = false, + hasMidi = false, + hasVideoPlayback = false, + hasVideoCapture = false, + configs: [{ + id = 1, + attributes = 1, + maxPower = 1, + name = "", + isRemoteWakeup = false, + isSelfPowered = false, + interfaces = [{ + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }] + }] + }; + var result = usb.connectDevice(device); + console.info('connectDevice = ' + result); + expect(Object.keys(result).length >0).assertEqual('1'); + }) + + it('has_right_test', 0, function () { + var deviceName = ""; + var result = usb.hasRight(deviceName); + console.info('hasRight = ' + result); + expect(result === true).assertEqual('1'); + }) + it('request_right_test', 0, function () { + var deviceName = ""; + var result = usb.requestRight(deviceName); + console.info('requestRight = ' + result); + expect(result === true).assertEqual('1'); + }) + + it('usb_functions_from_string_test', 0, function () { + var funcs = ""; + var result = usb.usbFunctionsFromString(funcs); + console.info('usbFunctionsFromString = ' + result); + expect(result > 0).assertEqual('1'); + }) + it('usb_functions_to_string_test', 0, function () { + var funcs = 1; + var result = usb.usbFunctionsToString(funcs); + console.info('usbFunctionsToString = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('set_current_functions_test', 0, function () { + var funcs = 1; + var result = usb.setCurrentFunctions(funcs); + console.info('setCurrentFunctions = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_current_functions_test', 0, function () { + var result = usb.getCurrentFunctions(); + console.info('getCurrentFunctions = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('set_hdc_enabled_test', 0, function () { + var enable = false; + var result = usb.setHdcEnabled(enable); + console.info('setHdcEnabled = ' + result); + expect(result === true).assertEqual('1'); + }) + + it('get_ports_test', 0, function () { + var result = usb.getPorts(); + console.info('getPorts = ' + result); + expect(result.size() > 0).assertEqual('1'); + }) + + /* usb port functions test */ + it('get_supported_modes_test', 0, function () { + var portId = 1; + var result = usb.getSupportedModes(portId); + console.info('getSupportedModes = ' + result); + expect(result > 0).assertEqual('1'); + }) + it('set_port_roles_test', 0, function () { + var portId = 1; + var powerRole = 1; + var dataRole = 1; + var result = usb.setPortRoles(portId, powerRole, dataRole); + console.info('setPortRoles = ' + result); + expect(result === true).assertEqual('1'); + }) + + /* usb pipe functions test */ + it('claim_interface_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var iface = { + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }; + var force = true; + var result = usb.claimInterface(pipe, iface, force); + console.info('claimInterface = ' + result); + expect(result === true).assertEqual('1'); + }) + it('release_interface_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var iface = { + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }; + var result = usb.releaseInterface(pipe, iface); + console.info('releaseInterface = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_serial_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.getSerial(pipe); + console.info('getSerial = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('set_configuration_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var config = { + id = 1, + attributes = 1, + maxPower = 1, + name = "", + isRemoteWakeup = false, + isSelfPowered = false, + interfaces = [{ + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }] + }; + var result = usb.setConfiguration(pipe, config); + console.info('setConfiguration = ' + result); + expect(result === true).assertEqual('1'); + }) + it('set_interface_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var iface = { + id = 1, + protocol = 1, + clazz = 1, + subclass = 1, + alternateSetting = 1, + name = "", + endpoints = [{ + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }] + }; + var result = usb.setInterface(pipe, iface); + console.info('setInterface = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_raw_descriptors_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.getRawDescriptors(pipe); + console.info('getRawDescriptors = ' + result); + expect(result.length > 0).assertEqual('1'); + }) + it('get_file_descriptors_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.getFileDescriptors(pipe); + console.info('getFileDescriptors = ' + result); + expect(result > 0).assertEqual('1'); + }) + + it('control_transfer_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var requestType = 1; + var request = 1; + var value = 1; + var index = 1; + var buffer = [1,2,3]; + var length = 1; + var timeout = 1; + var result = usb.controlTransfer(pipe, requestType, request, value, index, buffer, length,timeout); + console.info('controlTransfer = ' + result); + expect(result > 0).assertEqual('1'); + }) + it('bulk_transfer_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }; + var buffer = [1,2,3]; + var length = 1; + var timeout = 1; + var result = usb.bulkTransfer(pipe, endpoint, buffer, length, timeout); + console.info('bulkTransfer = ' + result); + expect(result > 0).assertEqual('1'); + }) + + it('request_wait_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.requestWait(pipe); + console.info('requestWait = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('request_wait_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var timeout = 1; + var result = usb.requestWait(pipe, timeout); + console.info('requestWait = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('close_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var result = usb.close(pipe, timeout); + console.info('close = ' + result); + expect(result === true).assertEqual('1'); + }) + + /* usb request functions test */ + it('initialize_test', 0, function () { + var pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }; + var endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }; + var result = usb.initialize(pipe, endpoint); + console.info('initialize = ' + result); + expect(typeof result == "undefined" || result == null || result == "").assertEqual('1'); + }) + it('free_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var result = usb.free(request); + console.info('free = ' + result); + expect(result === true).assertEqual('1'); + }) + it('abort_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var result = usb.abort(request); + console.info('abort = ' + result); + expect(result === true).assertEqual('1'); + }) + it('get_client_data_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var result = usb.getClientData(request); + console.info('getClientData = ' + result); + expect(result.length() > 0).assertEqual('1'); + }) + it('queue_test', 0, function () { + var request = { + pipe = { + fd = 1, + serial = "", + busNum = 1, + devAddr = 1 + }, + endpoint = { + address = 1, + attributes = 1, + interval = 1, + maxPacketSize = 1, + direction = 1, + number = 1, + type = 1 + }, + buffer = [1,2,3], + clientData = [1,2,3] + }; + var buffer = [1,2,3]; + var result = usb.queue(request, buffer); + console.info('queue = ' + result); + expect(result === true).assertEqual('1'); + }) +}) \ No newline at end of file diff --git a/ohos.build b/ohos.build new file mode 100644 index 00000000..fbdfa63f --- /dev/null +++ b/ohos.build @@ -0,0 +1,32 @@ +{ + "subsystem": "usbmgr", + "parts": { + "usb_manager_native": { + "module_list": [ + "//base/usb/usb_manager/hdi:hdi_group", + "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "//base/usb/usb_manager/sa_profile:usbmgr_sa_profile", + "//base/usb/usb_manager/services:usbservice", + "//base/usb/usb_manager/interfaces/kits/js/napi:usb" + ], + "inner_kits": [ + { + "name": "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "header": { + "header_files": [ + "usb_srv_client.h", + "iusb_srv.h", + "usb_info.h" + ], + "header_base": "//base/usb/usb_manager/interfaces/innerkits/native/include" + } + } + ], + "test_list": [ + "//base/usb/usb_manager/services/native/test:usb_service_unittest", + "//base/usb/usb_manager/hdi/test:usbd_client_unittest", + "//base/usb/usb_manager/test/native:usbmgr_native_test" + ] + } + } +} diff --git a/sa_profile/4201.xml b/sa_profile/4201.xml new file mode 100644 index 00000000..cbee7ccb --- /dev/null +++ b/sa_profile/4201.xml @@ -0,0 +1,24 @@ + + + + foundation + + 4201 + libusbservice.z.so + true + false + 1 + + diff --git a/sa_profile/BUILD.gn b/sa_profile/BUILD.gn new file mode 100644 index 00000000..67e668fa --- /dev/null +++ b/sa_profile/BUILD.gn @@ -0,0 +1,19 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("usbmgr_sa_profile") { + sources = [ "4201.xml" ] + part_name = "usb_manager_native" +} diff --git a/services/BUILD.gn b/services/BUILD.gn new file mode 100644 index 00000000..935c4a99 --- /dev/null +++ b/services/BUILD.gn @@ -0,0 +1,69 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("usbsrv_private_config") { + include_dirs = [ "//utils/system/safwk/native/include" ] +} + +config("usbsrv_public_config") { + include_dirs = [ + "native/include", + "${usb_manager_path}/services/zidl/include", + ] +} + +ohos_shared_library("usbservice") { + sources = [ + "${usb_manager_path}/services/zidl/src/usb_srv_stub.cpp", + "native/src/usb_descriptor_parser.cpp", + "native/src/usb_host_manager.cpp", + "native/src/usb_right_manager.cpp", + "native/src/usb_port_manager.cpp", + "native/src/usb_serial_reader.cpp", + "native/src/usb_server_event_handler.cpp", + "native/src/usb_service_subscriber.cpp", + "native/src/usb_service.cpp", + "native/src/usb_function_manager.cpp", + ] + + configs = [ + "${utils_path}:utils_config", + ":usbsrv_private_config", + ] + + public_configs = [ ":usbsrv_public_config" ] + + deps = [ + "${usb_manager_path}/hdi/client:usbd_client", + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] + + part_name = "usb_manager_native" +} + + diff --git a/services/native/include/usb_descriptor_parser.h b/services/native/include/usb_descriptor_parser.h new file mode 100644 index 00000000..f4d4ed26 --- /dev/null +++ b/services/native/include/usb_descriptor_parser.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 USB_DESCRIPTOR_PARSER_H +#define USB_DESCRIPTOR_PARSER_H +#include "usb_device.h" +#include "usb_interface.h" + +namespace OHOS { +namespace USB { + +class UsbDescriptorParser { +public: + UsbDescriptorParser(); + ~UsbDescriptorParser(); + + static int32_t ParseDeviceDescriptor(const uint8_t *buffer, uint32_t length, UsbDevice &dev); + static int32_t ParseConfigDescriptor(const uint8_t *buffer, uint32_t length, uint32_t &cursor, USBConfig &config); + static int32_t + ParseInterfaceDescriptor(const uint8_t *buffer, uint32_t length, uint32_t &cursor, UsbInterface &interface); + static int32_t ParseEndpointDescriptor(const uint8_t *buffer, uint32_t length, uint32_t &cursor, USBEndpoint &ep); +}; +} // namespace USB +} // namespace OHOS +#endif diff --git a/services/native/include/usb_function_manager.h b/services/native/include/usb_function_manager.h new file mode 100644 index 00000000..c532b7a5 --- /dev/null +++ b/services/native/include/usb_function_manager.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 USB_FUNCTION_MANAGER_H +#define USB_FUNCTION_MANAGER_H + +#include +#include +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { + +class UsbFunctionManager { +public: + static bool AreSettableFunctions(int32_t funcs); + + static int32_t FromStringFunctions(std::string funcs); + static std::string ToStringFunctions(int32_t func); + static void updateFunctions(int32_t func); + static int32_t getCurrentFunctions(); + + static const std::string FUNCTION_NAME_NONE; + static const std::string FUNCTION_NAME_HDC; + static const std::string FUNCTION_NAME_ACM; + static const std::string FUNCTION_NAME_ECM; + + static const int32_t FUNCTION_NONE; + static const int32_t FUNCTION_ACM; + static const int32_t FUNCTION_ECM; + static const int32_t FUNCTION_HDC; + +private: + static const int32_t FUNCTION_SETTABLE; + static const std::map FUNCTION_MAPPING_N2C; + static int currentFunctions; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USB_FUNCTION_MANAGER_H diff --git a/services/native/include/usb_host_manager.h b/services/native/include/usb_host_manager.h new file mode 100644 index 00000000..42d82aae --- /dev/null +++ b/services/native/include/usb_host_manager.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_HOST_MANAGER_H +#define USB_HOST_MANAGER_H + +#include +#include +#include +#include "system_ability.h" +#include "usb_device.h" +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { +typedef std::map MAP_STR_DEVICE; + +class UsbHostManager { +public: + UsbHostManager(SystemAbility *systemAbility); + ~UsbHostManager(); + void getDevices(MAP_STR_DEVICE &devices); + bool DelDevice(uint8_t busNum, uint8_t devNum); + bool AddDevice(UsbDevice *dev); + +private: + MAP_STR_DEVICE devices_; + SystemAbility *systemAbility_; +}; +} // namespace USB +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_port_manager.h b/services/native/include/usb_port_manager.h new file mode 100644 index 00000000..853de2e7 --- /dev/null +++ b/services/native/include/usb_port_manager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_PORT_MANAGER_H +#define USB_PORT_MANAGER_H + +#include +#include +#include +#include +#include "usb_common.h" +#include "usb_port.h" + +namespace OHOS { +namespace USB { +class UsbPortManager { +public: + UsbPortManager(); + typedef std::map PortMap; + PortMap portMap; + + void Init(); + void Init(int32_t test); + int32_t GetPorts(std::vector &ports); + int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); + void SetPortRoles(int32_t portId, int32_t powerRole, int32_t dataRole); + int32_t QueryPort(); + void UpdatePort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode); + void AddPort(UsbPort *port); + void RemovePort(int32_t portId); + +private: +}; + +} // namespace USB + +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_right_manager.h b/services/native/include/usb_right_manager.h new file mode 100644 index 00000000..e6c6a2d2 --- /dev/null +++ b/services/native/include/usb_right_manager.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 USB_RIGHT_MANAGER_H +#define USB_RIGHT_MANAGER_H + +#include +#include +#include +#include +#include +#include "usb_common.h" + +namespace OHOS { +namespace USB { +class UsbRightManager { +public: + typedef std::vector PidList; + typedef std::map RightMap; + RightMap rightMap; + + void Init(); + int32_t HasRight(std::string deviceName, int pid); + int32_t RequestRight(std::string deviceName, int pid); + void AddDeviceRight(std::string deviceName, int pid); + void RemoveDeviceRight(std::string deviceName); +}; +} // namespace USB +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_serial_reader.h b/services/native/include/usb_serial_reader.h new file mode 100644 index 00000000..32199739 --- /dev/null +++ b/services/native/include/usb_serial_reader.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 USB_SERIAL_READER_H +#define USB_SERIAL_READER_H + +#include +#include "system_ability.h" +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { + +class UsbSerialReader { +public: + UsbSerialReader(SystemAbility *systemAbility, UsbRightManager *rightManager, std::string serialNumber); + ~UsbSerialReader(); + +private: + SystemAbility *systemAbility_; + UsbRightManager *rightManager_; + std::string serialNumber_; +}; + +} // namespace USB + +} // namespace OHOS + +#endif diff --git a/services/native/include/usb_server_event_handler.h b/services/native/include/usb_server_event_handler.h new file mode 100644 index 00000000..0db4ddc1 --- /dev/null +++ b/services/native/include/usb_server_event_handler.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 USBMGR_USB_SERVER_EVENT_HANDLER_H +#define USBMGR_USB_SERVER_EVENT_HANDLER_H + +#include "event_handler.h" +#include "refbase.h" + +namespace OHOS { +namespace USB { + +class UsbService; + +class UsbServerEventHandler : public AppExecFwk::EventHandler { +public: + UsbServerEventHandler(const std::shared_ptr &runner, const wptr &service); + ~UsbServerEventHandler() = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + +private: + wptr service_; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVER_EVENT_HANDLER_H diff --git a/services/native/include/usb_service.h b/services/native/include/usb_service.h new file mode 100644 index 00000000..197011ad --- /dev/null +++ b/services/native/include/usb_service.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_USB_SERVICE_H +#define USBMGR_USB_SERVICE_H + +#include +#include +#include "delayed_sp_singleton.h" +#include "iremote_object.h" +#include "iusb_srv.h" +#include "system_ability.h" +#include "usb_function_manager.h" +#include "usb_host_manager.h" +#include "usb_port_manager.h" +#include "usb_right_manager.h" +#include "usb_server_event_handler.h" +#include "usb_server_stub.h" +#include "usb_service_subscriber.h" +#include "usbd_api.h" +#include "usbd_client.h" +#include "usbd_subscriber.h" + +namespace OHOS { +namespace USB { + +class UsbService : public SystemAbility, public UsbServerStub { + + DECLARE_SYSTEM_ABILITY(UsbService) + +public: + ~UsbService(); + +private: + friend DelayedSpSingleton; + UsbService(); + +public: + virtual void OnStart() override; + virtual void OnStop() override; + virtual int32_t OnFoundDevice(FoundDevice &info) override; + + bool IsServiceReady() const + { + return ready_; + } + std::shared_ptr GetHandler() const + { + return handler_; + } + + int32_t OpenDevice(uint8_t busNum, uint8_t devAddr) override; + int32_t HasRight(std::string deviceName) override; + int32_t RequestRight(std::string deviceName) override; + int32_t GetDevices(std::vector &deviceList) override; + int32_t GetCurrentFunctions(int32_t &funcs) override; + int32_t SetCurrentFunctions(int32_t funcs) override; + int32_t UsbFunctionsFromString(std::string funcs) override; + std::string UsbFunctionsToString(int32_t funcs) override; + int32_t GetPorts(std::vector &result) override; + int32_t GetSupportedModes(int32_t portId, int32_t &result) override; + int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) override; + + int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + int32_t BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + int32_t BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) override; + int32_t ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) override; + int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) override; + int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) override; + int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) override; + int32_t RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientData, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) override; + int32_t RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) override; + int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) override; + int32_t Close(uint8_t busNum, uint8_t devAddr) override; + bool AddDevice(uint8_t busNum, uint8_t devAddr); + bool DelDevice(uint8_t busNum, uint8_t devAddr); + void UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode); + int32_t GetDeviceInfo(uint8_t busNum, uint8_t devAddr, UsbDevice *dev); + +private: + bool Init(); + bool InitUsbd(); + bool IsCommonEventServiceAbilityExist(); + + bool ready_{false}; + int32_t commEventRetryTimes_{0}; + std::mutex mutex_; + UsbHostManager *usbHostManger_ = nullptr; + UsbRightManager *usbRightManager = nullptr; + UsbPortManager *usbPortManager = nullptr; + UsbFunctionManager *usbFunctionManager = nullptr; + std::shared_ptr eventRunner_; + std::shared_ptr handler_; + sptr usbdSubscriber_; + std::map portMap; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVICE_H diff --git a/services/native/include/usb_service_subscriber.h b/services/native/include/usb_service_subscriber.h new file mode 100644 index 00000000..c1f278f6 --- /dev/null +++ b/services/native/include/usb_service_subscriber.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 USBMGR_USB_SERVICE_SUBSCRIBER_H +#define USBMGR_USB_SERVICE_SUBSCRIBER_H + +#include "usbd_subscriber.h" + +namespace OHOS { +namespace USB { + +class UsbServiceSubscriber : public UsbdSubscriber { +public: + UsbServiceSubscriber(); + ~UsbServiceSubscriber() = default; + int32_t Update(const UsbInfo &info) override; + int32_t DeviceEvent(const UsbInfo &info) override; + int32_t PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) override; +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVICE_SUBSCRIBER_H diff --git a/services/native/src/usb_descriptor_parser.cpp b/services/native/src/usb_descriptor_parser.cpp new file mode 100644 index 00000000..79fba57d --- /dev/null +++ b/services/native/src/usb_descriptor_parser.cpp @@ -0,0 +1,247 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_descriptor_parser.h" +#include +#include "hilog_wrapper.h" +#include "message_parcel.h" +#include "securec.h" +#include "usb_config.h" +#include "usb_endpoint.h" +#include "usb_interface.h" +#include "usbd_api.h" + +namespace OHOS { +namespace USB { +enum DescriptorType { + DESCRIPTOR_TYPE_DEVICE = 1, + DESCRIPTOR_TYPE_CONFIG = 2, + DESCRIPTOR_TYPE_INTERFACE = 4, + DESCRIPTOR_TYPE_ENDPOINT = 5 +}; + +UsbDescriptorParser::UsbDescriptorParser() {} + +UsbDescriptorParser::~UsbDescriptorParser() {} + +int32_t UsbDescriptorParser::ParseDeviceDescriptor(const uint8_t *buffer, uint32_t length, UsbDevice &dev) +{ + uint32_t cursor = 0; + if (buffer == nullptr || length == 0) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: buffer is null", __func__); + return ERR_NO_INIT; + } + + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang parse begin buffer=%{public}p, length=%{public}d, cursor=%{public}d", __func__, + buffer, length, cursor); + uint32_t deviceDescriptorSize = sizeof(UsbdDeviceDescriptor); + if (length < deviceDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: buffer size error", __func__); + return ERR_INVALID_VALUE; + } + + UsbdDeviceDescriptor deviceDescriptor = *(UsbdDeviceDescriptor *)buffer; + cursor += deviceDescriptorSize; + if (deviceDescriptor.bLength != deviceDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: UsbdDeviceDescriptor size error", __func__); + return ERR_INVALID_VALUE; + } + + dev.SetVendorId(deviceDescriptor.idVendor); + dev.SetProductId(deviceDescriptor.idProduct); + dev.SetClass(deviceDescriptor.bDeviceClass); + dev.SetSubclass(deviceDescriptor.bDeviceSubClass); + dev.SetDescConfigCount(deviceDescriptor.bNumConfigurations); + + dev.SetbMaxPacketSize0(deviceDescriptor.bMaxPacketSize0); + dev.SetbcdDevice(deviceDescriptor.bcdDevice); + dev.SetbcdUSB(deviceDescriptor.bcdUSB); + dev.SetiManufacturer(deviceDescriptor.iManufacturer); + dev.SetiProduct(deviceDescriptor.iProduct); + dev.SetiSerialNumber(deviceDescriptor.iSerialNumber); + return ERR_OK; +} + +int32_t UsbDescriptorParser::ParseConfigDescriptor(const uint8_t *buffer, + uint32_t length, + uint32_t &cursor, + USBConfig &config) +{ + if (buffer == nullptr || length == 0) { + return ERR_INVALID_VALUE; + } + + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang parse begin buffer=%{public}p, length=%{public}d, cursor=%{public}d", __func__, + buffer, length, cursor); + uint32_t configDescriptorSize = sizeof(UsbdConfigDescriptor); + if (length < configDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: fumang buffer size error", __func__); + return ERR_INVALID_VALUE; + } + + UsbdConfigDescriptor configDescriptor = *(UsbdConfigDescriptor *)buffer; + cursor += configDescriptorSize; + if (configDescriptor.bLength != configDescriptorSize) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: fumang UsbdDeviceDescriptor size error", __func__); + return ERR_INVALID_VALUE; + } + + config.SetId(configDescriptor.bConfigurationValue); + config.SetAttribute(configDescriptor.bmAttributes); + config.SetMaxPower(configDescriptor.bMaxPower); + config.SetiConfiguration(configDescriptor.iConfiguration); + + std::vector interfaces; + for(int i = 0; (i < configDescriptor.bNumInterfaces) && (cursor < length); ++i) { + uint32_t interfaceCursor = 0; + UsbInterface interface; + ParseInterfaceDescriptor(buffer + cursor + interfaceCursor, length - cursor - interfaceCursor, interfaceCursor, + interface); + if (interface.GetEndpointCount() > 0) { + interfaces.push_back(interface); + } else { + --i; + } + cursor += interfaceCursor; + } + config.SetInterfaces(interfaces); + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang bLength=%{public}d, \ + bDescriptorType=%{public}d, \ + wTotalLength=%{public}d, \ + bNumInterfaces=%{public}d, \ + bConfigurationValue=%{public}d, \ + iConfiguration=%{public}d, \ + bmAttributes=%{public}d, \ + bMaxPower=%{public}d", + __func__, configDescriptor.bLength, configDescriptor.bDescriptorType, configDescriptor.wTotalLength, + configDescriptor.bNumInterfaces, configDescriptor.bConfigurationValue, configDescriptor.iConfiguration, + configDescriptor.bmAttributes, configDescriptor.bMaxPower); + return ERR_OK; +} + +int32_t UsbDescriptorParser::ParseInterfaceDescriptor(const uint8_t *buffer, + uint32_t length, + uint32_t &cursor, + UsbInterface &interface) +{ + if (buffer == nullptr || length == 0) { + return ERR_INVALID_VALUE; + } + + uint32_t descriptorHeaderSize = sizeof(UsbdDescriptorHeader); + while ((uint32_t)cursor < length) { + if (descriptorHeaderSize >= length) { + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + UsbdDescriptorHeader descriptorHeader = *(UsbdDescriptorHeader *)(buffer + cursor); + if (descriptorHeader.bLength > length) { + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + if (descriptorHeader.bDescriptorType == DESCRIPTOR_TYPE_INTERFACE) { + break; + } + cursor += descriptorHeader.bLength; + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: type = %{public}d, length=%{public}d", __func__, + descriptorHeader.bDescriptorType, descriptorHeader.bLength); + } + + UsbdInterfaceDescriptor interfaceDescriptor = *(UsbdInterfaceDescriptor *)(buffer + cursor); + if (interfaceDescriptor.bLength != sizeof(UsbdInterfaceDescriptor)) { + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s: UsbdInterfaceDescriptor size error", __func__); + return ERR_INVALID_VALUE; + } + cursor += interfaceDescriptor.bLength; + + interface.SetId(interfaceDescriptor.bInterfaceNumber); + interface.SetProtocol(interfaceDescriptor.bInterfaceProtocol); + interface.SetAlternateSetting(interfaceDescriptor.bAlternateSetting); + interface.SetClass(interfaceDescriptor.bInterfaceClass); + interface.SetSubClass(interfaceDescriptor.bInterfaceSubClass); + interface.SetiInterface(interfaceDescriptor.iInterface); + + std::vector eps; + for (int j = 0; j < interfaceDescriptor.bNumEndpoints; ++j) { + uint32_t epCursor = 0; + USBEndpoint ep; + ParseEndpointDescriptor(buffer + cursor + epCursor, length - cursor - epCursor, epCursor, ep); + ep.SetInterfaceId(interfaceDescriptor.bInterfaceNumber); + eps.push_back(ep); + cursor += epCursor; + } + interface.SetEndpoints(eps); + return ERR_OK; +} +int32_t UsbDescriptorParser::ParseEndpointDescriptor(const uint8_t *buffer, + uint32_t length, + uint32_t &cursor, + USBEndpoint &ep) +{ + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang parse begin buffer=%{public}p, length=%{public}d, cursor=%{public}d", __func__, + buffer, length, cursor); + if (buffer == nullptr || length == 0) { + return ERR_INVALID_VALUE; + } + + uint32_t descriptorHeaderSize = sizeof(UsbdDescriptorHeader); + while ((uint32_t)cursor < length) { + if (descriptorHeaderSize >= length) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + UsbdDescriptorHeader descriptorHeader = *(UsbdDescriptorHeader *)(buffer + cursor); + if (descriptorHeader.bLength > length) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: descriptor size error", __func__); + return ERR_INVALID_VALUE; + } + if (descriptorHeader.bDescriptorType == DESCRIPTOR_TYPE_ENDPOINT) { + break; + } + cursor += descriptorHeader.bLength; + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: error type = %{public}d, length=%{public}d", __func__, + descriptorHeader.bDescriptorType, descriptorHeader.bLength); + } + + UsbdEndpointDescriptor endpointDescriptor = *(UsbdEndpointDescriptor *)(buffer + cursor); + if (endpointDescriptor.bLength != sizeof(UsbdEndpointDescriptor)) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s: fumang Endpoint descriptor size error, length=%{public}d", __func__, + endpointDescriptor.bLength); + return ERR_INVALID_VALUE; + } + cursor += endpointDescriptor.bLength; + + ep.SetAddr(endpointDescriptor.bEndpointAddress); + ep.SetAttr(endpointDescriptor.bmAttributes); + ep.SetInterval(endpointDescriptor.bInterval); + ep.SetMaxPacketSize(endpointDescriptor.wMaxPacketSize); + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s: fumang bLength=%{public}d, \ + bDescriptorType=%{public}d, \ + bEndpointAddress=%{public}d, \ + bmAttributes=%{public}d, \ + wMaxPacketSize=%{public}d, \ + bInterval=%{public}d", + __func__, endpointDescriptor.bLength, endpointDescriptor.bDescriptorType, + endpointDescriptor.bEndpointAddress, endpointDescriptor.bmAttributes, endpointDescriptor.wMaxPacketSize, + endpointDescriptor.bInterval); + return ERR_OK; +} +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_function_manager.cpp b/services/native/src/usb_function_manager.cpp new file mode 100644 index 00000000..4cf5a653 --- /dev/null +++ b/services/native/src/usb_function_manager.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_function_manager.h" +#include +#include + +namespace OHOS { +namespace USB { + +const std::string UsbFunctionManager::FUNCTION_NAME_NONE = "none"; +const std::string UsbFunctionManager::FUNCTION_NAME_HDC = "hdc"; +const std::string UsbFunctionManager::FUNCTION_NAME_ACM = "acm"; +const std::string UsbFunctionManager::FUNCTION_NAME_ECM = "ecm"; + +const int32_t UsbFunctionManager::FUNCTION_NONE = 0; +const int32_t UsbFunctionManager::FUNCTION_ACM = 1; +const int32_t UsbFunctionManager::FUNCTION_ECM = 2; +const int32_t UsbFunctionManager::FUNCTION_HDC = 4; + +int32_t UsbFunctionManager::currentFunctions = 0; + +const int32_t UsbFunctionManager::FUNCTION_SETTABLE = FUNCTION_HDC | FUNCTION_ACM | FUNCTION_ECM; + +const std::map UsbFunctionManager::FUNCTION_MAPPING_N2C = { + {FUNCTION_NAME_NONE, FUNCTION_NONE}, + {FUNCTION_NAME_ACM, FUNCTION_ACM}, + {FUNCTION_NAME_ECM, FUNCTION_ECM}, + {FUNCTION_NAME_HDC, FUNCTION_HDC}, +}; + +bool UsbFunctionManager::AreSettableFunctions(int32_t funcs) +{ + return funcs == FUNCTION_NONE || ((~FUNCTION_SETTABLE & funcs) == 0); +} + +int32_t UsbFunctionManager::FromStringFunctions(std::string funcs) +{ + if (funcs.compare(FUNCTION_NAME_NONE) == 0) { + return FUNCTION_NONE; + } + + std::regex re(","); + std::vector vec(std::sregex_token_iterator(funcs.begin(), funcs.end(), re, -1), + std::sregex_token_iterator()); + int64_t ret = 0; + for (auto &&item : vec) { + auto it = FUNCTION_MAPPING_N2C.find(item); + if (it != FUNCTION_MAPPING_N2C.end()) { + ret |= it->second; + } else { + std::string msg = "Invalid argument of usb function" + funcs; + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionManager::FromStringFunctions Invalid argument of usb function"); + return ERR_INVALID_VALUE; + } + } + return ret; +} + +std::string UsbFunctionManager::ToStringFunctions(int32_t func) +{ + std::stringstream stream; + if (FUNCTION_NONE == func) { + stream << FUNCTION_NAME_NONE; + return stream.str(); + } + + bool flag = false; + if ((func & FUNCTION_HDC) != 0) { + stream << FUNCTION_NAME_HDC; + flag = true; + } + if ((func & FUNCTION_ACM) != 0) { + if (flag) { + stream << ","; + } + stream << FUNCTION_NAME_ACM; + flag = true; + } + if ((func & FUNCTION_ECM) != 0) { + if (flag) { + stream << ","; + } + stream << FUNCTION_NAME_ECM; + flag = true; + } + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionManager::ToStringFunctions success"); + return stream.str(); +} + +void UsbFunctionManager::updateFunctions(int32_t func) +{ + currentFunctions = func; +} + +int32_t UsbFunctionManager::getCurrentFunctions() +{ + return currentFunctions; +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_host_manager.cpp b/services/native/src/usb_host_manager.cpp new file mode 100644 index 00000000..999e8092 --- /dev/null +++ b/services/native/src/usb_host_manager.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_host_manager.h" +#include "hilog_wrapper.h" +#include "usb_serial_reader.h" + +namespace OHOS { +namespace USB { + +UsbHostManager::UsbHostManager(SystemAbility *systemAbility) +{ + systemAbility_ = systemAbility; +} + +UsbHostManager::~UsbHostManager() {} + +void UsbHostManager::getDevices(MAP_STR_DEVICE &Devices) +{ + Devices = devices_; +} + +bool UsbHostManager::DelDevice(uint8_t busNum, uint8_t devNum) +{ + std::string name = std::to_string(busNum) + "-" + std::to_string(devNum); + MAP_STR_DEVICE::iterator iter = devices_.find(name); + if (iter == devices_.end()) { + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d not exist", + __func__, __LINE__, name.c_str(), busNum, devNum); + return false; + } + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d erase ", __func__, + __LINE__, name.c_str(), busNum, devNum); + devices_.erase(iter); + return true; +} +bool UsbHostManager::AddDevice(UsbDevice *dev) +{ + if (dev == NULL) { + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device is NULL", __func__, __LINE__); + return false; + } + uint8_t busNum = dev->GetBusNum(); + uint8_t devNum = dev->GetDevAddr(); + std::string name = std::to_string(busNum) + "-" + std::to_string(devNum); + MAP_STR_DEVICE::iterator iter = devices_.find(name); + if (iter != devices_.end()) { + USB_HILOGF(MODULE_SERVICE, + "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d already exist", __func__, + __LINE__, name.c_str(), busNum, devNum); + UsbDevice *devOld = iter->second; + devices_.erase(iter); + delete (devOld); + } + USB_HILOGF(MODULE_SERVICE, "%{public}s:%{public}d device:%{public}s bus:%{public}d dev:%{public}d insert", + __func__, __LINE__, name.c_str(), busNum, devNum); + devices_.insert(std::pair(name, dev)); + return true; +} + +} // namespace USB + +} // namespace OHOS diff --git a/services/native/src/usb_port_manager.cpp b/services/native/src/usb_port_manager.cpp new file mode 100644 index 00000000..7a02efd1 --- /dev/null +++ b/services/native/src/usb_port_manager.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_port_manager.h" +#include "usbd_client.h" + +namespace OHOS { +namespace USB { + const int32_t SUPPORTED_MODES = 3; + +UsbPortManager::UsbPortManager() +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::Init start"); +} + +void UsbPortManager::Init() +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::QueryPort start"); + int ret = QueryPort(); + if (ret) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::QueryPort false"); + } +} + +int32_t UsbPortManager::GetPorts(std::vector &ports) +{ + + if (portMap.size() > 0) { + for (auto it = portMap.begin(); it != portMap.end(); ++it) { + ports.push_back(it->second); + } + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::GetPorts success"); + return ERR_OK; + } + USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::GetPorts false"); + return ERR_INVALID_VALUE; +} + +int32_t UsbPortManager::GetSupportedModes(int32_t portId, int32_t &supportedModes) +{ + auto it = portMap.find(portId); + if (it != portMap.end()) { + supportedModes = it->second->supportedModes; + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::GetSupportedModes success"); + return ERR_OK; + } + USB_HILOGE(MODULE_USB_SERVICE, "UsbPortManager::GetSupportedModes false"); + return ERR_INVALID_VALUE; +} + +int32_t UsbPortManager::QueryPort() +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::queryPorts run"); + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + int32_t mode = 0; + int ret = UsbdClient::QueryPort(portId, powerRole, dataRole, mode); + USB_HILOGE(MODULE_USB_SERVICE, "portId:%{public}d powerRole:%{public}d dataRole:%{public}d mode:%{public}d ", + portId, powerRole, dataRole, mode); + if (ret) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbdClient::queryPorts false"); + return ret; + } + UsbPortStatus *usbPortStatus = new UsbPortStatus; + UsbPort *usbPort = new UsbPort; + usbPortStatus->currentMode = mode; + usbPortStatus->currentDataRole = dataRole; + usbPortStatus->currentPowerRole = powerRole; + usbPort->id = portId; + usbPort->supportedModes = SUPPORTED_MODES; + usbPort->usbPortStatus = usbPortStatus; + AddPort(usbPort); + return ret; +} + +void UsbPortManager::UpdatePort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) +{ + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::updatePort run"); + auto it = portMap.find(portId); + if (it != portMap.end()) { + if (it->second->id == portId) { + it->second->usbPortStatus->currentPowerRole = powerRole; + it->second->usbPortStatus->currentDataRole = dataRole; + it->second->usbPortStatus->currentMode = mode; + USB_HILOGI(MODULE_USB_SERVICE, "UsbPortManager::updatePort seccess"); + return; + } + } + USB_HILOGE(MODULE_USB_SERVICE, "updatePort false"); +} + +void UsbPortManager::AddPort(UsbPort *port) +{ + USB_HILOGI(MODULE_USB_SERVICE, "addPort run"); + auto it = portMap.find(port->id); + if (it == portMap.end()) { + portMap.insert(PortMap::value_type(port->id, port)); + USB_HILOGI(MODULE_USB_SERVICE, "addPort seccess"); + return; + } else { + delete port; + port = nullptr; + } + USB_HILOGE(MODULE_USB_SERVICE, "addPort false"); +} + +void UsbPortManager::RemovePort(int32_t portId) +{ + USB_HILOGI(MODULE_USB_SERVICE, "removePort run"); + auto it = portMap.find(portId); + if (it != portMap.end()) { + portMap.erase(it); + delete it->second; + USB_HILOGI(MODULE_USB_SERVICE, "removePort seccess"); + return; + } + USB_HILOGE(MODULE_USB_SERVICE, "removePort false"); +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_right_manager.cpp b/services/native/src/usb_right_manager.cpp new file mode 100644 index 00000000..b474acd3 --- /dev/null +++ b/services/native/src/usb_right_manager.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { +void UsbRightManager::Init() {} + +int32_t UsbRightManager::HasRight(std::string deviceName, int pid) +{ + auto itMap = rightMap.find(deviceName); + if (itMap == rightMap.end()) { + USB_HILOGE(MODULE_USB_SERVICE, "hasRight empty false 1"); + return ERR_INVALID_VALUE; + } else { + PidList pidList = itMap->second; + auto itVevtor = std::find(pidList.begin(), pidList.end(), pid); + if (itVevtor == pidList.end()) { + USB_HILOGE(MODULE_USB_SERVICE, "hasRight pid false 2"); + return ERR_INVALID_VALUE; + } + } + USB_HILOGI(MODULE_USB_SERVICE, "Request Right Success 3"); + return ERR_OK; +} + +int32_t UsbRightManager::RequestRight(std::string deviceName, int pid) +{ + if (HasRight(deviceName, pid) == 0) { + USB_HILOGE(MODULE_USB_SERVICE, "device has Right "); + return ERR_OK; + } + AddDeviceRight(deviceName, pid); + if (HasRight(deviceName, pid) == 0) { + USB_HILOGI(MODULE_USB_SERVICE, "requestRight Success"); + return ERR_OK; + } + USB_HILOGE(MODULE_USB_SERVICE, "requestRight False "); + return ERR_INVALID_VALUE; +} + +void UsbRightManager::AddDeviceRight(std::string deviceName, int pid) +{ + auto itMap = rightMap.find(deviceName); + if (itMap != rightMap.end()) { + auto v = itMap->second; + auto itVevtor = std::find(v.begin(), v.end(), pid); + if (itVevtor != v.end()) { + USB_HILOGE(MODULE_USB_SERVICE, "addDeviceRight false 1"); + return; + } + itMap->second.push_back(pid); + USB_HILOGI(MODULE_USB_SERVICE, "addDeviceRight success 2"); + } + PidList pidList; + pidList.push_back(pid); + rightMap.insert(RightMap::value_type(deviceName, pidList)); + USB_HILOGI(MODULE_USB_SERVICE, "addDeviceRight success 3"); +} + +void UsbRightManager::RemoveDeviceRight(std::string deviceName) +{ + auto it = rightMap.find("deviceName"); + if (it != rightMap.end()) { + rightMap.erase(it); + USB_HILOGI(MODULE_USB_SERVICE, "removeDeviceRight success 1"); + } +} +} // namespace USB +} // namespace OHOS \ No newline at end of file diff --git a/services/native/src/usb_serial_reader.cpp b/services/native/src/usb_serial_reader.cpp new file mode 100644 index 00000000..28ae42ea --- /dev/null +++ b/services/native/src/usb_serial_reader.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "usb_serial_reader.h" + +namespace OHOS { +namespace USB { + +UsbSerialReader::UsbSerialReader(SystemAbility *systemAbility, UsbRightManager *rightManager, std::string serialNumber) +{ + systemAbility_ = systemAbility; + rightManager_ = rightManager; + serialNumber_ = serialNumber; +} + +UsbSerialReader::~UsbSerialReader() {} + +} // namespace USB + +} // namespace OHOS diff --git a/services/native/src/usb_server_event_handler.cpp b/services/native/src/usb_server_event_handler.cpp new file mode 100644 index 00000000..c8900cc0 --- /dev/null +++ b/services/native/src/usb_server_event_handler.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "usb_server_event_handler.h" +#include "usb_service.h" +//#include "usb_common.h" + +namespace OHOS { +namespace USB { +UsbServerEventHandler::UsbServerEventHandler(const std::shared_ptr &runner, + const wptr &service) + : AppExecFwk::EventHandler(runner), service_(service) +{ + // USB_HILOGE(MODULE_USB_SERVICE, "UsbServerEventHandler::UsbServerEventHandler instance created."); +} + +void UsbServerEventHandler::ProcessEvent([[maybe_unused]] const AppExecFwk::InnerEvent::Pointer &event) {} +std::string deviceAddress; +int deviceClass = 0; +int deviceSubclass = 0; +unsigned char *descriptors = (unsigned char *)"000"; +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_service.cpp b/services/native/src/usb_service.cpp new file mode 100644 index 00000000..8862b69a --- /dev/null +++ b/services/native/src/usb_service.cpp @@ -0,0 +1,556 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_service.h" +#include +#include +#include +#include +#include +#include +#include "file_ex.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_descriptor_parser.h" +#include "usb_port_manager.h" +#include "usb_right_manager.h" + +namespace OHOS { +namespace USB { + +namespace { +const std::string USB_SERVICE_NAME = "UsbService"; +constexpr int32_t COMMEVENT_REGISTER_RETRY_TIMES = 10; +constexpr int32_t COMMEVENT_REGISTER_WAIT_DELAY_US = 20000; +const int32_t USB_MAX_DESCRIPTOR_SIZE = 256; +} // namespace + +auto pms = DelayedSpSingleton::GetInstance(); +const bool G_REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSpSingleton::GetInstance().GetRefPtr()); + +UsbService::UsbService() : SystemAbility(USB_MANAGER_USB_SERVICE_ID, true) +{ + usbHostManger_ = new UsbHostManager(nullptr); + usbRightManager = new UsbRightManager(); + usbPortManager = new UsbPortManager(); + usbFunctionManager = new UsbFunctionManager(); +} +UsbService::~UsbService() +{ + delete usbHostManger_; + delete usbRightManager; + delete usbPortManager; +} + +int32_t UsbService::OnFoundDevice(FoundDevice &info) +{ + return 0; +} + +void UsbService::OnStart() +{ + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s:%{public}d usb_service OnStart enter", __func__, __LINE__); + if (ready_) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart is ready, nothing to do"); + return; + } + if (!(Init())) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart call init fail"); + return; + } + if (!(InitUsbd())) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart call initUsbd fail"); + return; + } + usbPortManager->Init(); + ready_ = true; + USB_HILOGE(MODULE_USB_SERVICE, "OnStart and add system ability success"); +} + +bool UsbService::Init() +{ + USB_HILOGE(MODULE_USB_SERVICE, "%{public}s:%{public}d usb_service Init enter", __func__, __LINE__); + if (!eventRunner_) { + eventRunner_ = AppExecFwk::EventRunner::Create(USB_SERVICE_NAME); + if (eventRunner_ == nullptr) { + USB_HILOGE(MODULE_USB_SERVICE, "Init failed due to create EventRunner"); + return false; + } + } + if (!handler_) { + handler_ = std::make_shared(eventRunner_, pms); + if (handler_ == nullptr) { + USB_HILOGE(MODULE_USB_SERVICE, "Init failed due to create handler error"); + return false; + } + if (!Publish(pms)) { + USB_HILOGE(MODULE_USB_SERVICE, "OnStart register to system ability manager failed."); + return false; + } + } + while (commEventRetryTimes_ <= COMMEVENT_REGISTER_RETRY_TIMES) { + if (!IsCommonEventServiceAbilityExist()) { + ++commEventRetryTimes_; + usleep(COMMEVENT_REGISTER_WAIT_DELAY_US); + } else { + commEventRetryTimes_ = 0; + break; + } + } + USB_HILOGE(MODULE_USB_SERVICE, "Init success"); + return true; +} + +bool UsbService::InitUsbd() +{ + usbdSubscriber_ = new UsbServiceSubscriber(); + ErrCode ret = UsbdClient::BindUsbdSubscriber(usbdSubscriber_); + USB_HILOGE(MODULE_USB_SERVICE, "fumang entry InitUsbd ret: %{public}d", ret); + return SUCCEEDED(ret); +} + +void UsbService::OnStop() +{ + USB_HILOGE(MODULE_USB_SERVICE, "fumang entry stop service %{public}d", ready_); + if (!ready_) { + return; + } + eventRunner_.reset(); + handler_.reset(); + ready_ = false; + UsbdClient::UnbindUsbdSubscriber(); +} + +bool UsbService::IsCommonEventServiceAbilityExist() +{ + sptr sm = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!sm) { + USB_HILOGE(MODULE_USB_SERVICE, + "IsCommonEventServiceAbilityExist Get ISystemAbilityManager " + "failed, no SystemAbilityManager"); + return false; + } + sptr remote = sm->CheckSystemAbility(COMMON_EVENT_SERVICE_ABILITY_ID); + if (!remote) { + USB_HILOGE(MODULE_USB_SERVICE, "No CesServiceAbility"); + return false; + } + return true; +} +int32_t UsbService::OpenDevice(uint8_t busNum, uint8_t devAddr) +{ + return UsbdClient::OpenDevice(busNum, devAddr); +} +int32_t UsbService::HasRight(std::string deviceName) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager HasRight"); + pid_t pid = GetCallingPid(); + USB_HILOGI(MODULE_USB_SERVICE, "RequestRight pid = %{public}d", pid); + return usbRightManager->HasRight(deviceName, pid); +} + +int32_t UsbService::RequestRight(std::string deviceName) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbRightManager RequestRight"); + pid_t pid = GetCallingPid(); + USB_HILOGI(MODULE_USB_SERVICE, "RequestRight pid = %{public}d", pid); + return usbRightManager->RequestRight(deviceName, pid); +} + +int32_t UsbService::GetDevices(std::vector &deviceList) +{ + std::map devices; + usbHostManger_->getDevices(devices); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s list size %{public}d", __func__, devices.size()); + for (auto it = devices.begin(); it != devices.end(); ++it) { + deviceList.push_back(*it->second); + } + return ERR_OK; +} + +int32_t UsbService::GetCurrentFunctions(int32_t &funcs) +{ + return UsbdClient::GetCurrentFunctions(funcs); +} + +int32_t UsbService::SetCurrentFunctions(int32_t funcs) +{ + USB_HILOGI(MODULE_USB_SERVICE, "func = %{public}d", funcs); + return UsbdClient::SetCurrentFunctions(funcs); +} + +int32_t UsbService::UsbFunctionsFromString(std::string funcs) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsFromString"); + return UsbFunctionManager::FromStringFunctions(funcs); +} + +std::string UsbService::UsbFunctionsToString(int32_t funcs) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling UsbFunctionsToString"); + return UsbFunctionManager::ToStringFunctions(funcs); +} + +int32_t UsbService::GetPorts(std::vector &ports) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getPorts"); + return usbPortManager->GetPorts(ports); +} + +int32_t UsbService::GetSupportedModes(int32_t portId, int32_t &supportedModes) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbPortManager getSupportedModes"); + return usbPortManager->GetSupportedModes(portId, supportedModes); +} + +int32_t UsbService::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + USB_HILOGI(MODULE_USB_SERVICE, "calling usbd getPorts"); + return UsbdClient::SetPortRole(portId, powerRole, dataRole); +} + +int32_t UsbService::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + return UsbdClient::ClaimInterface(busNum, devAddr, interface); +} +int32_t UsbService::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + return UsbdClient::ReleaseInterface(busNum, devAddr, interface); +} +int32_t UsbService::BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((length > 0) && (!buffer)) { + return ret; + } + struct TransferParams params = {interface, endpoint, buffer, length, timeout}; + ret = UsbdClient::BulkTransferRead(busNum, devAddr, params); + return ret; +} +int32_t UsbService::BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((length > 0) && (!buffer)) { + return ret; + } + struct TransferParams params = {interface, endpoint, (uint8_t *)buffer, length, timeout}; + ret = UsbdClient::BulkTransferWrite(busNum, devAddr, params); + return ret; +} +int32_t UsbService::ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((length > 0) && (!buffer)) { + return ret; + } + struct CtrlTransferParamsParams params = {requestType, request, value, index, buffer, length, timeout}; + ret = UsbdClient::ControlTransfer(busNum, devAddr, params); + return ret; +} +int32_t UsbService::SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) +{ + return UsbdClient::SetConfig(busNum, devAddr, configIndex); +} +int32_t UsbService::GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) +{ + return UsbdClient::GetConfig(busNum, devAddr, configIndex); +} +int32_t UsbService::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) +{ + return UsbdClient::SetInterface(busNum, devAddr, interfaceid, altIndex); +} +int32_t UsbService::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *desc, uint32_t &length) +{ + if ((length > 0) && (!desc)) { + return ERR_INVALID_VALUE; + } + return UsbdClient::GetRawDescriptor(busNum, devAddr, desc, length); +} +int32_t UsbService::RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientData, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((clientLength > 0) && (!clientData)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + struct RequestParams params = {(void *)clientData, clientLength, (uint8_t *)buffer, length}; + ret = UsbdClient::RequestQueue(busNum, devAddr, ifId, endpointId, params); + return ret; +} +int32_t UsbService::RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) +{ + int32_t ret = ERR_INVALID_VALUE; + if ((clientLength > 0) && (!clientData)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + struct RequestParams params = {clientData, clientLength, buffer, length}; + ret = UsbdClient::RequestWait(busNum, devAddr, timeout, params); + return ret; +} + +int32_t UsbService::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) +{ + return UsbdClient::RequestCancel(busNum, devAddr, interfaceid, endpointId); +} + +int32_t UsbService::Close(uint8_t busNum, uint8_t devAddr) +{ + return UsbdClient::CloseDevice(busNum, devAddr); +} + +static std::string GetDevStringValFromIdx(uint8_t busNum, uint8_t devAddr, uint8_t idx) +{ + int ret = ERR_OK; + uint32_t length = USB_MAX_DESCRIPTOR_SIZE; + uint8_t *buffer = new uint8_t[length]; + std::string string = " "; + struct DescriptorParams params = {idx, buffer, length}; + + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d getString idx:%{public}d", __func__, __LINE__, idx); + if (idx == 0) { + delete[] buffer; + return string; + } + + ret = UsbdClient::GetStringDescriptor(busNum, devAddr, params); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d get string[%{public}d] failed ret:%{public}d", __func__, + __LINE__, idx, ret); + delete[] buffer; + return string; + } + if ((length < 2) || (buffer[1] != 0x03)) { + USB_HILOGW(MODULE_USB_SERVICE, + "%{public}s:%{public}d type or length error, type:0x%{public}02x(0x03) len:%{public}d", __func__, + __LINE__, buffer[1], length); + delete[] buffer; + return string; + } + uint16_t tbuf[length + 1]; + for (uint32_t i = 0; i < length; ++i) { + tbuf[i] = buffer[i + 2]; + } + std::wstring wstr((wchar_t *)(tbuf), (length - 2) / 2); + string = std::string(wstr.begin(), wstr.end()); + + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d getString idx:%{public}d String:%{public}s length:%{public}d", + __func__, __LINE__, idx, string.c_str(), length); + delete[] buffer; + buffer = NULL; + return string; +} + +static std::string BcdToString(uint8_t *bcd, uint32_t bcdLen) +{ + std::string tstr; + for (uint32_t i = 0; i < bcdLen; ++i) { + tstr += std::to_string((bcd[i] & 0xf0) >> 4); + tstr += std::to_string((bcd[i] & 0x0f)); + } + return tstr; +} + +static int32_t FillDevStrings(UsbDevice *dev) +{ + uint8_t busNum; + uint8_t devAddr; + if (dev == NULL) { + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d dev is NULL", __func__, __LINE__); + return ERR_INVALID_VALUE; + } + + busNum = dev->GetBusNum(); + devAddr = dev->GetDevAddr(); + uint16_t bcdDevice = dev->GetbcdDevice(); + dev->SetVersion(BcdToString((uint8_t *)&bcdDevice, 2)); + dev->SetManufacturerName(GetDevStringValFromIdx(busNum, devAddr, dev->GetiManufacturer())); + dev->SetProductName(GetDevStringValFromIdx(busNum, devAddr, dev->GetiProduct())); + dev->SetmSerial(GetDevStringValFromIdx(busNum, devAddr, dev->GetiSerialNumber())); + USB_HILOGW(MODULE_USB_SERVICE, + "%{public}s:%{public}d iSerial:%{public}d mSerial:%{public}s Manufactur:%{public}s product:%{public}s " + "version:%{public}s", + __func__, __LINE__, dev->GetiSerialNumber(), dev->GetmSerial().c_str(), + dev->GetManufacturerName().c_str(), dev->GetProductName().c_str(), dev->GetVersion().c_str()); + + std::vector configs; + configs = dev->GetConfigs(); + for (auto it = configs.begin(); it != configs.end(); ++it) { + it->SetName(GetDevStringValFromIdx(busNum, devAddr, it->GetiConfiguration())); + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d Config:%{public}d %{public}s", __func__, __LINE__, + it->GetiConfiguration(), it->GetName().c_str()); + std::vector interfaces = it->GetInterfaces(); + for (auto itIF = interfaces.begin(); itIF != interfaces.end(); ++itIF) { + itIF->SetName(GetDevStringValFromIdx(busNum, devAddr, itIF->GetiInterface())); + USB_HILOGW(MODULE_USB_SERVICE, "%{public}s:%{public}d interface:%{public}d %{public}s", __func__, __LINE__, + itIF->GetiInterface(), itIF->GetName().c_str()); + } + it->SetInterfaces(interfaces); + } + dev->SetConfigs(configs); + + return ERR_OK; +} + +int32_t UsbService::GetDeviceInfo(uint8_t busNum, uint8_t devAddr, UsbDevice *dev) +{ + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d busNum:%{public}d devAddr:%{public}d", __func__, __LINE__, + busNum, devAddr); + + if (!dev) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d dev is NULL busNum:%{public}d devAddr:%{public}d", + __func__, __LINE__, busNum, devAddr); + return ERR_INVALID_VALUE; + } + int32_t ret = ERR_OK; + uint32_t length = USB_MAX_DESCRIPTOR_SIZE; + uint8_t *buffer = new uint8_t[length]; + ret = UsbdClient::OpenDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d fumang UsbdClient::OpenDevice ret=%{public}d", __func__, + __LINE__, ret); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang UsbdClient::OpenDevice failed ret=%{public}d", __func__, ret); + delete[] buffer; + return ret; + } + + ret = UsbdClient::GetDeviceDescriptor(busNum, devAddr, buffer, length); + if (ret != ERR_OK) { + UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, + "%{public}s:%{public}d UsbdClient::GetDeviceDescriptor failed ret=%{public}d busNum:%{public}d " + "devAddr:%{public}d", + __func__, __LINE__, ret, busNum, devAddr); + delete[] buffer; + return ret; + } + dev->SetBusNum(busNum); + dev->SetDevAddr(devAddr); + dev->SetName(std::to_string(busNum) + "-" + std::to_string(devAddr)); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang GetDeviceDescriptor length=%{public}d", __func__, length); + ret = UsbDescriptorParser::ParseDeviceDescriptor(buffer, length, *dev); + if (ret != ERR_OK) { + UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s ParseDeviceDescriptor failed ret=%{public}d", __func__, ret); + delete[] buffer; + return ret; + } + + std::vector configs; + for (uint8_t i = 0; i < dev->GetDescConfigCount(); ++i) { + uint32_t cursor = 0; + length = USB_MAX_DESCRIPTOR_SIZE; + struct DescriptorParams params = {i, buffer, length}; + ret = UsbdClient::GetConfigDescriptor(busNum, devAddr, params); + if (ret != ERR_OK) { + UsbdClient::CloseDevice(busNum, devAddr); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang UsbdClient::GetConfigDescriptor failed ret=%{public}d", + __func__, ret); + delete[] buffer; + return ret; + } + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang GetConfigDescriptor length=%{public}d", __func__, length); + uint32_t configCursor = 0; + USBConfig config; + ret = UsbDescriptorParser::ParseConfigDescriptor(buffer + cursor, length - cursor, configCursor, config); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s ParseConfigDescriptor[%{public}d] ret:%{public}d", __func__, i, ret); + cursor += configCursor; + configs.push_back(config); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang Descriptor=%{public}s", __func__, config.ToString().c_str()); + } + dev->SetConfigs(configs); + ret = FillDevStrings(dev); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s:%{public}d FillDevStrings ret=%{public}d", __func__, __LINE__, ret); + + UsbdClient::CloseDevice(busNum, devAddr); + delete[] buffer; + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s fumang Descriptor=%{public}s", __func__, dev->ToString().c_str()); + + return ERR_OK; +} + +bool UsbService::AddDevice(uint8_t busNum, uint8_t devAddr) +{ + int32_t ret = ERR_OK; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d busNum:%{public}d devAddr:%{public}d", __func__, __LINE__, busNum, + devAddr); + UsbDevice *devInfo = new UsbDevice(); + memset(devInfo, 0, sizeof(UsbDevice)); + ret = GetDeviceInfo(busNum, devAddr, devInfo); + if (ret == ERR_OK) { + usbHostManger_->AddDevice(devInfo); + return true; + } + delete devInfo; + return false; +} +bool UsbService::DelDevice(uint8_t busNum, uint8_t devAddr) +{ + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d fumang entry", __func__, __LINE__); + int32_t ret = Close(busNum, devAddr); + if (ret != ERR_OK) { + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d Close device failed width ret = %{public}d", __func__, __LINE__, + ret); + } + return usbHostManger_->DelDevice(busNum, devAddr); +} + +void UsbService::UpdateUsbPort(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) +{ + usbPortManager->UpdatePort(portId, powerRole, dataRole, mode); +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/src/usb_service_subscriber.cpp b/services/native/src/usb_service_subscriber.cpp new file mode 100644 index 00000000..c586c0ec --- /dev/null +++ b/services/native/src/usb_service_subscriber.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_service_subscriber.h" + +#include +#include "common_event_data.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "delayed_sp_singleton.h" +#include "ohos/aafwk/content/want.h" +#include "string_ex.h" +#include "usb_common.h" +#include "usb_service.h" + +using namespace OHOS::AAFwk; +using namespace OHOS::EventFwk; + +namespace OHOS { +namespace USB { + +UsbServiceSubscriber::UsbServiceSubscriber() {} + +int32_t UsbServiceSubscriber::PortChangedEvent(int32_t portId, int32_t powerRole, int32_t dataRole, int32_t mode) +{ + auto pms = DelayedSpSingleton::GetInstance(); + Want want; + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_PORT_CHANGED); + pms->UpdateUsbPort(portId, powerRole, dataRole, mode); + CommonEventData data; + data.SetWant(want); + CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(true); + bool isSuccess = CommonEventManager::PublishCommonEvent(data, publishInfo); + if (!isSuccess) { + USB_HILOGE(MODULE_USB_SERVICE, "failed to publish PortChangedEvent"); + } + return isSuccess; +} + +int32_t UsbServiceSubscriber::DeviceEvent(const UsbInfo &info) +{ + struct timeval start; + gettimeofday(&start, NULL); + int status = info.getDevInfoStatus(); + int32_t ret = ERR_OK; + Want want; + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d status:%{public}d bus:%{public}d dev:%{public}d", __func__, __LINE__, + status, info.getDevInfoBusNum(), info.getDevInfoDevNum()); + switch (status) { + case ACT_DEVUP: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_DEVICE_ATTACHED); + break; + case ACT_DEVDOWN: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_DEVICE_DETACHED); + break; + case ACT_UPDEVICE: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_ACCESSORY_ATTACHED); + break; + case ACT_DOWNDEVICE: + want.SetAction(CommonEventSupport::COMMON_EVENT_USB_ACCESSORY_DETACHED); + break; + default: + return ret; + } + CommonEventData data; + data.SetWant(want); + CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(true); + bool isSuccess = CommonEventManager::PublishCommonEvent(data, publishInfo); + if (!isSuccess) { + USB_HILOGE(MODULE_USB_SERVICE, "failed to publish USB_CHANGED event"); + ret = ERR_NO_INIT; + } + struct timeval end; + gettimeofday(&end, NULL); + USB_HILOGD(MODULE_USB_SERVICE, "end call subscriber usb device tached event, takes : %{public}ld ms", + (end.tv_sec - start.tv_sec) * 1000 + (end.tv_usec - start.tv_usec) / 1000); + + if ((ACT_UPDEVICE == status) || (ACT_DOWNDEVICE == status)) { + return ret; + } + int busNum = info.getDevInfoBusNum(); + int devAddr = info.getDevInfoDevNum(); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d status:%{public}d bus:%{public}d dev:%{public}d", __func__, __LINE__, + status, busNum, devAddr); + auto pms = DelayedSpSingleton::GetInstance(); + USB_HILOGW(MODULE_USBD, "%{public}s:%{public}d status:%{public}d pms:%{public}s", __func__, __LINE__, status, + pms == nullptr ? "NULL" : "OK"); + if (status == ACT_DEVUP) { + USB_HILOGE(MODULE_USB_SERVICE, "usb attached"); + pms->AddDevice(busNum, devAddr); + } else { + USB_HILOGE(MODULE_USB_SERVICE, "usb detached"); + pms->DelDevice(busNum, devAddr); + } + + return ret; +} + +int32_t UsbServiceSubscriber::Update(const UsbInfo &info) +{ + return ERR_NO_INIT; +} + +} // namespace USB +} // namespace OHOS diff --git a/services/native/test/BUILD.gn b/services/native/test/BUILD.gn new file mode 100644 index 00000000..377eedea --- /dev/null +++ b/services/native/test/BUILD.gn @@ -0,0 +1,22 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//build/test.gni") + +#################################group######################################### +group("usb_service_unittest") { + testonly = true + deps = [ "unittest/common:unittest", ] + +} +############################################################################### \ No newline at end of file diff --git a/services/native/test/unittest/common/BUILD.gn b/services/native/test/unittest/common/BUILD.gn new file mode 100644 index 00000000..39844e91 --- /dev/null +++ b/services/native/test/unittest/common/BUILD.gn @@ -0,0 +1,166 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +module_output_path = "usb_manager_native/usb_service_test" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "//base/usb/usb_manager/interfaces/innerkits/native/include", + ] +} + +##############################unittest##########################################= + +ohos_unittest("test_usbport") { + module_out_path = module_output_path + sources = [ + "src/usb_port_service_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_usbpipe") { + module_out_path = module_output_path + sources = [ + "src/usb_device_pipe_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_usbrequest") { + module_out_path = module_output_path + sources = [ + "src/usb_request_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +ohos_unittest("test_usbcore") { + module_out_path = module_output_path + sources = [ + "src/usb_core_test.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "${usb_manager_path}/interfaces/innerkits:usbsrv_client", + "${usb_manager_path}/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + "${usb_manager_path}/hdi/client:usbd_client", + ] + + external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", + ] +} +############################################################################### +group("unittest") { + testonly = true + deps = [ + ":test_usbport", + ":test_usbpipe", + ":test_usbrequest", + ":test_usbcore" + ] +} +############################################################################### diff --git a/services/native/test/unittest/common/include/usb_core_test.h b/services/native/test/unittest/common/include/usb_core_test.h new file mode 100644 index 00000000..1d2b1c53 --- /dev/null +++ b/services/native/test/unittest/common/include/usb_core_test.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_CORE_TEST_H +#define USB_CORE_TEST_H + +#include + +class UsbCoreTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif \ No newline at end of file diff --git a/services/native/test/unittest/common/include/usb_device_pipe_test.h b/services/native/test/unittest/common/include/usb_device_pipe_test.h new file mode 100644 index 00000000..38e3c61e --- /dev/null +++ b/services/native/test/unittest/common/include/usb_device_pipe_test.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_UsbDevicePipeTest_TEST_H +#define USB_UsbDevicePipeTest_TEST_H + +#include + +class UsbDevicePipeTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + static void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length); +}; +#endif \ No newline at end of file diff --git a/services/native/test/unittest/common/include/usb_request_test.h b/services/native/test/unittest/common/include/usb_request_test.h new file mode 100644 index 00000000..168a7160 --- /dev/null +++ b/services/native/test/unittest/common/include/usb_request_test.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_UsbRequestTest_TEST_H +#define USB_UsbRequestTest_TEST_H + +#include + +class UsbRequestTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; +#endif diff --git a/services/native/test/unittest/common/src/usb_core_test.cpp b/services/native/test/unittest/common/src/usb_core_test.cpp new file mode 100644 index 00000000..bc558595 --- /dev/null +++ b/services/native/test/unittest/common/src/usb_core_test.cpp @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_core_test.h" +#include +#include +#include +#include +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "string_ex.h" +#include "system_ability_definition.h" +#include "usb_service.h" +#include "usb_srv_client.h" + +using namespace testing::ext; +using namespace OHOS::USB; +using namespace OHOS; +using namespace std; + +void UsbCoreTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbCoreTest-----------"); +} + +void UsbCoreTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbCoreTest-----------"); +} + +void UsbCoreTest::SetUp(void) {} + +void UsbCoreTest::TearDown(void) {} + +/** + * @tc.name: GetCurrentFunctions003 + * @tc.desc: Test functions to GetCurrentFunctions() + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, GetCurrentFunctions003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : GetCurrentFunctions003 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t funcs = 0; + funcs = instance.GetCurrentFunctions(funcs); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::funcs=%{public}d", funcs); + ASSERT_TRUE(funcs == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : GetCurrentFunctions003 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions005 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions005 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions005 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions006 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions006 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(2); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions006 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions007 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions007 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(3); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions007 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions008 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, SetCurrentFunctions008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions008 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(4); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions008 : SetConfig-----------"); +} + +/** + * @tc.name: SetCurrentFunctions009 + * @tc.desc: Test functions to SetCurrentFunctions(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionService009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetCurrentFunctions009 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t isok = instance.SetCurrentFunctions(8); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::SetCurrentFunctions=%{public}d", isok); + ASSERT_TRUE(isok != ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetCurrentFunctions009 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsFromString010 + * @tc.desc: Test functions to UsbFunctionsFromString(string funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsFromString010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString010 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + int32_t funcCode = instance.UsbFunctionsFromString(UsbFunctionManager::FUNCTION_NAME_HDC); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::functionsFromString=%{public}d", funcCode); + ASSERT_TRUE(funcCode); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString010 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString011 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString011, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString011 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_NONE); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(funcName.empty()); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString011 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString012 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString012, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString012 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_HDC); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString012 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString013 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString013, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString013 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_ACM); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString013 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString014 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString014, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString014 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(UsbFunctionManager::FUNCTION_ECM); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString014 : SetConfig-----------"); +} + +/** + * @tc.name: UsbFunctionsToString015 + * @tc.desc: Test functions to UsbFunctionsToString(int32_t funcs) + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbFunctionsToString015, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbFunctionsFromString015 : SetConfig-----------"); + auto &instance = UsbSrvClient::GetInstance(); + std::string funcName = instance.UsbFunctionsToString(-1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbFunctionServiceTest::UsbFunctionsToString=%{public}s", funcName.c_str()); + ASSERT_TRUE(!(funcName.empty())); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbFunctionsFromString015 : SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight018 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 正向测试:代码正常运行,返回结果为0 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight018, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight018: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_60"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight018 HasRight=%{public}d", result); + ASSERT_TRUE(result != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight018: SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight019 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 反向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight019, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight019: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_60"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight019 HasRight=%{public}d", result); + ASSERT_TRUE(result != 0); + result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight019 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight019 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight019: SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight020 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 反向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight020, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight020: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_60"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight020 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + deviceName = "device_61"; + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight020 HasRight=%{public}d", result); + ASSERT_TRUE(result == -1); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight020: SetConfig-----------"); +} + +/** + * @tc.name: UsbHasRight021 + * @tc.desc: Test functions of HasRight + * @tc.desc: int32_t HasRight(std::string deviceName) + * @tc.desc: 反向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, UsbHasRight021, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbHasRight021: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_62"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight021 HasRight=%{public}d", result); + ASSERT_TRUE(result == -1); + result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight021 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::UsbHasRight021 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbHasRight021: SetConfig-----------"); +} + +/** + * @tc.name: Usbrequestright022 + * @tc.desc: Test functions of requestright + * @tc.desc: int32_t requestright(std::string deviceName) + * @tc.desc: 正向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, Usbrequestright022, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestright022: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_61"; + int32_t result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright022 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright022 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestright022: SetConfig-----------"); +} +/** + * @tc.name: Usbrequestright023 + * @tc.desc: Test functions of requestright + * @tc.desc: int32_t requestright(std::string deviceName) + * @tc.desc: 正向测试:代码正常运行,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, Usbrequestright023, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestright023: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_62"; + int32_t result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright023 RequestRight=%{public}d", result); + ASSERT_TRUE(result == -1); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright023 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestright023: SetConfig-----------"); +} + +/** + * @tc.name: Usbrequestright024 + * @tc.desc: Test functions of requestright + * @tc.desc: int32_t requestright(std::string deviceName) + * @tc.desc: 反向测试:代码报错,返回结果为1 + * @tc.type: FUNC + */ +HWTEST_F(UsbCoreTest, Usbrequestright024, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestright024: SetConfig-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::string deviceName = "device_63"; + int32_t result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright024 HasRight=%{public}d", result); + ASSERT_TRUE(result == -1); + result = UsbSrvClient.RequestRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright024 RequestRight=%{public}d", result); + ASSERT_TRUE(result == 0); + result = UsbSrvClient.HasRight(deviceName); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Usbrequestright024 HasRight=%{public}d", result); + ASSERT_TRUE(result == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestright024: SetConfig-----------"); +} \ No newline at end of file diff --git a/services/native/test/unittest/common/src/usb_device_pipe_test.cpp b/services/native/test/unittest/common/src/usb_device_pipe_test.cpp new file mode 100644 index 00000000..31e5c0ac --- /dev/null +++ b/services/native/test/unittest/common/src/usb_device_pipe_test.cpp @@ -0,0 +1,1778 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_device_pipe_test.h" +#include +#include +#include "delayed_sp_singleton.h" +#include "hilog_wrapper.h" +#include "if_system_ability_manager.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_service.h" +#include "usb_srv_client.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +void UsbDevicePipeTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbDevicePipeTest-----------"); +} + +void UsbDevicePipeTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbDevicePipeTest-----------"); +} + +void UsbDevicePipeTest::SetUp(void) {} + +void UsbDevicePipeTest::TearDown(void) {} + +void UsbDevicePipeTest::PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << 二进制数据流[" << length << "字节] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_INNERKIT, "%{public}s", oss.str().c_str()); +} + +/** + * @tc.name: getDevices001 + * @tc.desc: Test functions to getDevices(std::vector &deviceList); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, getDevices001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : getDevices001 : getDevices-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::getDevices001 %{public}d Close=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : getDevices001 : getDevices-----------"); +} + +/** + * @tc.name: UsbOpenDevice001 + * @tc.desc: Test functions of OpenDevice + * @tc.desc: int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip) + * @tc.desc: 正向测试:代码正常运行,返回结果为0 + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbOpenDevice001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbOpenDevice001: OpenDevice-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + std::vector deviceList; + auto ret = UsbSrvClient.GetDevices(deviceList); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbOpenDevice001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(deviceList.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbOpenDevice001 %{public}d size=%{public}d", __LINE__, + deviceList.size()); + USBDevicePipe pipe; + ret = UsbSrvClient.OpenDevice(deviceList[0], pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbOpenDevice001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbOpenDevice001: OpenDevice-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer001 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer001 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 8; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 8, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer001 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer001 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer002 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer002 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 8; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 8, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer002 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer002 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer003 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer003 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 8; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 8, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer003 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer003 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer004 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer004 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 8; + uint8_t buffer[255] = {}; + memset(buffer, 0, 255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 6, 0x100, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer004 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer004 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer005 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer005 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 8; + uint8_t buffer[255] = {}; + memset(buffer, 0, 255); + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 6, 0x100, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer005 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer005 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer006 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer006 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 8; + uint8_t buffer[255] = {}; + memset(buffer, 0, 255); + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 6, 0x100, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer006 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer006 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer007 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer007 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0X0A, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer007 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer007 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer008 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer008 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0X0A, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer008 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer008 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer009 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer009 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0X0A, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer009 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer009 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer010 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer010 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer010 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer010 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer011 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer011, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer011 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer011 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer011 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer012 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer012, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer012 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000000, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer012 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer012 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer0013 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer0013, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer0013 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {0}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0013 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer0013 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer0014 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer0014, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer0014 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {0}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0014 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer0014 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer0015 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer0015, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer0015 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 255; + uint8_t buffer[255] = {0}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000001, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer0015 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer0015 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer016 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer016, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer016 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 16; + uint8_t buffer[255] = {0}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer016 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer016 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer017 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer017, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer017 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 16; + uint8_t buffer[255] = {0}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer017 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer017 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer018 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer018, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer018 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + uint32_t len = 16; + uint8_t buffer[255] = {0}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer018 %{public}d Close=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer018 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer019 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer019, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer019 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = {}; + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0X0C, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer019 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer019 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer020 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer020, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer020 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetBusNum(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0X0C, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer020 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer020 : ControlTransfer-----------"); +} + +/** + * @tc.name: Usbcontrolstansfer021 + * @tc.desc: Test functions to ControlTransfer + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Usbcontrolstansfer021, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbcontrolstansfer021 : ControlTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = {}; + pipe.SetDevAddr(255); + ret = UsbSrvClient.ControlTransfer(pipe, 0b10000010, 0X0C, 0, 0, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Usbcontrolstansfer021 %{public}d ControlTransfer=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbCoreTest::Close=%{public}d", ret); + ASSERT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbcontrolstansfer021 : ControlTransfer-----------"); +} + +/** + * @tc.name: UsbClaimInterface001 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface001 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbClaimInterface001 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbClaimInterface002 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface002 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().front(); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbClaimInterface002 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbClaimInterface003 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface003 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().at(1); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface003 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbClaimInterface003 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbClaimInterface004 + * @tc.desc: Test functions to ClaimInterface(const UsbInterface &interface, bool force); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbClaimInterface004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface004 : ClaimInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().at(1); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, false); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbClaimInterface004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbClaimInterface004 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbClaimInterface004 : ClaimInterface-----------"); +} + +/** + * @tc.name: UsbReleaseInterface001 + * @tc.desc: Test functions to ReleaseInterface(const UsbInterface &interface); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbReleaseInterface001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbReleaseInterface001 : ReleaseInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(0); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbReleaseInterface001 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbReleaseInterface001 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbReleaseInterface002 + * @tc.desc: Test functions to ReleaseInterface(const UsbInterface &interface); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbReleaseInterface002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbReleaseInterface002 : ReleaseInterface-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d ret=%{public}d", __LINE__, + ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d OpenDevice=%{public}d", + __LINE__, ret); + UsbInterface interface = devi.front().GetConfigs().front().GetInterfaces().at(1); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbReleaseInterface002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbReleaseInterface002 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbReleaseInterface002 : ReleaseInterface-----------"); +} + +/** + * @tc.name: UsbBulkTransfer001 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer001 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbDevicePipeTest::PrintBuffer("BulkTransferRead", buffer, len); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer001 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer001 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer002 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer002 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, -5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer002 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer002 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer003 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer003 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + pipe.SetBusNum(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer003 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer003 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer004 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer004 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + memset(buffer, 0, len); + pipe.SetDevAddr(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d len=%{public}d", __LINE__, len); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer004 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer004 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer005 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer005 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + point.SetInterfaceId(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer005 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer005 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer006 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer006 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "bulk read"; + uint32_t len = 255; + point.SetAddr(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer006 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer006 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer007 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer007, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer007 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer007"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer007 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer007 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer008 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer008 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer008"; + uint32_t len = 255; + pipe.SetDevAddr(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer008 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer008 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer009 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer009 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer009"; + uint32_t len = 255; + pipe.SetBusNum(255); + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, 500); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer009 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer009 : BulkTransfer-----------"); +} + +/** + * @tc.name: UsbBulkTransfer010 + * @tc.desc: Test functions to BulkTransfer(const USBEndpoint &endpoint, uint8_t *buffer, uint32_t &length, int32_t + * timeout); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, UsbBulkTransfer010, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbBulkTransfer010 : BulkTransfer-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ReleaseInterface(pipe, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pipe, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d point=%{public}d", __LINE__, + point.GetInterfaceId()); + uint8_t buffer[255] = "hello world Bulk transfer010"; + uint32_t len = 255; + ret = UsbSrvClient.BulkTransfer(pipe, point, buffer, len, -5); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d BulkTransfer=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::UsbBulkTransfer010 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbBulkTransfer010 : BulkTransfer-----------"); +} + +/** + * @tc.name: SetConfiguration001 + * @tc.desc: Test functions to SetConfiguration(const USBConfig &config); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, SetConfiguration001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetConfiguration001 : SetConfiguration-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + USBConfig config = device.GetConfigs().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.SetConfiguration(pipe, config); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration001 %{public}d SetConfiguration=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::SetConfiguration001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetConfiguration001 : SetConfiguration-----------"); +} + +/** + * @tc.name: SetConfiguration002 + * @tc.desc: Test functions to SetConfiguration(const USBConfig &config); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, SetConfiguration002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetConfiguration002 : SetConfiguration-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + USBConfig config = device.GetConfigs().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetBusNum(255); + ret = UsbSrvClient.SetConfiguration(pipe, config); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration002 %{public}d SetConfiguration=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::SetConfiguration002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetConfiguration002 : SetConfiguration-----------"); +} + +/** + * @tc.name: SetConfiguration003 + * @tc.desc: Test functions to SetConfiguration(const USBConfig &config); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, SetConfiguration003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : SetConfiguration003 : SetConfiguration-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d size=%{public}d", __LINE__, + devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + USBConfig config = device.GetConfigs().front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetDevAddr(255); + ret = UsbSrvClient.SetConfiguration(pipe, config); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::SetConfiguration003 %{public}d SetConfiguration=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret != ERR_OK); + pipe.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::SetConfiguration003 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : SetConfiguration003 : SetConfiguration-----------"); +} + +/** + * @tc.name: Close001 + * @tc.desc: Test functions to Close(); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Close001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Close001 : Close-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close001 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close001 %{public}d size=%{public}d", __LINE__, devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close001 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close001 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Close001 : Close-----------"); +} + +/** + * @tc.name: Close002 + * @tc.desc: Test functions to Close(); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Close002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Close002 : Close-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close002 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close002 %{public}d size=%{public}d", __LINE__, devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close002 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetBusNum(255); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close002 %{public}d close=%{public}d", __LINE__, ret); + ASSERT_TRUE(!ret); + pipe.SetBusNum(device.GetBusNum()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close002 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Close002 : Close-----------"); +} + +/** + * @tc.name: Close003 + * @tc.desc: Test functions to Close(); + * @tc.type: FUNC + */ +HWTEST_F(UsbDevicePipeTest, Close003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Close003 : Close-----------"); + vector devi; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(devi); + ASSERT_TRUE(ret == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close003 %{public}d ret=%{public}d", __LINE__, ret); + ASSERT_TRUE(!(devi.empty())) << "delist NULL"; + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close003 %{public}d size=%{public}d", __LINE__, devi.size()); + USBDevicePipe pipe; + UsbDevice device = devi.front(); + ret = UsbSrvClient.OpenDevice(device, pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbDevicePipeTest::Close003 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + pipe.SetDevAddr(255); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close003 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(!ret); + pipe.SetDevAddr(device.GetDevAddr()); + ret = UsbSrvClient.Close(pipe); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Close003 %{public}d close=%{public}d", __LINE__, ret); + EXPECT_TRUE(ret); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Close003 : Close-----------"); +} \ No newline at end of file diff --git a/services/native/test/unittest/common/src/usb_port_service_test.cpp b/services/native/test/unittest/common/src/usb_port_service_test.cpp new file mode 100644 index 00000000..4b014207 --- /dev/null +++ b/services/native/test/unittest/common/src/usb_port_service_test.cpp @@ -0,0 +1,200 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 +#include +#include +#include + +#include "usb_service.h" +#include "usb_srv_client.h" + +using namespace testing::ext; +using namespace OHOS::USB; +using namespace OHOS; + +class UsbPortServiceTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; + +void UsbPortServiceTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbPortServiceTest-----------"); +} + +void UsbPortServiceTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbPortServiceTest-----------"); +} + +void UsbPortServiceTest::SetUp(void) {} + +void UsbPortServiceTest::TearDown(void) {} + +/** + * @tc.name: UsbPortServiceTest01 + * @tc.desc: Test functions to GetPorts + * @tc.desc: int32_t GetPorts(std::vector &usbports); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest01, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest01 : GetPorts-----------"); + auto &usbSrvClient = UsbSrvClient::GetInstance(); + std::vector portlist; + auto ports = usbSrvClient.GetPorts(portlist); + USB_HILOGD(MODULE_USB_SERVICE, "Get UsbPort size=%{public}d", ports); + ASSERT_TRUE(ports == ERR_OK); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest01 : GetPorts-----------"); +} + +/** + * @tc.name: UsbPortServiceTest02 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t GetSupportedModes(int32_t portId, int32_t &result); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest02, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest02 : GetSupportedModes-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + int32_t result = 0; + auto modes = UsbSrvClient.GetSupportedModes(0, result); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", modes); + ASSERT_TRUE(modes != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest02 : GetSupportedModes-----------"); +} + +/** + * @tc.name: UsbPortServiceTest03 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t GetSupportedModes(int32_t portId, int32_t &result); + * @tc.desc: 反向测试:portid错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest03, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest03 : GetSupportedModes-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + int32_t result = 0; + auto modes = UsbSrvClient.GetSupportedModes(-1, result); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", modes); + ASSERT_TRUE(modes != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest03 : GetSupportedModes-----------"); +} + +/** + * @tc.name: UsbPortServiceTest04 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t GetSupportedModes(int32_t portId, int32_t &result); + * @tc.desc: 反向测试:portid错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest04, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest04 : GetSupportedModes-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + int32_t result = 0; + auto modes = UsbSrvClient.GetSupportedModes(0xFFFFFFFF, result); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", modes); + ASSERT_TRUE(modes != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest04 : GetSupportedModes-----------"); +} + +/** + * @tc.name: UsbPortServiceTest05 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 正向测试:参数正确 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest05, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest05 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(1, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret == 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest05 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbPortServiceTest06 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 反向测试:portid错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest06, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest06 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(-1, 1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest06 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbPortServiceTest07 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 反向测试:powerRole错误 + * @tc.type: FUNC + */ + +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest07, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest07 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(1, -1, 1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest07 : SetPortRole-----------"); +} + +/** + * @tc.name: UsbPortServiceTest08 + * @tc.desc: Test functions to GetSupportedModes + * @tc.desc: int32_t SetPortRole(int32_t portId,int32_t powerRole,int32_t dataRole); + * @tc.desc: 反向测试:dataRole错误 + * @tc.type: FUNC + */ +HWTEST_F(UsbPortServiceTest, UsbPortServiceTest08, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbPortServiceTest08 : SetPortRole-----------"); + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.SetPortRole(1, 1, -1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbServiceTest::status=%{public}d", 1); + ASSERT_TRUE(ret != 0); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbPortServiceTest08 : SetPortRole-----------"); +} diff --git a/services/native/test/unittest/common/src/usb_request_test.cpp b/services/native/test/unittest/common/src/usb_request_test.cpp new file mode 100644 index 00000000..5d1d981a --- /dev/null +++ b/services/native/test/unittest/common/src/usb_request_test.cpp @@ -0,0 +1,712 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_request_test.h" +#include +#include +#include +#include +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iusb_srv.h" +#include "system_ability_definition.h" +#include "usb_common.h" +#include "usb_device_pipe.h" +#include "usb_request.h" +#include "usb_service.h" +#include "usb_srv_client.h" +using namespace testing::ext; +using namespace OHOS::USB; +using namespace OHOS; +using namespace std; + +void UsbRequestTest::SetUpTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Start UsbdRequestTest-----------"); +} + +void UsbRequestTest::TearDownTestCase(void) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------End UsbdRequestTest-----------"); +} + +void UsbRequestTest::SetUp(void) {} + +void UsbRequestTest::TearDown(void) {} +/** + * @tc.name: UsbRequestInitialize001 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize001 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().front(); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + uint8_t tag[50] = "request read"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize001 %{public}d Initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize001 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize001 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize002 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize002 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d OpenDevice=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request write"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize002 %{public}d Initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize002 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize002 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize003 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize003, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize003 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize003 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize003 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize003 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize003 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request read"; + request.SetClientData((void *)tag, 11); + pip.SetBusNum(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize003 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize003 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize003 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize004 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize004, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize004 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize004 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize004 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize004 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize004 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request read"; + request.SetClientData((void *)tag, 11); + pip.SetDevAddr(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize004 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize004 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize004 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize005 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize005, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize005 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize005 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize005 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize005 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize005 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request write"; + request.SetClientData((void *)tag, 11); + pip.SetBusNum(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize005 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetBusNum(device.GetBusNum()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize005 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize005 : Initialize-----------"); +} + +/** + * @tc.name: UsbRequestInitialize006 + * @tc.desc: Test functions of Initialize(const USBDevicePipe &pipe, const USBEndpoint &endpoint) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbRequestInitialize006, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbRequestInitialize006 : Initialize-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize006 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize006 %{public}d ret=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize006 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize006 %{public}d ClaimInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request write"; + request.SetClientData((void *)tag, 11); + pip.SetDevAddr(255); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequestInitialize006 %{public}d ret=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret != ERR_OK); + pip.SetDevAddr(device.GetDevAddr()); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbRequestInitialize006 %{public}d close=%{public}d", __LINE__, + close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbRequestInitialize006 : Initialize-----------"); +} + +/** + * @tc.name: UsbrequestQueue001 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbrequestQueue001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbrequestQueue001 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = "request queue read001"; + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbrequestQueue001 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbrequestQueue002 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, UsbrequestQueue002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : UsbrequestQueue002 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint32_t len = 255; + uint8_t buffer[255] = "request queue write 002"; + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbrequestQueue002 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbrequestQueue002 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::UsbrequestQueue002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : UsbrequestQueue002 : RequestQueue-----------"); +} + +/** + * @tc.name: UsbrequestQueue003 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequest008, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequest008 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d ret=%{public}d size:%{public}d", __LINE__, + ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice devi = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(devi, pip); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbRequestTest:UsbRequest008 %{public}d ret=%{public}d pip.BusNum=%{public}d pip.DevAddr=%{public}d ", + __LINE__, ret, pip.GetBusNum(), pip.GetDevAddr()); + ASSERT_TRUE(ret == ERR_OK); + std::vector configs = devi.GetConfigs(); + USBConfig conf = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d size=%{public}d config:%{public}s ", + __LINE__, configs.size(), conf.ToString().c_str()); + USBConfig config = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d ret=%{public}d ", __LINE__, ret); + UsbRequest request; + UsbInterface &interface = config.GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d GetDirection=%{public}d ", __LINE__, + point.GetDirection()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d GetInterfaceId=%{public}d ", __LINE__, + point.GetInterfaceId()); + UsbSrvClient.ReleaseInterface(pip, interface); + UsbSrvClient.ClaimInterface(pip, interface, true); + uint32_t len = 1; + uint8_t buffer[1] = {0X12}; + UsbSrvClient.BulkTransfer(pip, point, buffer, len, 5); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest008 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequest008 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequest008 : RequestQueue-----------"); +} + +/** + * @tc.name: Usbrequest009 + * @tc.desc: Test functions of Queue(uint8_t *buffer, uint32_t length) + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequest009, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequest009 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d ret=%{public}d size:%{public}d", __LINE__, + ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice devi = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(devi, pip); + USB_HILOGI(MODULE_USB_SERVICE, + "UsbRequestTest:UsbRequest009 %{public}d ret=%{public}d pip.BusNum=%{public}d pip.DevAddr=%{public}d ", + __LINE__, ret, pip.GetBusNum(), pip.GetDevAddr()); + ASSERT_TRUE(ret == ERR_OK); + std::vector configs = devi.GetConfigs(); + USBConfig conf = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d size=%{public}d config:%{public}s ", + __LINE__, configs.size(), conf.ToString().c_str()); + USBConfig config = configs.front(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d ret=%{public}d ", __LINE__, ret); + UsbRequest request; + UsbInterface &interface = config.GetInterfaces().at(0); + USBEndpoint point = interface.GetEndpoints().at(0); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d GetDirection=%{public}d ", __LINE__, + point.GetDirection()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d GetInterfaceId=%{public}d ", __LINE__, + point.GetInterfaceId()); + UsbSrvClient.ReleaseInterface(pip, interface); + UsbSrvClient.ClaimInterface(pip, interface, true); + uint32_t len = 255; + uint8_t buffer[255] = {}; + UsbSrvClient.ControlTransfer(pip, 0b10000010, 0, 0, 0, buffer, len, 50); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:UsbRequest009 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequest009 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequest009 : RequestQueue-----------"); +} + +/** + * @tc.name: Usbrequestfree001 + * @tc.desc: Test functions of free() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestfree001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestfree001 : RequestQueue-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d OpenDevice=%{public}d ", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree001 %{public}d ReleaseInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request free 001"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Free(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree001 %{public}d free=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestfree001 : RequestQueue-----------"); +} + +/** + * @tc.name: Usbrequestfree002 + * @tc.desc: Test functions of free() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestfree002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestfree002 : Requestfree-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d OpenDevice=%{public}d", __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + UsbRequest request; + USBEndpoint point = interface.GetEndpoints().at(1); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d ReleaseInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "request free 002"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree002 %{public}d initialize=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Free(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestfree002 %{public}d free=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestfree002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestfree002 : Requestfree-----------"); +} + +/** + * @tc.name: Usbrequestabort001 + * @tc.desc: Test functions of abort() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestabort001, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestabort001 : Requestabort-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(0); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort001 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort001 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "hello world request013"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "request abort 001"; + uint8_t len = 255; + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Abort(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort001 %{public}d Abort=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort001 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestabort001 : Requestabort-----------"); +} + +/** + * @tc.name: Usbrequestabort002 + * @tc.desc: Test functions of abort() + * @tc.type: FUNC + */ +HWTEST_F(UsbRequestTest, Usbrequestabort002, TestSize.Level1) +{ + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case Start : Usbrequestabort002 : Requestabort-----------"); + vector delist; + auto &UsbSrvClient = UsbSrvClient::GetInstance(); + auto ret = UsbSrvClient.GetDevices(delist); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d ret=%{public}d size:%{public}d", + __LINE__, ret, delist.size()); + ASSERT_TRUE(ret == ERR_OK); + ASSERT_TRUE(!(delist.empty())) << "delist NULL"; + UsbDevice device = delist.front(); + USBDevicePipe pip; + ret = UsbSrvClient.OpenDevice(device, pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d OpenDevice=%{public}d ", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + UsbRequest request; + UsbInterface interface = device.GetConfigs().front().GetInterfaces().at(1); + USBEndpoint point = interface.GetEndpoints().at(1); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d GetDirection=%{public}d ", __LINE__, + point.GetDirection()); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d GetInterfaceId=%{public}d ", __LINE__, + point.GetInterfaceId()); + ret = UsbSrvClient.ReleaseInterface(pip, interface); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort002 %{public}d ReleaseInterface=%{public}d", + __LINE__, ret); + ASSERT_TRUE(ret == ERR_OK); + ret = UsbSrvClient.ClaimInterface(pip, interface, true); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort002 %{public}d ClaimInterface=%{public}d", __LINE__, + ret); + ASSERT_TRUE(ret == ERR_OK); + uint8_t tag[50] = "hello world request014"; + request.SetClientData((void *)tag, 11); + ret = request.Initialize(pip, point); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d initialize=%{public}d ", __LINE__, + ret); + EXPECT_TRUE(ret == ERR_OK); + uint8_t buffer[255] = "request abort 002"; + uint8_t len = 255; + ret = request.Queue(buffer, len); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d queue=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + ret = request.Abort(); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest:Usbrequestabort002 %{public}d abort=%{public}d ", __LINE__, ret); + EXPECT_TRUE(ret == ERR_OK); + bool close = UsbSrvClient.Close(pip); + USB_HILOGI(MODULE_USB_SERVICE, "UsbRequestTest::Usbrequestabort002 %{public}d close=%{public}d", __LINE__, close); + EXPECT_TRUE(close); + USB_HILOGI(MODULE_USB_SERVICE, "-----------Case End : Usbrequestabort002 : Requestabort-----------"); +} diff --git a/services/zidl/include/usb_server_proxy.h b/services/zidl/include/usb_server_proxy.h new file mode 100644 index 00000000..1a22b2c8 --- /dev/null +++ b/services/zidl/include/usb_server_proxy.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USBMGR_USB_SERVER_PROXY_H +#define USBMGR_USB_SERVER_PROXY_H + +#include +#include +#include "iremote_proxy.h" +#include "iusb_srv.h" +#include "nocopyable.h" +#include "usb_device.h" + +namespace OHOS { +namespace USB { + +class UsbServerProxy : public IRemoteProxy { +public: + explicit UsbServerProxy(const sptr &impl) : IRemoteProxy(impl) {} + ~UsbServerProxy() = default; + DISALLOW_COPY_AND_MOVE(UsbServerProxy); + + virtual int32_t GetDevices(std::vector &deviceList) override; + virtual int32_t OpenDevice(uint8_t busNum, uint8_t devAddr) override; + virtual int32_t HasRight(std::string deviceName) override; + virtual int32_t RequestRight(std::string deviceName) override; + virtual int32_t GetCurrentFunctions(int32_t &funcs) override; + virtual int32_t SetCurrentFunctions(int32_t funcs) override; + virtual int32_t UsbFunctionsFromString(std::string funcs) override; + virtual std::string UsbFunctionsToString(int32_t funcs) override; + virtual int32_t GetPorts(std::vector &ports) override; + virtual int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes) override; + virtual int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) override; + + virtual int32_t ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + virtual int32_t ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid) override; + virtual int32_t BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + virtual int32_t BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interfaceid, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) override; + virtual int32_t ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) override; + virtual int32_t SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) override; + virtual int32_t GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) override; + virtual int32_t SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) override; + virtual int32_t GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) override; + virtual int32_t RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointIndex, + const void *clientObj, + uint32_t objLength, + const uint8_t *buffer, + uint32_t length) override; + virtual int32_t RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) override; + virtual int32_t RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) override; + virtual int32_t Close(uint8_t busNum, uint8_t devAddr) override; + +private: + static inline BrokerDelegator delegator_; + void ParseUsbPort(MessageParcel &reply, std::vector &result); + int32_t SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr); + int32_t SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length); + int32_t GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length); + int32_t GetDeviceListMessageParcel(MessageParcel &data, std::vector &deviceList); + int32_t GetDeviceMessageParcel(MessageParcel &data, UsbDevice &devInfo); + int32_t GetDeviceConfigsMessageParcel(MessageParcel &data, std::vector &configs); + int32_t GetDeviceInterfacesMessageParcel(MessageParcel &data, std::vector &interfaces); + int32_t GetDeviceEndpointsMessageParcel(MessageParcel &data, std::vector &eps); +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVER_PROXY_H diff --git a/services/zidl/include/usb_server_stub.h b/services/zidl/include/usb_server_stub.h new file mode 100644 index 00000000..8b192a57 --- /dev/null +++ b/services/zidl/include/usb_server_stub.h @@ -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. + */ + +#ifndef USBMGR_USB_SERVER_STUB_H +#define USBMGR_USB_SERVER_STUB_H + +#include +#include "iremote_stub.h" +#include "iusb_srv.h" +#include "nocopyable.h" +#include "usb_device.h" + +namespace OHOS { +namespace USB { + +class UsbServerStub : public IRemoteStub { +public: + DISALLOW_COPY_AND_MOVE(UsbServerStub); + + UsbServerStub() = default; + virtual ~UsbServerStub() = default; + + virtual int32_t OnFoundDevice(FoundDevice &info) = 0; + + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; + +private: + const FoundDevice *ParserOpenDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + int32_t DoGetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoUsbFunctionsFromString(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoUsbFunctionsToString(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + int32_t DoOpenDevice(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoHasRight(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestRight(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetPorts(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetSupportedModes(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetPortRole(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoClaimInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoReleaseInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoBulkTransferRead(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoBulkTransferWrite(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoControlTransfer(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoSetInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetRawDescriptor(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestQueue(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestWait(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoRequestCancel(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + int32_t DoClose(MessageParcel &data, MessageParcel &reply, MessageOption &option); + int32_t DoGetDevices(MessageParcel &data, MessageParcel &reply, MessageOption &option); + + void WriteUsbPort(MessageParcel &reply, const UsbPort *port); + + int32_t GetDeviceMessage(MessageParcel &data, uint8_t &busNum, uint8_t &devAddr); + int32_t SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length); + int32_t GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length); + + int32_t SetDeviceListMessageParcel(std::vector &deviceList, MessageParcel &data); + int32_t SetDeviceMessageParcel(UsbDevice &devInfo, MessageParcel &data); + int32_t SetDeviceConfigsMessageParcel(std::vector &configs, MessageParcel &data); + int32_t SetDeviceInterfacesMessageParcel(std::vector &interfaces, MessageParcel &data); + int32_t SetDeviceEndpointsMessageParcel(std::vector &eps, MessageParcel &data); +}; + +} // namespace USB +} // namespace OHOS + +#endif // USBMGR_USB_SERVER_STUB_H diff --git a/services/zidl/iusb_server.zidl b/services/zidl/iusb_server.zidl new file mode 100644 index 00000000..c0dc2568 --- /dev/null +++ b/services/zidl/iusb_server.zidl @@ -0,0 +1,19 @@ +/* + * Copyright 2021 Huawei Device Co., Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface OHOS.Usb.IUsbServer { + /* the function about UsbService */ +} diff --git a/services/zidl/src/usb_srv_proxy.cpp b/services/zidl/src/usb_srv_proxy.cpp new file mode 100644 index 00000000..bb854db9 --- /dev/null +++ b/services/zidl/src/usb_srv_proxy.cpp @@ -0,0 +1,887 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ipc_types.h" +#include "message_parcel.h" +#include "securec.h" +#include "usb_common.h" +#include "usb_request.h" +#include "usb_server_proxy.h" + +namespace OHOS { +namespace USB { + +void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " < binary data [" << length << "bytes] > :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " -> " << buffer << std::endl; + USB_HILOGD(MODULE_USBD, "%{public}s", oss.str().c_str()); +} + +int32_t UsbServerProxy::SetDeviceMessage(MessageParcel &data, uint8_t busNum, uint8_t devAddr) +{ + WRITE_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerProxy::SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length) +{ + if (!data.WriteUint32(length)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && !data.WriteBuffer(buffer, length)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbServerProxy::GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length) +{ + uint32_t dataSize; + if (!data.ReadUint32(dataSize)) { + return ERR_INVALID_VALUE; + } + if (dataSize == 0) { + length = 0; + return ERR_OK; + } + if (!buffer) { + length = 0; + return ERR_INVALID_VALUE; + } + const uint8_t *readData = data.ReadBuffer(dataSize); + if (readData == nullptr) { + return ERR_INVALID_VALUE; + } + memcpy_s(buffer, length, readData, dataSize); + length = dataSize < length ? dataSize : length; + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d", __func__, length); + return ERR_OK; +} + +int32_t UsbServerProxy::GetDevices(std::vector &deviceList) +{ + int32_t ret; + sptr remote = Remote(); + if (remote == nullptr) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s remote is failed", __func__); + return ERR_INVALID_VALUE; + } + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_INVALID_VALUE; + } + + ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_DEVICES), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s failed code: %{public}d", __func__, ret); + return ret; + } + ret = GetDeviceListMessageParcel(reply, deviceList); + return ret; +} + +int32_t UsbServerProxy::GetDeviceListMessageParcel(MessageParcel &data, std::vector &deviceList) +{ + int32_t count; + data.ReadInt32(count); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s device size : %{public}d", __func__, count); + + for (int32_t i = 0; i < count; ++i) { + UsbDevice devInfo; + GetDeviceMessageParcel(data, devInfo); + deviceList.push_back(devInfo); + } + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceMessageParcel(MessageParcel &data, UsbDevice &devInfo) +{ + int32_t tmp; + uint8_t tui8; + uint16_t tui16; + std::string tstr; + data.ReadInt32(tmp); + devInfo.SetBusNum(tmp); + data.ReadInt32(tmp); + devInfo.SetDevAddr(tmp); + + data.ReadInt32(tmp); + devInfo.SetVendorId(tmp); + data.ReadInt32(tmp); + devInfo.SetProductId(tmp); + data.ReadInt32(tmp); + devInfo.SetClass(tmp); + data.ReadInt32(tmp); + devInfo.SetSubclass(tmp); + data.ReadInt32(tmp); + devInfo.SetProtocol(tmp); + data.ReadUint8(tui8); + devInfo.SetiManufacturer(tui8); + data.ReadUint8(tui8); + devInfo.SetiProduct(tui8); + data.ReadUint8(tui8); + devInfo.SetiSerialNumber(tui8); + data.ReadUint8(tui8); + devInfo.SetbMaxPacketSize0(tui8); + data.ReadUint16(tui16); + devInfo.SetbcdUSB(tui16); + data.ReadUint16(tui16); + devInfo.SetbcdDevice(tui16); + data.ReadString(tstr); + devInfo.SetName(tstr); + data.ReadString(tstr); + devInfo.SetManufacturerName(tstr); + data.ReadString(tstr); + devInfo.SetProductName(tstr); + data.ReadString(tstr); + devInfo.SetVersion(tstr); + data.ReadString(tstr); + devInfo.SetmSerial(tstr); + + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:%{public}d devName:%{public}s Bus:%{public}d dev:%{public}d ", __func__, + __LINE__, devInfo.GetName().c_str(), devInfo.GetBusNum(), devInfo.GetDevAddr()); + std::vector configs; + GetDeviceConfigsMessageParcel(data, configs); + devInfo.SetConfigs(configs); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s ToString : %{public}s", __func__, devInfo.ToString().c_str()); + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceConfigsMessageParcel(MessageParcel &data, std::vector &configs) +{ + int32_t tmp, configCount; + uint8_t tui8; + std::string tstr; + data.ReadInt32(tmp); + configCount = tmp; + for (int i = 0; i < configCount; ++i) { + USBConfig config; + data.ReadInt32(tmp); + config.SetId(tmp); + data.ReadInt32(tmp); + config.SetAttribute(tmp); + data.ReadInt32(tmp); + config.SetMaxPower(tmp); + + data.ReadUint8(tui8); + config.SetiConfiguration(tui8); + data.ReadString(tstr); + config.SetName(tstr); + + std::vector interfaces; + GetDeviceInterfacesMessageParcel(data, interfaces); + config.SetInterfaces(interfaces); + configs.push_back(config); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, config.ToString().c_str()); + } + + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceInterfacesMessageParcel(MessageParcel &data, std::vector &interfaces) +{ + int32_t tmp, interfaceCount; + uint8_t tui8; + std::string tstr; + data.ReadInt32(tmp); + interfaceCount = tmp; + for (int i = 0; i < interfaceCount; ++i) { + UsbInterface interface; + data.ReadInt32(tmp); + interface.SetId(tmp); + data.ReadInt32(tmp); + interface.SetClass(tmp); + data.ReadInt32(tmp); + interface.SetSubClass(tmp); + data.ReadInt32(tmp); + interface.SetAlternateSetting(tmp); + data.ReadInt32(tmp); + interface.SetProtocol(tmp); + + data.ReadUint8(tui8); + interface.SetiInterface(tui8); + data.ReadString(tstr); + interface.SetName(tstr); + + std::vector eps; + GetDeviceEndpointsMessageParcel(data, eps); + for (size_t j = 0; j < eps.size(); ++j) { + eps[j].SetInterfaceId(interface.GetId()); + } + interface.SetEndpoints(eps); + interfaces.push_back(interface); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, interface.ToString().c_str()); + } + return ERR_OK; +} + +int32_t UsbServerProxy::GetDeviceEndpointsMessageParcel(MessageParcel &data, std::vector &eps) +{ + int32_t tmp, epCount; + data.ReadInt32(tmp); + epCount = tmp; + for (int i = 0; i < epCount; ++i) { + USBEndpoint ep; + data.ReadInt32(tmp); + ep.SetAddr(tmp); + data.ReadInt32(tmp); + ep.SetAttr(tmp); + data.ReadInt32(tmp); + ep.SetInterval(tmp); + data.ReadInt32(tmp); + ep.SetMaxPacketSize(tmp); + eps.push_back(ep); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, ep.ToString().c_str()); + } + return ERR_OK; +} + +int32_t UsbServerProxy::OpenDevice(uint8_t busNum, uint8_t devAddr) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_OPEN_DEVICE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %{public}d", + __func__, ret); + return ret; + } + return ret; +} + +int32_t UsbServerProxy::HasRight(std::string deviceName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + WRITE_PARCEL_WITH_RET(data, String, deviceName, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_HAS_RIGHT), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + int32_t result = 0; + READ_PARCEL_WITH_RET(reply, Int32, result, E_READ_PARCEL_ERROR); + return result; +} + +int32_t UsbServerProxy::RequestRight(std::string deviceName) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + WRITE_PARCEL_WITH_RET(data, String, deviceName, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_RIGHT), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + int32_t result = 0; + READ_PARCEL_WITH_RET(reply, Int32, result, E_READ_PARCEL_ERROR); + return result; +} + +int32_t UsbServerProxy::GetCurrentFunctions(int32_t &funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, INVALID_USB_INT_VALUE); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_CURRENT_FUNCTIONS), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + + READ_PARCEL_WITH_RET(reply, Int32, funcs, INVALID_USB_INT_VALUE); + return ret; +} + +int32_t UsbServerProxy::SetCurrentFunctions(int32_t funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, false); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + + data.WriteInt32(funcs); + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_CURRENT_FUNCTIONS), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + return ret; +} + +int32_t UsbServerProxy::UsbFunctionsFromString(std::string funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, INVALID_USB_INT_VALUE); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + + data.WriteString(funcs); + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_FROM_STRING), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + + int32_t result = 0; + READ_PARCEL_WITH_RET(reply, Int32, result, INVALID_USB_INT_VALUE); + return result; +} + +std::string UsbServerProxy::UsbFunctionsToString(int32_t funcs) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, INVALID_STRING_VALUE); + + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_STRING_VALUE; + } + + data.WriteInt32(funcs); + int32_t ret = + remote->SendRequest(static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_TO_STRING), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_SERVICE, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_STRING_VALUE; + } + + std::string result; + READ_PARCEL_WITH_RET(reply, String, result, result); + return result; +} + +int32_t UsbServerProxy::GetPorts(std::vector &result) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_PORTS), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return INVALID_USB_INT_VALUE; + } + ret = reply.ReadInt32(); + USB_HILOGI(MODULE_USB_INNERKIT, "GetPorts ret %{public}d", ret); + if (ret != 0) { + return ret; + } + uint32_t size = reply.ReadInt32(); + USB_HILOGI(MODULE_USB_INNERKIT, "GetPorts size %{public}d", size); + for (uint32_t i = 0; i < size; ++i) { + USB_HILOGI(MODULE_USB_INNERKIT, "ParseUsbPort : %{public}d", i); + ParseUsbPort(reply, result); + } + return ret; +} + +void UsbServerProxy::ParseUsbPort(MessageParcel &reply, std::vector &ports) +{ + UsbPort *port = new UsbPort(); + UsbPortStatus *status = new UsbPortStatus(); + port->id = reply.ReadInt32(); + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::port->id %{public}d", port->id); + port->supportedModes = reply.ReadInt32(); + port->usbPortStatus = status; + status->currentMode = reply.ReadInt32(); + status->currentPowerRole = reply.ReadInt32(); + status->currentDataRole = reply.ReadInt32(); + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::port->usbPortStatus->currentMode %{public}d", + port->usbPortStatus->currentMode); + ports.push_back(port); + return; +} + +int32_t UsbServerProxy::GetSupportedModes(int32_t portId, int32_t &supportedModes) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + data.WriteInt32(portId); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_SUPPORTED_MODES), data, reply, option); + if (ret) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + ret = reply.ReadInt32(); + supportedModes = reply.ReadInt32(); + return ret; +} + +int32_t UsbServerProxy::SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return INVALID_USB_INT_VALUE; + } + data.WriteInt32(portId); + data.WriteInt32(powerRole); + data.WriteInt32(dataRole); + int32_t ret = Remote()->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_PORT_ROLE), data, reply, option); + if (ret) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + int32_t result = reply.ReadInt32(); + return result; +} + +int32_t UsbServerProxy::ClaimInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_CLAIM_INTERFACE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %{public}d", + __func__, ret); + return ret; + } + return ret; +} +int32_t UsbServerProxy::ReleaseInterface(uint8_t busNum, uint8_t devAddr, uint8_t interface) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_RELEASE_INTERFACE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + // int32_t ret = ERR_OK; + // READ_PARCEL_WITH_RET(reply, Int32, ret, E_READ_PARCEL_ERROR); + return ret; +} +int32_t UsbServerProxy::BulkTransferRead(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!buffer || (length == 0)) { + USB_HILOGW(MODULE_USBD, "%{public}s buffer is null or length is zero, length = %{public}d", __func__, length); + return ERR_INVALID_VALUE; + } + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_READ), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s SendRequest is failed, error code: %d", __func__, + ret); + return ret; + } + ret = GetBufferMessage(reply, buffer, length); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_USB_INNERKIT, "UsbServerProxy::%{public}s get buffer is failed, error code: %d", __func__, + ret); + return ret; + } + USB_HILOGW(MODULE_USBD, "%{public}s Set buffer message. length = %{public}d", __func__, length); + return ret; +} +int32_t UsbServerProxy::BulkTransferWrite(uint8_t busNum, + uint8_t devAddr, + uint8_t interface, + uint8_t endpoint, + const uint8_t *buffer, + uint32_t length, + int32_t timeout) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + PrintBuffer("UsbServerProxy::BulkTransferWrite", (const uint8_t *)buffer, length); + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + data.WriteUint8(interface); + data.WriteUint8(endpoint); + data.WriteUint32(timeout); + SetBufferMessage(data, buffer, length); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_WRITE), data, reply, option); + return ret; +} + +int32_t UsbServerProxy::ControlTransfer(uint8_t busNum, + uint8_t devAddr, + int32_t requestType, + int32_t request, + int32_t value, + int32_t index, + uint8_t *buffer, + uint32_t &length, + int32_t timeout) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, requestType, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, request, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, value, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, index, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + bool bWrite = ((requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT); + if (bWrite) { + data.WriteBuffer(buffer, length); + } + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_CONTROL_TRANSFER), data, reply, option); + if (ret != ERR_OK) { + return ret; + } + if (!bWrite) { + GetBufferMessage(reply, buffer, length); + PrintBuffer("UsbServerProxy::ControlTransfer", buffer, length); + USB_HILOGW(MODULE_USBD, "%{public}s Get buffer message. length = %{public}d", __func__, length); + } + return ERR_OK; +} +int32_t UsbServerProxy::SetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t configIndex) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, configIndex, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_ACTIVE_CONFIG), data, reply, option); + return ret; +} +int32_t UsbServerProxy::GetActiveConfig(uint8_t busNum, uint8_t devAddr, uint8_t &configIndex) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_ACTIVE_CONFIG), data, reply, option); + if (ret != ERR_OK) { + return ret; + } + READ_PARCEL_WITH_RET(reply, Uint8, configIndex, E_WRITE_PARCEL_ERROR); + return ret; +} +int32_t UsbServerProxy::SetInterface(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t altIndex) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, altIndex, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_SET_INTERFACE), data, reply, option); + return ret; +} +int32_t UsbServerProxy::GetRawDescriptor(uint8_t busNum, uint8_t devAddr, uint8_t *buffer, uint32_t &length) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s write descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_GET_DESCRIPTOR), data, reply, option); + if (ret == ERR_OK) { + GetBufferMessage(reply, buffer, length); + } + return ret; +} + +int32_t UsbServerProxy::RequestQueue(uint8_t busNum, + uint8_t devAddr, + uint8_t ifId, + uint8_t endpointId, + const void *clientObj, + uint32_t clientLength, + const uint8_t *buffer, + uint32_t length) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, ifId, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpointId, E_WRITE_PARCEL_ERROR); + SetBufferMessage(data, clientObj, clientLength); + SetBufferMessage(data, buffer, length); + // PrintBuffer("UsbServerProxy::RequestQueue buffer", buffer, length); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_QUEUE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s queue failed!", __func__); + return ret; + } + return ret; +} + +int32_t UsbServerProxy::RequestWait(uint8_t busNum, + uint8_t devAddr, + int32_t timeout, + void *clientData, + uint32_t &clientLength, + uint8_t *buffer, + uint32_t &length) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_WAIT), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s:%{public}d queue failed! ret:%{public}d", __func__, + __LINE__, ret); + return ret; + } + + ret = GetBufferMessage(reply, clientData, clientLength); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s:%{public}d get clientData failed! ret:%{public}d", + __func__, __LINE__, ret); + clientLength = 0; + length = 0; + return ret; + } + ret = GetBufferMessage(reply, buffer, length); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s:%{public}d get buffer failed! ret:%{public}d", __func__, + __LINE__, ret); + return ret; + } + PrintBuffer("UsbServerProxy::RequestWait buffer", buffer, length); + return ret; +} + +int32_t UsbServerProxy::RequestCancel(uint8_t busNum, uint8_t devAddr, uint8_t interfaceid, uint8_t endpointId) +{ + int32_t ret; + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + WRITE_PARCEL_WITH_RET(data, Uint8, interfaceid, E_WRITE_PARCEL_ERROR); + WRITE_PARCEL_WITH_RET(data, Uint8, endpointId, E_WRITE_PARCEL_ERROR); + ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_REQUEST_CANCEL), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s request cancel failed!", __func__); + } + + return ret; +} + +int32_t UsbServerProxy::Close(uint8_t busNum, uint8_t devAddr) +{ + sptr remote = Remote(); + RETURN_IF_WITH_RET(remote == nullptr, E_INNER_ERR); + MessageParcel data; + MessageParcel reply; + MessageOption option; + if (!data.WriteInterfaceToken(UsbServerProxy::GetDescriptor())) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s get descriptor failed!", __func__); + return ERR_ENOUGH_DATA; + } + + SetDeviceMessage(data, busNum, devAddr); + int32_t ret = remote->SendRequest(static_cast(IUsbSrv::USB_FUN_CLOSE_DEVICE), data, reply, option); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_INNERKIT, "UsbServerProxy::%{public}s queue failed!", __func__); + return ret; + } + + return ERR_OK; +} + +} // namespace USB +} // namespace OHOS diff --git a/services/zidl/src/usb_srv_stub.cpp b/services/zidl/src/usb_srv_stub.cpp new file mode 100644 index 00000000..b5ac468d --- /dev/null +++ b/services/zidl/src/usb_srv_stub.cpp @@ -0,0 +1,663 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "message_parcel.h" +#include "securec.h" +#include "usb_common.h" +#include "usb_server_proxy.h" +#include "usb_server_stub.h" + +namespace OHOS { +namespace USB { + +const uint32_t MAX_REQUEST_BUFFER_SIZE = 1024; + +void PrintBuffer(const char *title, const uint8_t *buffer, uint32_t length) +{ + std::ostringstream oss; + if (title == NULL || buffer == nullptr || length == 0) { + return; + } + oss.str(""); + oss << title << " << BINARY DATA [" << length << "bytes] >> :"; + for (uint32_t i = 0; i < length; ++i) { + oss << " " << std::hex << (int)buffer[i]; + } + oss << " --> " << buffer << std::endl; + USB_HILOGD(MODULE_USB_SERVICE, "%{public}s", oss.str().c_str()); +} + +int32_t UsbServerStub::GetDeviceMessage(MessageParcel &data, uint8_t &busNum, uint8_t &devAddr) +{ + if (!data.ReadUint8(busNum)) { + return ERR_INVALID_VALUE; + } + if (!data.ReadUint8(devAddr)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbServerStub::SetBufferMessage(MessageParcel &data, const void *buffer, uint32_t length) +{ + if (!data.WriteUint32(length)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && (!buffer)) { + return ERR_INVALID_VALUE; + } + if ((length > 0) && !data.WriteBuffer(buffer, length)) { + return ERR_INVALID_VALUE; + } + return ERR_OK; +} + +int32_t UsbServerStub::GetBufferMessage(MessageParcel &data, void *buffer, uint32_t &length) +{ + uint32_t dataSize; + if (!data.ReadUint32(dataSize)) { + return ERR_INVALID_VALUE; + } + if (dataSize == 0) { + length = 0; + return ERR_OK; + } + if (!buffer) { + length = 0; + return ERR_INVALID_VALUE; + } + const uint8_t *readData = data.ReadBuffer(dataSize); + if (readData == nullptr) { + return ERR_INVALID_VALUE; + } + memcpy_s(buffer, length, readData, dataSize); + length = dataSize < length ? dataSize : length; + return ERR_OK; +} +const FoundDevice *UsbServerStub::ParserOpenDeviceInfo(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + + return nullptr; +} + +int UsbServerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + USB_HILOGD(MODULE_USB_SERVICE, "UsbServerStub::OnRemoteRequest, cmd = %{public}d, flags = %{public}d", code, + option.GetFlags()); + std::u16string descriptor = UsbServerStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + USB_HILOGE(MODULE_SERVICE, "UsbServerStub::OnRemoteRequest failed, descriptor is not matched!"); + return E_GET_USB_SERVICE_FAILED; + } + + switch (code) { + case static_cast(IUsbSrv::USB_FUN_OPEN_DEVICE): { + return DoOpenDevice(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_HAS_RIGHT): { + return DoHasRight(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_RIGHT): { + return DoRequestRight(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_PORTS): { + return DoGetPorts(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_SUPPORTED_MODES): { + return DoGetSupportedModes(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_PORT_ROLE): { + return DoSetPortRole(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_CLAIM_INTERFACE): { + return DoClaimInterface(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_RELEASE_INTERFACE): { + return DoReleaseInterface(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_READ): { + return DoBulkTransferRead(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_BULK_TRANSFER_WRITE): { + return DoBulkTransferWrite(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_CONTROL_TRANSFER): { + return DoControlTransfer(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_DEVICES): { + return DoGetDevices(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_GET_CURRENT_FUNCTIONS): { + return DoGetCurrentFunctions(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_CURRENT_FUNCTIONS): { + return DoSetCurrentFunctions(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_FROM_STRING): { + return DoUsbFunctionsFromString(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_USB_FUNCTIONS_TO_STRING): { + return DoUsbFunctionsToString(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_CLOSE_DEVICE): { + return DoClose(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_QUEUE): { + return DoRequestQueue(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_WAIT): { + return DoRequestWait(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_INTERFACE): { + return DoSetInterface(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_SET_ACTIVE_CONFIG): { + return DoSetActiveConfig(data, reply, option); + } + case static_cast(IUsbSrv::USB_FUN_REQUEST_CANCEL): { + return DoRequestCancel(data, reply, option); + } + + /* + case static_cast(IUsbServer::USB_NOTICE_ADD_DEVICE): { + const OpenDeviceInfo *info = ParserOpenDeviceInfo(data, + reply, option); return NoticeAddDevice(info); + } + break; + */ + default: { + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + } + + return ERR_OK; +} + +int32_t UsbServerStub::DoGetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t funcs; + int32_t ret = GetCurrentFunctions(funcs); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Int32, funcs, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoSetCurrentFunctions(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t funcs; + data.ReadInt32(funcs); + bool ret = SetCurrentFunctions(funcs); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Bool, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoUsbFunctionsFromString(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::string funcs; + data.ReadString(funcs); + int32_t ret = UsbFunctionsFromString(funcs); + WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoUsbFunctionsToString(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t funcs; + data.ReadInt32(funcs); + std::string ret = UsbFunctionsToString(funcs); + WRITE_PARCEL_WITH_RET(reply, String, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoOpenDevice(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_READ_PARCEL_ERROR); + // int32_t fd; + int32_t ret = OpenDevice(busNum, devAddr); + if (ret != ERR_OK) { + return ret; + } + + // WRITE_PARCEL_WITH_RET(reply, Int32, fd, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoHasRight(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::string deviceName = ""; + READ_PARCEL_WITH_RET(data, String, deviceName, E_READ_PARCEL_ERROR); + int32_t ret = HasRight(deviceName); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoRequestRight(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::string deviceName = ""; + READ_PARCEL_WITH_RET(data, String, deviceName, E_READ_PARCEL_ERROR); + int32_t ret = RequestRight(deviceName); + if (ret != ERR_OK) { + return ret; + } + WRITE_PARCEL_WITH_RET(reply, Int32, ret, E_WRITE_PARCEL_ERROR); + return ERR_OK; +} + +int32_t UsbServerStub::DoGetPorts(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + std::vector ports; + int ret = GetPorts(ports); + USB_HILOGI(MODULE_SERVICE, "UsbServerStub::GetPorts ret %{public}d ", ret); + reply.WriteInt32(ret); + if (ret != ERR_OK) { + return ret; + } + unsigned int size = ports.size(); + USB_HILOGI(MODULE_SERVICE, "UsbServerStub::GetPorts size %{public}d ", size); + reply.WriteInt32(size); + for (unsigned int i = 0; i < size; ++i) { + WriteUsbPort(reply, ports[i]); + } + return ERR_OK; +} + +void UsbServerStub::WriteUsbPort(MessageParcel &reply, const UsbPort *port) +{ + reply.WriteInt32(port->id); + reply.WriteInt32(port->supportedModes); + reply.WriteInt32(port->usbPortStatus->currentMode); + reply.WriteInt32(port->usbPortStatus->currentPowerRole); + reply.WriteInt32(port->usbPortStatus->currentDataRole); + USB_HILOGI(MODULE_SERVICE, "UsbServerStub::GetPorts supportedModes %{public}d ", port->supportedModes); + return; +} + +int32_t UsbServerStub::DoGetSupportedModes(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t supportedModes = 0; + int32_t portId = 0; + portId = data.ReadInt32(); + int32_t ret = GetSupportedModes(portId, supportedModes); + if (ret != ERR_OK) { + return ret; + } + reply.WriteInt32(ret); + reply.WriteInt32(supportedModes); + return ERR_OK; +} + +int32_t UsbServerStub::DoSetPortRole(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t portId = 0; + int32_t powerRole = 0; + int32_t dataRole = 0; + portId = data.ReadInt32(); + powerRole = data.ReadInt32(); + dataRole = data.ReadInt32(); + int32_t ret = SetPortRole(portId, powerRole, dataRole); + if (ret != ERR_OK) { + return ret; + } + reply.WriteInt32(ret); + return ERR_OK; +} + +int32_t UsbServerStub::DoClaimInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t interface; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_READ_PARCEL_ERROR); + return ClaimInterface(busNum, devAddr, interface); +} +int32_t UsbServerStub::DoReleaseInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t interface; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_READ_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_READ_PARCEL_ERROR); + return ReleaseInterface(busNum, devAddr, interface); +} + +int32_t UsbServerStub::DoBulkTransferRead(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, interface, endpoint; + int32_t timeout = 0; + uint32_t length; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + uint8_t *buffer = new uint8_t[length]; + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + int32_t ret = BulkTransferRead(busNum, devAddr, interface, endpoint, buffer, length, timeout); + if (ret != ERR_OK) { + delete[] buffer; + return ret; + } + SetBufferMessage(reply, buffer, length); + USB_HILOGW(MODULE_USBD, "%{public}s Set buffer message. length = %{public}d", __func__, length); + delete[] buffer; + return ERR_OK; +} + +int32_t UsbServerStub::DoBulkTransferWrite(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, interface, endpoint; + int32_t timeout = 0; + uint32_t length = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interface, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + const uint8_t *buffer = data.ReadBuffer(length); + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + PrintBuffer("UsbServerStub::DoBulkTransferWrite", (const uint8_t *)buffer, length); + int32_t ret = BulkTransferWrite(busNum, devAddr, interface, endpoint, buffer, length, timeout); + return ret; +} + +int32_t UsbServerStub::DoControlTransfer(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + int32_t requestType, request, value, index, timeout; + uint32_t length; + uint8_t *buffer = nullptr; + + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, requestType, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, request, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, value, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, index, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + + buffer = new uint8_t[length]; + if (buffer == nullptr) { + return ERR_NO_MEMORY; + } + // 写数据 + bool bWrite = ((requestType & USB_ENDPOINT_DIR_MASK) == USB_ENDPOINT_DIR_OUT); + if (bWrite) { + const uint8_t *dataBuffer = data.ReadBuffer(length); + memcpy_s(buffer, length, dataBuffer, length); + } + int32_t ret = ControlTransfer(busNum, devAddr, requestType, request, value, index, buffer, length, timeout); + if (ret != ERR_OK) { + delete[] buffer; + return ret; + } + // 读数据 + if (!bWrite && buffer != nullptr) { + SetBufferMessage(reply, buffer, length); + USB_HILOGW(MODULE_USBD, "%{public}s Set buffer message. length = %{public}d", __func__, length); + PrintBuffer("UsbServerStub::DoControlTransfer", buffer, length); + } + + delete[] buffer; + return ERR_OK; +} + +int32_t UsbServerStub::DoSetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, config = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, config, E_WRITE_PARCEL_ERROR); + return SetActiveConfig(busNum, devAddr, config); +} + +int32_t UsbServerStub::DoGetActiveConfig(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, config = 0; + int32_t ret; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + ret = GetActiveConfig(busNum, devAddr, config); + if (ret == ERR_OK) { + reply.WriteUint8(config); + } + return ret; +} + +int32_t UsbServerStub::DoSetInterface(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, interfaceId, altIndex = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interfaceId, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, altIndex, E_WRITE_PARCEL_ERROR); + return SetInterface(busNum, devAddr, interfaceId, altIndex); +} + +int32_t UsbServerStub::DoGetRawDescriptor(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t ret = ERR_OK; + uint8_t busNum = 0, devAddr = 0; + uint32_t length = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + uint8_t *buffer = new uint8_t[length]; + ret = GetRawDescriptor(busNum, devAddr, buffer, length); + if (ret == ERR_OK) { + SetBufferMessage(reply, buffer, length); + } + delete[] buffer; + return ret; +} + +int32_t UsbServerStub::DoRequestQueue(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0, ifId = 0, endpoint; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, ifId, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpoint, E_WRITE_PARCEL_ERROR); + uint32_t clientLength = 0; + READ_PARCEL_WITH_RET(data, Uint32, clientLength, E_WRITE_PARCEL_ERROR); + const uint8_t *clientObj = data.ReadBuffer(clientLength); + uint32_t length; + READ_PARCEL_WITH_RET(data, Uint32, length, E_WRITE_PARCEL_ERROR); + const uint8_t *buffer = data.ReadBuffer(length); + // PrintBuffer("UsbServerStub::DoRequestQueue buffer", buffer, length); + return RequestQueue(busNum, devAddr, ifId, endpoint, (void *)clientObj, clientLength, (uint8_t *)buffer, length); +} + +int32_t UsbServerStub::DoRequestWait(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t *clientObj = nullptr, *buffer = nullptr; + uint32_t clientLength, length = 0; + int32_t timeout; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Int32, timeout, E_WRITE_PARCEL_ERROR); + clientLength = MAX_REQUEST_BUFFER_SIZE; + clientObj = new uint8_t[clientLength]; + length = MAX_REQUEST_BUFFER_SIZE; + buffer = new uint8_t[length]; + int32_t ret = RequestWait(busNum, devAddr, timeout, (void *)clientObj, clientLength, buffer, length); + if (ret != ERR_OK) { + USB_HILOGI(MODULE_USB_INNERKIT, "%{public}s:%{public}d failed ret:%{public}d", __func__, __LINE__, ret); + delete[] clientObj; + delete[] buffer; + return ret; + } + + // PrintBuffer("UsbServerStub::DoRequestWait buffer", buffer, length); + SetBufferMessage(reply, clientObj, clientLength); + SetBufferMessage(reply, buffer, length); + delete[] clientObj; + delete[] buffer; + return ERR_OK; +} + +int32_t UsbServerStub::DoRequestCancel(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + uint8_t interfaceId, endpointId; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, interfaceId, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, endpointId, E_WRITE_PARCEL_ERROR); + int32_t ret = RequestCancel(busNum, devAddr, interfaceId, endpointId); + return ret; +} + +int32_t UsbServerStub::DoClose(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + uint8_t busNum = 0, devAddr = 0; + READ_PARCEL_WITH_RET(data, Uint8, busNum, E_WRITE_PARCEL_ERROR); + READ_PARCEL_WITH_RET(data, Uint8, devAddr, E_WRITE_PARCEL_ERROR); + int32_t ret = Close(busNum, devAddr); + return ret; +} + +int32_t UsbServerStub::DoGetDevices(MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + int32_t ret = -1; + std::vector deviceList; + ret = GetDevices(deviceList); + if (ret != ERR_OK) { + USB_HILOGE(MODULE_SERVICE, "%{public}s: failed ret = %{public}d", __func__, ret); + return ret; + } + USB_HILOGE(MODULE_SERVICE, "%{public}s: list size = %{public}d", __func__, deviceList.size()); + // ret = SetDevicesMapToMessageParcel(devices, data); + ret = SetDeviceListMessageParcel(deviceList, reply); + return ret; +} + +int32_t UsbServerStub::SetDeviceListMessageParcel(std::vector &deviceList, MessageParcel &data) +{ + int32_t deviceCount = (int32_t)deviceList.size(); + data.WriteInt32(deviceCount); + for (int32_t i = 0; i < deviceCount; ++i) { + UsbDevice &devInfo = deviceList[i]; + SetDeviceMessageParcel(devInfo, data); + } + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceMessageParcel(UsbDevice &devInfo, MessageParcel &data) +{ + data.WriteInt32(devInfo.GetBusNum()); + data.WriteInt32(devInfo.GetDevAddr()); + + data.WriteInt32(devInfo.GetVendorId()); + data.WriteInt32(devInfo.GetProductId()); + data.WriteInt32(devInfo.GetClass()); + data.WriteInt32(devInfo.GetSubclass()); + data.WriteInt32(devInfo.GetProtocol()); + data.WriteUint8(devInfo.GetiManufacturer()); + data.WriteUint8(devInfo.GetiProduct()); + data.WriteUint8(devInfo.GetiSerialNumber()); + data.WriteUint8(devInfo.GetbMaxPacketSize0()); + data.WriteUint16(devInfo.GetbcdUSB()); + data.WriteUint16(devInfo.GetbcdDevice()); + data.WriteString(devInfo.GetName()); + data.WriteString(devInfo.GetManufacturerName()); + data.WriteString(devInfo.GetProductName()); + data.WriteString(devInfo.GetVersion()); + data.WriteString(devInfo.GetmSerial()); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:%{public}d devName:%{public}s Bus:%{public}d dev:%{public}d ", __func__, + __LINE__, devInfo.GetName().c_str(), devInfo.GetBusNum(), devInfo.GetDevAddr()); + USB_HILOGE(MODULE_USB_INNERKIT, "%{public}s:%{public}d devInfo:%{public}s", __func__, __LINE__, + devInfo.ToString().c_str()); + data.WriteInt32(devInfo.GetConfigCount()); + SetDeviceConfigsMessageParcel(devInfo.GetConfigs(), data); + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceConfigsMessageParcel(std::vector &configs, MessageParcel &data) +{ + for (auto it = configs.begin(); it != configs.end(); ++it) { + USBConfig config = *it; + data.WriteInt32(config.GetId()); + data.WriteInt32(config.GetAttributes()); + data.WriteInt32(config.GetMaxPower()); + + data.WriteUint8(config.GetiConfiguration()); + data.WriteString(config.GetName()); + + data.WriteInt32(config.GetInterfaceCount()); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, config.ToString().c_str()); + SetDeviceInterfacesMessageParcel(config.GetInterfaces(), data); + } + + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceInterfacesMessageParcel(std::vector &interfaces, MessageParcel &data) +{ + for (auto it = interfaces.begin(); it != interfaces.end(); ++it) { + UsbInterface interface = *it; + data.WriteInt32(interface.GetId()); + data.WriteInt32(interface.GetClass()); + data.WriteInt32(interface.GetSubClass()); + data.WriteInt32(interface.GetAlternateSetting()); + data.WriteInt32(interface.GetProtocol()); + + data.WriteUint8(interface.GetiInterface()); + data.WriteString(interface.GetName()); + + data.WriteInt32(interface.GetEndpointCount()); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, interface.ToString().c_str()); + SetDeviceEndpointsMessageParcel(interface.GetEndpoints(), data); + } + return ERR_OK; +} + +int32_t UsbServerStub::SetDeviceEndpointsMessageParcel(std::vector &eps, MessageParcel &data) +{ + for (auto it = eps.begin(); it != eps.end(); ++it) { + USBEndpoint ep = *it; + data.WriteInt32(ep.GetAddress()); + data.WriteInt32(ep.GetAttributes()); + data.WriteInt32(ep.GetInterval()); + data.WriteInt32(ep.GetMaxPacketSize()); + USB_HILOGI(MODULE_USB_SERVICE, "%{public}s devInfo=%{public}s", __func__, ep.ToString().c_str()); + } + return ERR_OK; +} + +} // namespace USB +} // namespace OHOS diff --git a/test/native/BUILD.gn b/test/native/BUILD.gn new file mode 100644 index 00000000..7284925b --- /dev/null +++ b/test/native/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("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +group("usbmgr_native_test") { + testonly = true + deps = [ "unittest:unittest" ] +} diff --git a/test/native/unittest/BUILD.gn b/test/native/unittest/BUILD.gn new file mode 100644 index 00000000..fe13f76b --- /dev/null +++ b/test/native/unittest/BUILD.gn @@ -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. + +import("//base/usb/usb_manager/usbmgr.gni") +import("//build/test.gni") + +module_output_path = "${usb_manager_native_part_name}/usb_manager_native" + +############################################################################### +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "include", + "//utils/system/safwk/native/include", + "${usb_manager_path}/hdi/api/include", + "${usb_manager_path}/hdi/client/include", + ] +} + +deps_ex = [ + "aafwk_standard:base", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:libeventhandler", + "ipc:ipc_core", + "hiviewdfx_hilog_native:libhilog", + "safwk:system_ability_fwk", + "samgr_L2:samgr_proxy", +] + + +##############################unittest########################################## +ohos_unittest("test_usb_mgr_service") { + module_out_path = module_output_path + + sources = [ "src/usb_service_test.cpp" ] + + configs = [ + "${utils_path}:utils_config", + ":module_private_config", + ] + + deps = [ + "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", + "//base/usb/usb_manager/services:usbservice", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = deps_ex +} + +group("unittest") { + testonly = true + deps = [ + ":test_usb_mgr_service", + ] +} + + + diff --git a/test/native/unittest/include/usb_service_test.h b/test/native/unittest/include/usb_service_test.h new file mode 100644 index 00000000..9055be77 --- /dev/null +++ b/test/native/unittest/include/usb_service_test.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 USB_SERVICE_TEST_H +#define USB_SERVICE_TEST_H + +#include +#include + +class UsbServiceTest : public testing::Test { +public: + void HasRight(std::string deviceName) {} +}; +#endif // USB_SERVICE_TEST_H diff --git a/test/native/unittest/src/usb_service_test.cpp b/test/native/unittest/src/usb_service_test.cpp new file mode 100644 index 00000000..a00375a6 --- /dev/null +++ b/test/native/unittest/src/usb_service_test.cpp @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "usb_service_test.h" + +#include +#include + +#include "usb_service.h" + +using namespace testing::ext; +using namespace OHOS; +using namespace OHOS::USB; +using namespace std; + +/** + * @tc.name: DisplayMgrService01 + * @tc.desc: Test DisplayMgrService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService01, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService01 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; +} + +/** + * @tc.name: UsbService02 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService02, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService02 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() == 0) << "UsbService02 Devices count is 0"; + + cout << "Please insert a USB device\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs1 = proxy_->GetDevices(); + EXPECT_TRUE(devs1.size() != 0) << "UsbService02 Devices count is not 0"; + + cout << "Please unplug the USB device\nPress any key to continue..." << endl; + // system("pause"); + // int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs2 = proxy_->GetDevices(); + EXPECT_TRUE(devs2.size() == 0) << "UsbService02 Devices count is 0"; +} + +/** + * @tc.name: UsbService03 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService03, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService03 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a normal USB device\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService03 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasMidi() == false) << "HasMidi is false"; + EXPECT_TRUE(iter->second->GetHasAudioCapture() == false) << "HasAudioCapture is false"; + EXPECT_TRUE(iter->second->GetHasAudioPlayback() == false) << "HasAudioPlayback is false"; + EXPECT_TRUE(iter->second->GetHasVideoCapture() == false) << "HasVideoCapture is false"; + EXPECT_TRUE(iter->second->GetHasVideoPlayback() == false) << "HasVideoPlayBack is false"; +} + +/** + * @tc.name: UsbService04 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService04, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService04 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a Midi USB device\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService04 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasMidi() == true) << "HasMidi is true"; +} + +/** + * @tc.name: UsbService05 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService05, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService05 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with no AudioPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService05 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasAudioCapture() == true) << "HasAudioCapture is true"; + EXPECT_TRUE(iter->second->GetHasAudioPlayback() == false) << "HasAudioPlayback is false"; +} + +/** + * @tc.name: UsbService06 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService06, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService06 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with AudioPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService06 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasAudioCapture() == true) << "HasAudioCapture is true"; + EXPECT_TRUE(iter->second->GetHasAudioPlayback() == true) << "HasAudioPlayback is true"; +} + +/** + * @tc.name: UsbService07 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService07, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService07 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with no VideoPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService07 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasVideoCapture() == true) << "HasVideoCapture is true"; + EXPECT_TRUE(iter->second->GetHasVideoPlayback() == false) << "HasVideoPlayBack is false"; +} + +/** + * @tc.name: UsbService08 + * @tc.desc: Test UsbService service ready. + * @tc.type: FUNC + */ +HWTEST_F(UsbServiceTest, UsbService08, TestSize.Level1) +{ + sptr sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_TRUE(sam != nullptr) << "UsbService08 fail to get GetSystemAbilityManager"; + sptr remoteObject_ = sam->CheckSystemAbility(USB_MANAGER_USB_SERVICE_ID); + EXPECT_TRUE(remoteObject_ != nullptr) << "GetSystemAbility failed."; + + sptr proxy_ = iface_cast(remoteObject_); + cout << "Please insert a USB device with VideoPlayback function\nPress any key to continue..." << endl; + // system("pause"); + int c; + while ((c = getchar()) != '\n' && c != EOF) + ; + std::map devs = proxy_->GetDevices(); + EXPECT_TRUE(devs.size() != 0) << "UsbService08 Devices count is not 0"; + std::map::iterator iter = devs.begin(); + EXPECT_TRUE(iter->second->GetHasVideoCapture() == true) << "HasVideoCapture is true"; + EXPECT_TRUE(iter->second->GetHasVideoPlayback() == true) << "HasVideoPlayBack is true"; +} diff --git a/usbmgr.gni b/usbmgr.gni new file mode 100644 index 00000000..b00cad92 --- /dev/null +++ b/usbmgr.gni @@ -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. + +import("//build/ohos.gni") + +usb_manager_path = "//base/usb/usb_manager" +usb_manager_native_part_name = "usb_manager_native" +utils_path = "${usb_manager_path}/utils" diff --git a/utils/BUILD.gn b/utils/BUILD.gn new file mode 100644 index 00000000..2d3f04e6 --- /dev/null +++ b/utils/BUILD.gn @@ -0,0 +1,21 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/usb/usb_manager/usbmgr.gni") + +config("utils_config") { + include_dirs = [ + "native/include", + "//utils/native/base/include", + ] +} diff --git a/utils/native/include/delayed_sp_singleton.h b/utils/native/include/delayed_sp_singleton.h new file mode 100644 index 00000000..7946c41b --- /dev/null +++ b/utils/native/include/delayed_sp_singleton.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef DELAYED_SP_SINGLETON_H +#define DELAYED_SP_SINGLETON_H + +#include +#include +#include +#include "nocopyable.h" + +namespace OHOS { +namespace USB { +template class DelayedSpSingleton : public NoCopyable { +public: + static sptr GetInstance(); + static void DestroyInstance(); + +private: + static sptr instance_; + static std::mutex mutex_; +}; + +template sptr DelayedSpSingleton::instance_ = nullptr; + +template std::mutex DelayedSpSingleton::mutex_; + +template sptr DelayedSpSingleton::GetInstance() +{ + if (!instance_) { + std::lock_guard lock(mutex_); + if (instance_ == nullptr) { + instance_ = new T(); + } + } + + return instance_; +} + +template void DelayedSpSingleton::DestroyInstance() +{ + std::lock_guard lock(mutex_); + if (instance_) { + instance_.clear(); + instance_ = nullptr; + } +} +} // namespace USB +} // namespace OHOS +#endif // DELAYED_SP_SINGLETON_H diff --git a/utils/native/include/hilog_wrapper.h b/utils/native/include/hilog_wrapper.h new file mode 100644 index 00000000..aca7bea4 --- /dev/null +++ b/utils/native/include/hilog_wrapper.h @@ -0,0 +1,108 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HILOG_WRAPPER_H +#define HILOG_WRAPPER_H + +#define CONFIG_HILOG +#ifdef CONFIG_HILOG +#include "hilog/log.h" +namespace OHOS { +namespace USB { +#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) +#define __FORMATED(fmt, ...) "[%{public}s] %{public}s# " fmt, __FILENAME__, __FUNCTION__, ##__VA_ARGS__ + +#ifdef USB_HILOGF +#undef USB_HILOGF +#endif + +#ifdef USB_HILOGE +#undef USB_HILOGE +#endif + +#ifdef USB_HILOGW +#undef USB_HILOGW +#endif + +#ifdef USB_HILOGI +#undef USB_HILOGI +#endif + +#ifdef USB_HILOGD +#undef USB_HILOGD +#endif + +// param of log interface, such as USB_HILOGF. +enum UsbMgrSubModule { + MODULE_INNERKIT = 0, + MODULE_SERVICE, + MODULE_JAVAKIT, // java kit used, define to avoid repeat used domain + MODULE_JNI, + MODULE_USB_INNERKIT, // below used by usb service + MODULE_USB_SERVICE, + MODULE_USBD, + MODULE_COMMON, + MODULE_JS_NAPI, + USBMGR_MODULE_BUTT, +}; + +// 0xD002900: subsystem:Usb module:Usb, reserved 8 bit. +static constexpr unsigned int BASE_USB_DOMAIN_ID = 0xD002900; + +enum UsbMgrDomainId { + USBMGR_INNERKIT_DOMAIN = BASE_USB_DOMAIN_ID + MODULE_INNERKIT, + USBMGR_SERVICE_DOMAIN, + USBMGR_JAVAKIT_DOMAIN, // 0xD002902 + USB_INNERKIT_DOMAIN, + USB_SERVICE_DOMAIN, + USBD_DOMAIN, + COMMON_DOMAIN, + USB_JS_NAPI, + USB_BUTT, +}; + +static constexpr OHOS::HiviewDFX::HiLogLabel USB_MGR_LABEL[USBMGR_MODULE_BUTT] = { + {LOG_CORE, USBMGR_INNERKIT_DOMAIN, "UsbMgrClient"}, + {LOG_CORE, USBMGR_SERVICE_DOMAIN, "UsbMgrService"}, + {LOG_CORE, USBMGR_JAVAKIT_DOMAIN, "UsbMgrJavaService"}, + {LOG_CORE, USBMGR_INNERKIT_DOMAIN, "UsbMgrJni"}, + {LOG_CORE, USB_INNERKIT_DOMAIN, "UsbSrvClient"}, + {LOG_CORE, USB_SERVICE_DOMAIN, "UsbService"}, + {LOG_CORE, USBD_DOMAIN, "Usbd"}, + {LOG_CORE, COMMON_DOMAIN, "UsbMgrCommon"}, + {LOG_CORE, USB_JS_NAPI, "UsbMgrJSNAPI"}, +}; + +// In order to improve performance, do not check the module range, module should less than USBMGR_MODULE_BUTT. +#define USB_HILOGF(module, ...) (void)OHOS::HiviewDFX::HiLog::Fatal(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGE(module, ...) (void)OHOS::HiviewDFX::HiLog::Error(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGW(module, ...) (void)OHOS::HiviewDFX::HiLog::Warn(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGI(module, ...) (void)OHOS::HiviewDFX::HiLog::Info(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) +#define USB_HILOGD(module, ...) (void)OHOS::HiviewDFX::HiLog::Debug(USB_MGR_LABEL[module], __FORMATED(__VA_ARGS__)) + +} // namespace USB +} // namespace OHOS + +#else + +#define USB_HILOGF(...) +#define USB_HILOGE(...) +#define USB_HILOGW(...) +#define USB_HILOGI(...) +#define USB_HILOGD(...) + +#endif // CONFIG_HILOG + +#endif // HILOG_WRAPPER_H diff --git a/utils/native/include/usb_common.h b/utils/native/include/usb_common.h new file mode 100644 index 00000000..8e935533 --- /dev/null +++ b/utils/native/include/usb_common.h @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef USB_COMMON_H +#define USB_COMMON_H + +#include +#include + +#include "hilog_wrapper.h" +#include "usb_errors.h" + +namespace OHOS { +namespace USB { +/** + * Invalid usb int value + */ +constexpr int32_t INVALID_USB_INT_VALUE = -1; + +/** + * Bitmask used for extracting the USBEndpoint type from it's address + */ +constexpr int32_t USB_ENDPOINT_XFERTYPE_MASK = 0x03; + +/** + * Control USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_CONTROL = 0; + +/** + * Isochronous USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_ISOC = 1; + +/** + * Bulk USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_BULK = 2; + +/** + * Interrupt USBEndpoint type + */ +constexpr int32_t USB_ENDPOINT_XFER_INT = 3; + +/** + * Bitmask used for extracting the USBEndpoint number from it's address + */ +constexpr int32_t USB_ENDPOINT_NUMBER_MASK = 0x0f; + +/** + * Bitmask used for extracting the USBEndpoint direction from it's address + */ +constexpr int32_t USB_ENDPOINT_DIR_MASK = 0x80; + +/** + * Used to signify direction of data for USBEndpoint is OUT, host to device + */ +constexpr int32_t USB_ENDPOINT_DIR_OUT = 0; + +/** + * Used to signify direction of data for USBEndpoint is IN, device to host + */ +constexpr int32_t USB_ENDPOINT_DIR_IN = 0x80; + +/** + * Bitmask for self power in the USBConfig + */ +constexpr int32_t USB_CFG_SELF_POWERED = 0x80; + +/** + * Bitmask for remote wakeup in the USBConfig + */ +constexpr int32_t USB_CFG_REMOTE_WAKEUP = 0x20; + +#define INVALID_STRING_VALUE ("") +#define RETURN_IF_WITH_RET(cond, retval) \ + if (cond) { \ + return (retval); \ + } +#define RETURN_IF(cond) \ + if (cond) { \ + return; \ + } +#define RETURN_IF_WITH_LOG(cond, loginfo) \ + do { \ + if (cond) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s " #loginfo " ", __func__); \ + return; \ + } \ + } while (0) + +#define READ_PARCEL_NO_RET(parcel, type, out) \ + do { \ + if (!(parcel).Read##type(out)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s read " #out " failed", __func__); \ + return; \ + } \ + } while (0) + +#define WRITE_PARCEL_NO_RET(parcel, type, data) \ + do { \ + if (!(parcel).Write##type(data)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s write " #data " failed", __func__); \ + return; \ + } \ + } while (0) + +#define READ_PARCEL_WITH_RET(parcel, type, out, retval) \ + do { \ + if (!(parcel).Read##type(out)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s read " #out " failed", __func__); \ + return (retval); \ + } \ + } while (0) + +#define WRITE_PARCEL_WITH_RET(parcel, type, data, retval) \ + do { \ + if (!(parcel).Write##type(data)) { \ + USB_HILOGE(MODULE_COMMON, "%{public}s write " #data " failed", __func__); \ + return (retval); \ + } \ + } while (0) + +template constexpr auto ToUnderlying(E e) noexcept +{ + return static_cast>(e); +} +} // namespace USB +} // namespace OHOS + +#endif // USB_COMMON_H diff --git a/utils/native/include/usb_errors.h b/utils/native/include/usb_errors.h new file mode 100644 index 00000000..84d4a7d6 --- /dev/null +++ b/utils/native/include/usb_errors.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 USB_ERRORS_H +#define USB_ERRORS_H + +#include + +namespace OHOS { +namespace USB { +enum { + /** + * Module type: Usb Manager Service + */ + USB_MODULE_TYPE_SERVICE = 0, + /** + * Module type: Usb Manager Kit + */ + USB_MODULE_TYPE_KIT = 1 +}; + +// offset of usbmgr error, only be used in this file. +constexpr ErrCode USBFWK_SERVICE_ERR_OFFSET = ErrCodeOffset(SUBSYS_USB, USB_MODULE_TYPE_SERVICE); + +enum { + E_WRITE_PARCEL_ERROR = USBFWK_SERVICE_ERR_OFFSET, + E_READ_PARCEL_ERROR, + E_GET_SYSTEM_ABILITY_MANAGER_FAILED, + E_GET_USB_SERVICE_FAILED, + E_ADD_DEATH_RECIPIENT_FAILED, + E_INNER_ERR +}; +} // namespace USB +} // namespace OHOS + +#endif // USB_ERRORS_H -- Gitee