From 8751a94514884603b51116b1605120083643272c Mon Sep 17 00:00:00 2001 From: NickWang007 Date: Tue, 17 Jun 2025 20:30:59 +0800 Subject: [PATCH] =?UTF-8?q?IDL=E5=8C=96=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: NickWang007 Change-Id: I1e17e7e8cdf016accf163d08d0fcbf579092afdf Signed-off-by: NickWang007 --- bundle.json | 6 +- frameworks/ets/taihe/usb_manager/BUILD.gn | 218 +-- .../idl/ohos.usbManager.serial.taihe | 153 ++ .../usb_manager/idl/ohos.usbManager.taihe | 386 +++++ .../idl/ohos.usbManager.usbManager.taihe | 74 - .../taihe/usb_manager/src/ani_constructor.cpp | 64 +- .../usb_manager/src/ohos.usbManager.impl.cpp | 1282 +++++++++++++++++ .../src/ohos.usbManager.serial.impl.cpp | 488 +++++++ .../src/ohos.usbManager.usbManager.impl.cpp | 155 -- .../usb_manager/test/unittest/BUILD copy.gn | 41 + .../taihe/usb_manager/test/unittest/BUILD.gn | 46 + .../unittest/stats_ani_constructor_test.cpp | 126 ++ .../stats_serial_taihe_native_test.cpp | 209 +++ .../test/unittest/stats_taihe_native_test.cpp | 246 ++++ .../test/xts/SerialBaseTest.test.ets | 698 +++++++++ .../usb_manager/test/xts/SerialTest.test.ets | 777 ++++++++++ .../test/xts/usb_accessory_test.ets | 196 +++ .../usb_manager/test/xts/usb_base_test.ets | 547 +++++++ .../test/xts/usb_resetDevice_test.ets | 153 ++ .../test/xts/usb_transfer_test.ets | 345 +++++ 20 files changed, 5857 insertions(+), 353 deletions(-) create mode 100644 frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.serial.taihe create mode 100644 frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.taihe delete mode 100644 frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.usbManager.taihe create mode 100644 frameworks/ets/taihe/usb_manager/src/ohos.usbManager.impl.cpp create mode 100644 frameworks/ets/taihe/usb_manager/src/ohos.usbManager.serial.impl.cpp delete mode 100644 frameworks/ets/taihe/usb_manager/src/ohos.usbManager.usbManager.impl.cpp create mode 100644 frameworks/ets/taihe/usb_manager/test/unittest/BUILD copy.gn create mode 100644 frameworks/ets/taihe/usb_manager/test/unittest/BUILD.gn create mode 100644 frameworks/ets/taihe/usb_manager/test/unittest/stats_ani_constructor_test.cpp create mode 100644 frameworks/ets/taihe/usb_manager/test/unittest/stats_serial_taihe_native_test.cpp create mode 100644 frameworks/ets/taihe/usb_manager/test/unittest/stats_taihe_native_test.cpp create mode 100644 frameworks/ets/taihe/usb_manager/test/xts/SerialBaseTest.test.ets create mode 100644 frameworks/ets/taihe/usb_manager/test/xts/SerialTest.test.ets create mode 100644 frameworks/ets/taihe/usb_manager/test/xts/usb_accessory_test.ets create mode 100644 frameworks/ets/taihe/usb_manager/test/xts/usb_base_test.ets create mode 100644 frameworks/ets/taihe/usb_manager/test/xts/usb_resetDevice_test.ets create mode 100644 frameworks/ets/taihe/usb_manager/test/xts/usb_transfer_test.ets diff --git a/bundle.json b/bundle.json index b2504333..727de7db 100644 --- a/bundle.json +++ b/bundle.json @@ -58,7 +58,8 @@ "cJSON", "bounds_checking_function", "hitrace", - "runtime_core" + "runtime_core", + "eventhandler" ] }, "build": { @@ -93,7 +94,8 @@ "name": "//base/usb/usb_manager/frameworks/ets/taihe/usb_manager:copy_usbManager" }], "test": [ - "//base/usb/usb_manager/test/native:usb_unittest_test" + "//base/usb/usb_manager/test/native:usb_unittest_test", + "//base/usb/usb_manager/frameworks/ets/taihe/usb_manager/test/unittest:stats_taihe_native_test" ] } } diff --git a/frameworks/ets/taihe/usb_manager/BUILD.gn b/frameworks/ets/taihe/usb_manager/BUILD.gn index a9358c34..9eab86e7 100644 --- a/frameworks/ets/taihe/usb_manager/BUILD.gn +++ b/frameworks/ets/taihe/usb_manager/BUILD.gn @@ -1,93 +1,125 @@ -# Copyright (c) 2025 Huawei Device Co., Ltd. -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT 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/config/components/ets_frontend/ets2abc_config.gni") -import("//build/ohos.gni") -import("//build/ohos/taihe_idl/taihe.gni") - -copy_taihe_idl("copy_usbManager") { - sources = [ "idl/ohos.usbManager.usbManager.taihe" ] -} - -subsystem_name = "usb" -part_name = "usb_manager" -taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" - -ohos_taihe("run_taihe") { - taihe_generated_file_path = "$taihe_generated_file_path" - deps = [ ":copy_usbManager" ] - outputs = [ - "$taihe_generated_file_path/src/ohos.usbManager.usbManager.ani.cpp", - "$taihe_generated_file_path/src/ohos.usbManager.usbManager.abi.c", - ] -} - -taihe_shared_library("usb_manager_taihe_native") { - sanitize = { - cfi = true - cfi_cross_dso = true - debug = false - } - taihe_generated_file_path = "$taihe_generated_file_path" - part_name = "$part_name" - subsystem_name = "$subsystem_name" - sources = get_target_outputs(":run_taihe") - sources += [ - "src/ani_constructor.cpp", - "src/ohos.usbManager.usbManager.impl.cpp", - ] - deps = [ - ":run_taihe", - "${usb_manager_path}/interfaces/innerkits:usbsrv_client", - ] - - external_deps = [ - "bounds_checking_function:libsec_shared", - "hilog:libhilog" - ] - - defines = [] - if (usb_manager_feature_host) { - defines += [ "USB_MANAGER_FEATURE_HOST" ] - } - if (usb_manager_feature_device) { - defines += [ "USB_MANAGER_FEATURE_DEVICE" ] - } - if (usb_manager_feature_port) { - defines += [ "USB_MANAGER_FEATURE_PORT" ] - } -} - -generate_static_abc("usb_manager_abc") { - base_url = "$taihe_generated_file_path" - files = [ "$taihe_generated_file_path/@ohos.usbManager.ets" ] - is_boot_abc = "True" - device_dst_file = "/system/framework/usb_manager_abc.abc" - dependencies = [ ":run_taihe" ] -} - -ohos_prebuilt_etc("usb_manager_etc") { - source = "$target_out_dir/usb_manager_abc.abc" - module_install_dir = "framework" - part_name = "$part_name" - subsystem_name = "$subsystem_name" - deps = [ ":usb_manager_abc" ] -} - -group("usbManager_taihe") { - deps = [ - ":usb_manager_etc", - ":usb_manager_taihe_native", - ] -} +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT 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/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") +import("//base/usb/usb_manager/usbmgr.gni") + +copy_taihe_idl("copy_usbManager") { + sources = [ + "idl/ohos.usbManager.taihe", + "idl/ohos.usbManager.serial.taihe" + ] +} + +subsystem_name = "usb" +part_name = "usb_manager" +taihe_generated_file_path = "$taihe_file_path/out/$subsystem_name/$part_name" + +ohos_taihe("run_taihe") { + taihe_generated_file_path = "$taihe_generated_file_path" + deps = [ ":copy_usbManager" ] + outputs = [ + "$taihe_generated_file_path/src/ohos.usbManager.ani.cpp", + "$taihe_generated_file_path/src/ohos.usbManager.abi.c", + "$taihe_generated_file_path/src/ohos.usbManager.serial.ani.cpp", + "$taihe_generated_file_path/src/ohos.usbManager.serial.abi.c" + ] +} + +taihe_shared_library("usb_manager_taihe_native") { + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + + taihe_generated_file_path = "$taihe_generated_file_path" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + sources = get_target_outputs(":run_taihe") + + sources += [ + "src/ani_constructor.cpp", + "src/ohos.usbManager.impl.cpp", + "src/ohos.usbManager.serial.impl.cpp" + ] + + deps = [ + ":run_taihe", + "${usb_manager_path}/interfaces/innerkits:usbsrv_client" + ] + + defines = [] + if (usb_manager_feature_host) { + defines += [ "USB_MANAGER_FEATURE_HOST" ] + } + if (usb_manager_feature_device) { + defines += [ "USB_MANAGER_FEATURE_DEVICE" ] + } + if (usb_manager_feature_port) { + defines += [ "USB_MANAGER_FEATURE_PORT" ] + } + + public_external_deps = [ "cJSON:cjson" ] + external_deps = [ + "bounds_checking_function:libsec_shared", + "c_utils:utils", + "drivers_interface_usb:usb_idl_headers_1.2", + "hilog:libhilog", + "hitrace:hitrace_meter", + "ipc:ipc_single", + "eventhandler:libeventhandler", + ] + +} + +generate_static_abc("usb_manager_abc") { + base_url = "$taihe_generated_file_path" + files = [ "$taihe_generated_file_path/@ohos.usbManager.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/usb_manager_abc.abc" + dependencies = [ ":run_taihe" ] +} + +generate_static_abc("usbmanager_serial_abc") { + base_url = "$taihe_generated_file_path" + files = ["$taihe_generated_file_path/@ohos.usbManager.serial.ets"] + is_boot_abc = "True" + device_dst_file = "/system/framework/usbmanager_serial_abc.abc" + dependencies = [":run_taihe"] +} + +ohos_prebuilt_etc("usbmanager_etc") { + source = "$target_out_dir/usb_manager_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":usb_manager_abc" ] +} + +ohos_prebuilt_etc("usbmanager_serial_etc") { + source = "$target_out_dir/usbmanager_serial_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps=[":usbmanager_serial_abc"] +} + +group("usbManager_taihe") { + deps = [ + ":usbmanager_etc", + ":usb_manager_taihe_native", + ":usbmanager_serial_etc", + ] +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.serial.taihe b/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.serial.taihe new file mode 100644 index 00000000..1d546df3 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.serial.taihe @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@!namespace("@ohos.usbManager.serial", "serialManager") +@!sts_inject("""loadLibrary("usb_manager_taihe_native.z")""") + +function getPortList(): Array; + +function hasSerialRight(portId: f64): bool; + +@gen_promise("requestSerialRight") +function requestSerialRightSync(portId: f64): bool; + +function addSerialRight(tokenId: f64, portId: f64): void; + +function cancelSerialRight(portId: f64): void; + +function open(portId: f64): void; + +function close(portId: f64): void; + +function getAttribute(portId: f64): SerialAttribute; + +function setAttribute(portId: f64, attribute: SerialAttribute): void; + +@gen_promise("read") +function readSync(portId: f64, buffer: @typedarray Array, timeout: Optional): f64; + +@gen_promise("write") +function writeSync(portId: f64, buffer: @typedarray Array, timeout: Optional): f64; + +struct SerialPort { + + portId: f64; + + deviceName: String; +} +struct SerialAttribute { + + baudRate: BaudRates; + + dataBits: Optional; + + parity: Optional; + + stopBits: Optional; +} +enum BaudRates : u32 { + + BAUDRATE_50 = 50, + + BAUDRATE_75 = 75, + + BAUDRATE_110 = 110, + + BAUDRATE_134 = 134, + + BAUDRATE_150 = 150, + + BAUDRATE_200 = 200, + + BAUDRATE_300 = 300, + + BAUDRATE_600 = 600, + + BAUDRATE_1200 = 1200, + + BAUDRATE_1800 = 1800, + + BAUDRATE_2400 = 2400, + + BAUDRATE_4800 = 4800, + + BAUDRATE_9600 = 9600, + + BAUDRATE_19200 = 19200, + + BAUDRATE_38400 = 38400, + + BAUDRATE_57600 = 57600, + + BAUDRATE_115200 = 115200, + + BAUDRATE_230400 = 230400, + + BAUDRATE_460800 = 460800, + + BAUDRATE_500000 = 500000, + + BAUDRATE_576000 = 576000, + + BAUDRATE_921600 = 921600, + + BAUDRATE_1000000 = 1000000, + + BAUDRATE_1152000 = 1152000, + + BAUDRATE_1500000 = 1500000, + + BAUDRATE_2000000 = 2000000, + + BAUDRATE_2500000 = 2500000, + + BAUDRATE_3000000 = 3000000, + + BAUDRATE_3500000 = 3500000, + + BAUDRATE_4000000 = 4000000 +} +enum DataBits : u8 { + + DATABIT_8 = 8, + + DATABIT_7 = 7, + + DATABIT_6 = 6, + + DATABIT_5 = 5, + + DATABIT_4 = 4 +} +enum Parity : u8 { + + PARITY_NONE = 0, + + PARITY_ODD = 1, + + PARITY_EVEN = 2, + + PARITY_MARK = 3, + + PARITY_SPACE = 4 +} +enum StopBits : u8 { + + STOPBIT_1 = 0, + + STOPBIT_1P5 = 1, + + STOPBIT_2 = 2 +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.taihe b/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.taihe new file mode 100644 index 00000000..afae717a --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.taihe @@ -0,0 +1,386 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@!sts_inject_into_module("import { AsyncCallback } from '@ohos.base';") + +@!namespace("@ohos.usbManager", "usbManager") +@!sts_inject(""" +static { loadLibrary("usb_manager_taihe_native.z") } +""") + +function getDevices(): Array; + +function connectDevice(device: USBDevice): USBDevicePipe; + +function hasRight(deviceName: String): bool; + +@gen_promise("requestRight") +function requestRightSync(deviceName: String): bool; + +function removeRight(deviceName: String): bool; + +function addDeviceAccessRight(tokenId: String, deviceName: String): bool; + +function getFunctionsFromString(funcs: String): f64; + +function getStringFromFunctions(funcs: FunctionType): String; + +@gen_promise("setDeviceFunctions") +function setDeviceFunctionsSync(funcs: FunctionType): void; + +function getDeviceFunctions(): FunctionType; + +function getPortList(): Array; + +function getPortSupportModes(portId: f64): PortModeType; + +@gen_promise("setPortRoleTypes") +function setPortRoleTypesSync(portId: f64, powerRole: PowerRoleType, dataRole: DataRoleType): void; + +function addAccessoryRight(tokenId: f64, accessory: USBAccessory): void; + +function claimInterface(pipe: USBDevicePipe, iface: USBInterface, force: Optional): f64; + +function releaseInterface(pipe: USBDevicePipe, iface: USBInterface): f64; + +function setConfiguration(pipe: USBDevicePipe, config: USBConfiguration): f64; + +function setInterface(pipe: USBDevicePipe, iface: USBInterface): f64; + +function getRawDescriptor(pipe: USBDevicePipe): @typedarray Array; + +function getFileDescriptor(pipe: USBDevicePipe): f64; + +@gen_promise("usbControlTransfer") +function usbControlTransferSync(pipe: USBDevicePipe, requestparam: USBDeviceRequestParams, timeout: Optional): f64; + +@gen_promise("bulkTransfer") +function bulkTransferSync( + pipe: USBDevicePipe, + endpoint: USBEndpoint, + buffer: @sts_type("Uint8Array") Opaque, + timeout: Optional +): f64; + +function closePipe(pipe: USBDevicePipe): f64; + +function hasAccessoryRight(accessory: USBAccessory): bool; + +@gen_promise("requestAccessoryRight") +function requestAccessoryRightSync(accessory: USBAccessory): bool; + +function cancelAccessoryRight(accessory: USBAccessory): void; + +function getAccessoryList(): Array; + +function openAccessory(accessory: USBAccessory): USBAccessoryHandle; + +function closeAccessory(accessoryHandle: USBAccessoryHandle): void; + +struct USBEndpoint { + address: i32; + + attributes: i32; + + interval: i32; + + maxPacketSize: i32; + + direction: USBRequestDirection; + + endpointAddr: i32; + + type: i32; + + interfaceId: i32; +} + +struct USBInterface { + id: i32; + + protocol: i32; + + clazz: i32; + + subClass: i32; + + alternateSetting: i32; + + name: String; + + endpoints: Array; +} + +struct USBConfiguration { + id: i32; + + attributes: i32; + + maxPower: i32; + + name: String; + + isRemoteWakeup: bool; + + isSelfPowered: bool; + + interfaces: Array; +} + +struct USBDevice { + busNum: i32; + + devAddress: i32; + + serial: String; + + name: String; + + manufacturerName: String; + + productName: String; + + version: String; + + vendorId: i32; + + productId: i32; + + clazz: i32; + + subClass: i32; + + protocol: i32; + + configs: Array; +} + +struct USBDevicePipe { + busNum: f64; + + devAddress: f64; +} + +enum PowerRoleType : i32 { + NONE = 0, + + SOURCE = 1, + + SINK = 2 +} + +enum DataRoleType : i32 { + NONE = 0, + + HOST = 1, + + DEVICE = 2 +} + +enum PortModeType : i32 { + NONE = 0, + + UFP = 1, + + DFP = 2, + + DRP = 3, + + NUM_MODES = 4 +} + +struct USBPortStatus { + currentMode: i32; + + currentPowerRole: i32; + + currentDataRole: i32; +} + +struct USBPort { + id: i32; + + supportedModes: PortModeType; + + status: USBPortStatus; +} + +struct USBControlParams { + request: i32; + + target: USBRequestTargetType; + + reqType: USBControlRequestType; + + value: i32; + + index: i32; + + data: @typedarray Array; +} + +struct USBDeviceRequestParams { + bmRequestType: f64; + + bRequest: f64; + + wValue: f64; + + wIndex: f64; + + wLength: f64; + + data: @sts_type("Uint8Array") Opaque; +} + +enum USBRequestTargetType : i32 { + USB_REQUEST_TARGET_DEVICE = 0, + + USB_REQUEST_TARGET_INTERFACE = 1, + + USB_REQUEST_TARGET_ENDPOINT = 2, + + USB_REQUEST_TARGET_OTHER = 3 +} + +enum USBControlRequestType : i32 { + USB_REQUEST_TYPE_STANDARD = 0, + + USB_REQUEST_TYPE_CLASS = 1, + + USB_REQUEST_TYPE_VENDOR = 2 +} + +enum USBRequestDirection : i32 { + USB_REQUEST_DIR_TO_DEVICE = 0, + + USB_REQUEST_DIR_FROM_DEVICE = 0x80 +} + +enum FunctionType : i32 { + NONE = 0, + + ACM = 1, + + ECM = 2, + + HDC = 4, + + MTP = 8, + + PTP = 16, + + RNDIS = 32, + + MIDI = 64, + + AUDIO_SOURCE = 128, + + NCM = 256 +} + +struct USBAccessory { + manufacturer: String; + + product: String; + + description: String; + + version: String; + + serialNumber: String; +} + +struct USBAccessoryHandle { + accessoryFd: i32; +} + +enum UsbTransferFlags : i32 { + USB_TRANSFER_SHORT_NOT_OK = 0, + + USB_TRANSFER_FREE_BUFFER = 1, + + USB_TRANSFER_FREE_TRANSFER = 2, + + USB_TRANSFER_ADD_ZERO_PACKET = 3 +} + +enum UsbTransferStatus : i32 { + TRANSFER_COMPLETED = 0, + + TRANSFER_ERROR = 1, + + TRANSFER_TIMED_OUT = 2, + + TRANSFER_CANCELED = 3, + + TRANSFER_STALL = 4, + + TRANSFER_NO_DEVICE = 5, + + TRANSFER_OVERFLOW = 6 +} + +enum UsbEndpointTransferType : i32 { + TRANSFER_TYPE_ISOCHRONOUS = 0x1, + + TRANSFER_TYPE_BULK = 0x2, + + TRANSFER_TYPE_INTERRUPT = 0x3 +} + +struct UsbIsoPacketDescriptor { + length: i32; + + actualLength: i32; + + status: UsbTransferStatus; +} + +struct SubmitTransferCallback { + actualLength: i32; + + status: UsbTransferStatus; + + isoPacketDescs: Array; +} + +struct UsbDataTransferParams { + devPipe: USBDevicePipe; + + flags: UsbTransferFlags; + + endpoint: f64; + + type: UsbEndpointTransferType; + + timeout: f64; + + length: f64; + + callback: @sts_type("AsyncCallback") Opaque; + + userData: @typedarray Array; + + buffer: @sts_type("Uint8Array") Opaque; + + isoPacketCount: f64; +} + +function usbSubmitTransfer(transfer: UsbDataTransferParams): void; + +function usbCancelTransfer(transfer: UsbDataTransferParams): void; + +function resetUsbDevice(pipe: USBDevicePipe): bool; \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.usbManager.taihe b/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.usbManager.taihe deleted file mode 100644 index ad3d1a54..00000000 --- a/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.usbManager.taihe +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -@!namespace("@ohos.usbManager", "usbManager") - -@!sts_inject(""" -static { loadLibrary("usb_manager_taihe_native.z") } -""") - -enum USBRequestDirection: i32 { - USB_REQUEST_DIR_TO_DEVICE = 0, - USB_REQUEST_DIR_FROM_DEVICE = 0x80 -} - -struct USBEndpoint { - address: i32; - attributes: i32; - interval: i32; - maxPacketSize: i32; - direction: USBRequestDirection; - endpointAddr: i32; - type: i32; - interfaceId: i32; -} - -struct USBInterface { - id: i32; - protocol: i32; - clazz: i32; - subClass: i32; - alternateSetting: i32; - name: String; - endpoints: Array; -} - -struct USBConfiguration { - id: i32; - attributes: i32; - maxPower: i32; - name: String; - isRemoteWakeup: bool; - isSelfPowered: bool; - interfaces: Array; -} - -struct USBDevice { - busNum: i32; - devAddress: i32; - serial: String; - name: String; - manufacturerName: String; - productName: String; - version: String; - vendorId: i32; - productId: i32; - clazz: i32; - subClass: i32; - protocol: i32; - configs: Array; -} - -function getDevices(): Array; diff --git a/frameworks/ets/taihe/usb_manager/src/ani_constructor.cpp b/frameworks/ets/taihe/usb_manager/src/ani_constructor.cpp index e14b885e..d472f6c6 100644 --- a/frameworks/ets/taihe/usb_manager/src/ani_constructor.cpp +++ b/frameworks/ets/taihe/usb_manager/src/ani_constructor.cpp @@ -1,29 +1,35 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 "ohos.usbManager.usbManager.ani.hpp" -ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) -{ - ani_env *env; - if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { - return ANI_ERROR; - } - if (ANI_OK != ohos::usbManager::usbManager::ANIRegister(env)) { - std::cerr << "Error from ohos::usbManager::usbManager::ANIRegister" << std::endl; - return ANI_ERROR; - } - *result = ANI_VERSION_1; - return ANI_OK; -} +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ohos.usbManager.ani.hpp" +#include "ohos.usbManager.serial.ani.hpp" +#include "taihe/runtime.hpp" +ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result) +{ + ani_env *env; + if (ANI_OK != vm->GetEnv(ANI_VERSION_1, &env)) { + return ANI_ERROR; + } + if (ANI_OK != ohos::usbManager::ANIRegister(env)) { + std::cerr << "Error from ohos::usbManager::ANIRegister" << std::endl; + return ANI_ERROR; + } + if (ANI_OK != ohos::usbManager::serial::ANIRegister(env)) { + std::cerr << "Error from ohos::usbManager::serial::ANIRegister" << std::endl; + return ANI_ERROR; + } + *result = ANI_VERSION_1; + return ANI_OK; +} diff --git a/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.impl.cpp b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.impl.cpp new file mode 100644 index 00000000..c4683db3 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.impl.cpp @@ -0,0 +1,1282 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ohos.usbManager.impl.hpp" +#include "ashmem.h" +#include "event_handler.h" +#include "hilog_wrapper.h" +#include "ohos.usbManager.proj.hpp" +#include "stdexcept" +#include "taihe/runtime.hpp" +#include "usb_errors.h" +#include "usb_srv_client.h" +#include "v1_2/usb_types.h" +#include "ohos.usbManager.SubmitTransferCallback.ani.2.h" + +using namespace taihe; +using namespace ohos::usbManager; +using OHOS::Ashmem; +using OHOS::sptr; +using OHOS::USB::MODULE_JS_NAPI; +using OHOS::USB::USB_MGR_LABEL; + +static int32_t g_accFd = 0; +const int32_t IO_ERROR = -1; +const int32_t INVALID_PARAM = -2; +const int32_t NO_DEVICE = -4; +const int32_t NOT_FOUND = -5; +const int32_t ERROR_BUSY = -6; +const int32_t NO_MEM = -11; + +const int32_t ERROR = -1; +const int32_t HDF_DEV_ERR_NO_DEVICE = -202; +const int32_t USB_DEVICE_PIPE_CHECK_ERROR = 14400013; +constexpr int32_t CAPACITY_NOT_SUPPORT = 801; + +static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance(); + +enum UsbManagerFeature { + FEATURE_HOST = 0, + FEATURE_DEVICE = 1, + FEATURE_PORT = 2, +}; + +static bool HasFeature(UsbManagerFeature feature) +{ + switch (feature) { + case FEATURE_HOST: +#ifndef USB_MANAGER_FEATURE_HOST + return false; +#else + return true; +#endif // USB_MANAGER_FEATURE_HOST + case FEATURE_DEVICE: +#ifndef USB_MANAGER_FEATURE_DEVICE + return false; +#else + return true; +#endif // USB_MANAGER_FEATURE_DEVICE + case FEATURE_PORT: +#ifndef USB_MANAGER_FEATURE_PORT + return false; +#else + return true; +#endif // USB_MANAGER_FEATURE_PORT + default:; + } + return false; +} + +enum UsbJsErrCode : int32_t { + OHEC_COMMON_PERMISSION_NOT_ALLOWED = 201, + OHEC_COMMON_NORMAL_APP_NOT_ALLOWED = 202, + OHEC_COMMON_PARAM_ERROR = 401, + CAPABILITY_NOT_SUPPORT = 801, + + UEC_COMMON_BASE = 14400000, + UEC_COMMON_HAS_NO_RIGHT = UEC_COMMON_BASE + 1, + UEC_COMMON_HDC_NOT_ALLOWED = UEC_COMMON_BASE + 2, + UEC_COMMON_PORTROLE_SWITCH_NOT_ALLOWED = UEC_COMMON_BASE + 3, + UEC_COMMON_SERVICE_EXCEPTION = UEC_COMMON_BASE + 4, + UEC_COMMON_RIGHT_DATABASE_ERROR = UEC_COMMON_BASE + 5, + UEC_COMMON_FUNCTION_NOT_SUPPORT = UEC_COMMON_BASE + 6, + + UEC_ACCESSORY_BASE = UEC_COMMON_BASE + 1000, + UEC_ACCESSORY_NOT_MATCH = UEC_ACCESSORY_BASE + 1, + UEC_ACCESSORY_OPEN_FAILED = UEC_ACCESSORY_BASE + 2, + UEC_ACCESSORY_CAN_NOT_REOPEN = UEC_ACCESSORY_BASE + 3, + + USB_SUBMIT_TRANSFER_RESOURCE_BUSY_ERROR = 14400007, + USB_SUBMIT_TRANSFER_NO_DEVICE_ERROR = 14400008, + USB_SUBMIT_TRANSFER_NO_MEM_ERROR = 14400009, + USB_SUBMIT_TRANSFER_OTHER_ERROR = 14400010, + USB_SUBMIT_TRANSFER_NOT_FOUND_ERROR = 14400011, + USB_SUBMIT_TRANSFER_IO_ERROR = 14400012, +}; + +const std::map ERRCODE_MSG_MAP = { + {OHEC_COMMON_PERMISSION_NOT_ALLOWED, + "BusinessError 201:Permission verification failed. " + "The application does not have the permission required to call the API."}, + {OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, "BusinessError 202:Permission denied. Normal application uses system api."}, + {OHEC_COMMON_PARAM_ERROR, "BusinessError 401:Parameter error."}, + {CAPABILITY_NOT_SUPPORT, "BusinessError 801:Capability not supported."}, + {UEC_COMMON_HAS_NO_RIGHT, "BusinessError 14400001:Permission denied."}, + {UEC_COMMON_HDC_NOT_ALLOWED, "BusinessError 14400002:Permission denied. The HDC is disabled by the system."}, + {UEC_COMMON_PORTROLE_SWITCH_NOT_ALLOWED, + "BusinessError 14400003:Unsupported operation.The current device does not support port role switching."}, + {UEC_COMMON_SERVICE_EXCEPTION, + "BusinessError 14400004:Service exception. Possible causes:No accessory is plugged in."}, + {UEC_COMMON_RIGHT_DATABASE_ERROR, "BusinessError 14400005:Database operation exception."}, + {UEC_COMMON_FUNCTION_NOT_SUPPORT, "BusinessError 14400006:Unsupported operation. The function is not supported."}, + {UEC_ACCESSORY_NOT_MATCH, "BusinessError 14401001:The target USBAccessory not matched."}, + {UEC_ACCESSORY_OPEN_FAILED, "BusinessError 14401002:Failed to open the native accessory node."}, + {UEC_ACCESSORY_CAN_NOT_REOPEN, "BusinessError 14401003:Cannot reopen the accessory."}, + + {USB_SUBMIT_TRANSFER_RESOURCE_BUSY_ERROR, "BusinessError 14400007:Resource busy."}, + {USB_SUBMIT_TRANSFER_NO_DEVICE_ERROR, "BusinessError 14400008:No such device (it may have been disconnected)."}, + {USB_SUBMIT_TRANSFER_NO_MEM_ERROR, "BusinessError 14400009:Insufficient memory."}, + {USB_SUBMIT_TRANSFER_OTHER_ERROR, "BusinessError 14400010:Other USB error."}, + {USB_SUBMIT_TRANSFER_NOT_FOUND_ERROR, + "BusinessError 14400011:The transfer is not in progress, or is already complete or cancelled."}, + {USB_SUBMIT_TRANSFER_IO_ERROR, "BusinessError 14400012:Transmission I/O error."}, +}; + +static std::string_view GetErrMsgByErrCode(int32_t errCode) +{ + auto obj = ERRCODE_MSG_MAP.find(errCode); + if (obj == ERRCODE_MSG_MAP.end()) { + return ""; + } + return obj->second; +} + +static void ThrowBusinessError(int32_t errCode, const std::string &errMsg) +{ + set_business_error(errCode, std::string(GetErrMsgByErrCode(errCode)) + errMsg); +} + +namespace { + +static ohos::usbManager::USBEndpoint ParseToUSBEndpoint(const OHOS::USB::USBEndpoint &usbEndpoint) +{ + auto directionKey = usbEndpoint.GetDirection() == OHOS::USB::USB_ENDPOINT_DIR_OUT ? + ohos::usbManager::USBRequestDirection::key_t::USB_REQUEST_DIR_TO_DEVICE : + ohos::usbManager::USBRequestDirection::key_t::USB_REQUEST_DIR_FROM_DEVICE; + return { + .address = usbEndpoint.GetAddress(), + .attributes = usbEndpoint.GetAttributes(), + .interval = usbEndpoint.GetInterval(), + .maxPacketSize = usbEndpoint.GetMaxPacketSize(), + .direction = ohos::usbManager::USBRequestDirection(directionKey), + .endpointAddr = usbEndpoint.GetEndpointNumber(), + .type = usbEndpoint.GetType(), + .interfaceId = usbEndpoint.GetInterfaceId() + }; +} + +static ohos::usbManager::USBInterface ParseToUSBInterface(OHOS::USB::UsbInterface &usbInterface) +{ + std::vector endpoints; + for (const auto &endpoint : usbInterface.GetEndpoints()) { + endpoints.push_back(ParseToUSBEndpoint(endpoint)); + } + return { + .id = usbInterface.GetId(), + .protocol = usbInterface.GetProtocol(), + .clazz = usbInterface.GetClass(), + .subClass = usbInterface.GetSubClass(), + .alternateSetting = usbInterface.GetAlternateSetting(), + .name = usbInterface.GetName(), + .endpoints = array(endpoints) + }; +} + +static ohos::usbManager::USBConfiguration ParseToUSBConfiguration(OHOS::USB::USBConfig &usbConfig) +{ + std::vector interfaces; + for (auto &interface : usbConfig.GetInterfaces()) { + interfaces.push_back(ParseToUSBInterface(interface)); + } + return { + .id = usbConfig.GetId(), + .attributes = usbConfig.GetAttributes(), + .maxPower = usbConfig.GetMaxPower(), + .name = usbConfig.GetName(), + .isRemoteWakeup = usbConfig.IsRemoteWakeup(), + .isSelfPowered = usbConfig.IsSelfPowered(), + .interfaces = array(interfaces) + }; +} + +static ohos::usbManager::USBDevice ParseToUSBDevice(OHOS::USB::UsbDevice &usbDevice) +{ + std::vector configs; + for (auto &config : usbDevice.GetConfigs()) { + configs.push_back(ParseToUSBConfiguration(config)); + } + return { + .busNum = usbDevice.GetBusNum(), + .devAddress = usbDevice.GetDevAddr(), + .serial = usbDevice.GetmSerial(), + .name = usbDevice.GetName(), + .manufacturerName = usbDevice.GetManufacturerName(), + .productName = usbDevice.GetProductName(), + .version = usbDevice.GetVersion(), + .vendorId = usbDevice.GetVendorId(), + .productId = usbDevice.GetProductId(), + .clazz = usbDevice.GetClass(), + .subClass = usbDevice.GetSubclass(), + .protocol = usbDevice.GetProtocol(), + .configs = array(configs) + }; +} + +std::map errorTable = { + {OHOS::USB::UsbErrCode::UEC_SERIAL_OTHER_ERROR, "Connecting to the service failed."}, + {OHOS::USB::UsbErrCode::UEC_INTERFACE_PERMISSION_DENIED, "Permission is denied" }, + {OHOS::USB::UsbErrCode::UEC_SERVICE_PERMISSION_DENIED_SYSAPI, "System permission is denied" }, + {OHOS::USB::UsbErrCode::UEC_INTERFACE_INVALID_VALUE, "Invalid input parameter." } +}; + +static OHOS::USB::USBEndpoint ConvertToUSBEndpoint(const ohos::usbManager::USBEndpoint &usbEndpoint) +{ + OHOS::USB::USBEndpoint point; + point.SetAddr(usbEndpoint.address); + point.SetAttr(usbEndpoint.attributes); + point.SetInterval(usbEndpoint.interval); + point.SetMaxPacketSize(usbEndpoint.maxPacketSize); + point.SetInterfaceId(usbEndpoint.interfaceId); + return point; +} + +static OHOS::USB::UsbInterface ConvertToUsbInterface(ohos::usbManager::USBInterface const &usbInterface) +{ + std::vector endpts; + for (const auto &endpoint : usbInterface.endpoints) { + endpts.push_back(ConvertToUSBEndpoint(endpoint)); + } + OHOS::USB::UsbInterface interface; + interface.SetId(usbInterface.id); + interface.SetProtocol(usbInterface.protocol); + interface.SetClass(usbInterface.clazz); + interface.SetSubClass(usbInterface.subClass); + interface.SetAlternateSetting(usbInterface.alternateSetting); + interface.SetName(usbInterface.name.c_str()); + interface.SetEndpoints(endpts); + return interface; +} + +static OHOS::USB::USBDevicePipe ConvertUSBDevicePipe(ohos::usbManager::USBDevicePipe const &usbDevice) +{ + OHOS::USB::USBDevicePipe device; + device.SetBusNum(static_cast(usbDevice.busNum)); + device.SetDevAddr(static_cast(usbDevice.devAddress)); + return device; +} + +static OHOS::USB::USBConfig ConvertToUSBConfig(ohos::usbManager::USBConfiguration const &usbConfiguration) +{ + std::vector interfaces; + for (auto &interface : usbConfiguration.interfaces) { + interfaces.push_back(ConvertToUsbInterface(interface)); + } + OHOS::USB::USBConfig usbConfig; + usbConfig.SetId(usbConfiguration.id); + usbConfig.SetAttribute(usbConfiguration.attributes); + usbConfig.SetMaxPower(usbConfiguration.maxPower); + usbConfig.SetName(usbConfiguration.name.c_str()); + usbConfig.SetInterfaces(interfaces); + return usbConfig; +} + +static OHOS::USB::USBAccessory ConvertUsbDevice(ohos::usbManager::USBAccessory const &usbDevice) +{ + OHOS::USB::USBAccessory device; + device.SetManufacturer(usbDevice.manufacturer.c_str()); + device.SetProduct(usbDevice.product.c_str()); + device.SetDescription(usbDevice.description.c_str()); + device.SetVersion(usbDevice.version.c_str()); + device.SetSerialNumber(usbDevice.serialNumber.c_str()); + return device; +} + +static OHOS::USB::UsbDevice ConvertToUsbDevice(ohos::usbManager::USBDevice const &usbDevice) +{ + std::vector configs; + for (auto &config : usbDevice.configs) { + configs.push_back(ConvertToUSBConfig(config)); + } + OHOS::USB::UsbDevice device; + device.SetConfigs(configs); + device.SetDevAddr(usbDevice.devAddress); + device.SetBusNum(usbDevice.busNum); + device.SetName(usbDevice.name.c_str()); + device.SetManufacturerName(usbDevice.manufacturerName.c_str()); + device.SetProductName(usbDevice.productName.c_str()); + device.SetVersion(usbDevice.version.c_str()); + device.SetVendorId(usbDevice.vendorId); + device.SetProductId(usbDevice.productId); + device.SetClass(usbDevice.clazz); + device.SetSubclass(usbDevice.subClass); + device.SetProtocol(usbDevice.protocol); + return device; +} + +static ohos::usbManager::USBPortStatus ConvertUSBPortStatus(OHOS::USB::UsbPortStatus const &usbDevice) +{ + ohos::usbManager::USBPortStatus device; + device.currentDataRole = usbDevice.currentDataRole; + device.currentMode = usbDevice.currentMode; + device.currentPowerRole = usbDevice.currentPowerRole; + return device; +} + +static ohos::usbManager::USBPort ConvertUSBPort(OHOS::USB::UsbPort const &usbDevice) +{ + using PortModeType = ohos::usbManager::PortModeType; + using key_t = PortModeType::key_t; + key_t modeKey = key_t::NONE; + if (usbDevice.supportedModes >= 0 && usbDevice.supportedModes < static_cast(key_t::NUM_MODES)) { + modeKey = static_cast(usbDevice.supportedModes); + } + return { + .id = usbDevice.id, + .status = ConvertUSBPortStatus(usbDevice.usbPortStatus), + .supportedModes = PortModeType(modeKey) + }; +} + +USBDevicePipe connectDevice(USBDevice const &device) +{ + OHOS::USB::UsbDevice usbDev = ConvertToUsbDevice(device); + OHOS::USB::USBDevicePipe pipe; + int32_t ret = g_usbClient.OpenDevice(usbDev, pipe); + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED || ret == OHOS::USB::UEC_INTERFACE_PERMISSION_DENIED) { + set_business_error(OHOS::USB::UEC_INTERFACE_PERMISSION_DENIED, "need call requestRight to get the permission"); + USB_HILOGE(MODULE_JS_NAPI, "Connect Device failed, return code:%{public}d", ret); + return {}; + } + return { + .busNum = pipe.GetBusNum(), + .devAddress = pipe.GetDevAddr() + }; +} + +static void ParseEndpointObj(const ohos::usbManager::USBEndpoint endpoint, OHOS::USB::USBEndpoint &ep) +{ + ep = OHOS::USB::USBEndpoint(endpoint.address, endpoint.attributes, endpoint.interval, endpoint.maxPacketSize); + ep.SetInterfaceId(endpoint.interfaceId); +} + +array getDevices() +{ + std::vector res; + if (!HasFeature(FEATURE_HOST)) { + set_business_error(CAPACITY_NOT_SUPPORT, ""); + return array(res); + } + std::vector deviceList; + auto ret = g_usbClient.GetDevices(deviceList); + if (ret != 0) { + return array(res); + } + for (auto &usbDevice : deviceList) { + res.push_back(ParseToUSBDevice(usbDevice)); + } + return array(res); +} + +bool hasRight(string_view deviceName) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return false; + } + bool result = g_usbClient.HasRight(std::string(deviceName)); + return result; +} + +bool requestRightSync(string_view deviceName) +{ + bool bRet = false; + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return bRet; + } + int32_t ret = g_usbClient.RequestRight(std::string(deviceName)); + if (ret == OHOS::USB::UEC_OK) { + bRet = true; + } else { + USB_HILOGE(MODULE_JS_NAPI, "RequestRight failed, return code:%{public}d", ret); + ThrowBusinessError(ret, ""); + return bRet; + } + return bRet; +} + +bool removeRight(string_view deviceName) +{ + bool bResult = false; + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return bResult; + } + int32_t ret = g_usbClient.RemoveRight(std::string(deviceName)); + if (ret == OHOS::USB::UEC_OK) { + bResult = true; + } else { + USB_HILOGE(MODULE_JS_NAPI, "RemoveRight failed, return code:%{public}d", ret); + ThrowBusinessError(ret, ""); + return bResult; + } + return bResult; +} + +bool addDeviceAccessRight(string_view tokenId, string_view deviceName) +{ + bool bResult = false; + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return bResult; + } + int32_t ret = g_usbClient.AddAccessRight(std::string(tokenId), std::string(deviceName)); + if (ret == OHOS::USB::UEC_OK) { + bResult = true; + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, "Normal app not allowed"); + return bResult; + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, "Permission not allowed"); + return bResult; + } else { + ThrowBusinessError(ret, ""); + return bResult; + } + return bResult; +} + +double getFunctionsFromString(string_view funcs) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return CAPABILITY_NOT_SUPPORT; + } + int32_t numFuncs = g_usbClient.UsbFunctionsFromString(std::string(funcs)); + if (numFuncs == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + return OHEC_COMMON_NORMAL_APP_NOT_ALLOWED; + } + if (numFuncs == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + return OHEC_COMMON_PERMISSION_NOT_ALLOWED; + } + return static_cast(numFuncs); +} + +string getStringFromFunctions(FunctionType funcs) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return ""; + } + std::string strFuncs = g_usbClient.UsbFunctionsToString(funcs); + if (strFuncs == OHOS::USB::PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + return ""; + } + if (strFuncs == OHOS::USB::SYS_APP_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + return ""; + } + return strFuncs; +} + +void setDeviceFunctionsSync(FunctionType funcs) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return; + } + int32_t ret = g_usbClient.SetCurrentFunctions(funcs); + if (ret == OHOS::USB::UEC_OK) { + return; + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + return; + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + return; + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_CHECK_HDC) { + ThrowBusinessError(UEC_COMMON_HDC_NOT_ALLOWED, ""); + return; + } else if (ret == OHOS::USB::UEC_SERVICE_FUNCTION_NOT_SUPPORT) { + ThrowBusinessError(UEC_COMMON_FUNCTION_NOT_SUPPORT, ""); + return; + } else { + USB_HILOGE(MODULE_JS_NAPI, "setDeviceFunctionsSync failed, return code:%{public}d", ret); + ThrowBusinessError(ret, ""); + return; + } +} + +FunctionType getDeviceFunctions() +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + int32_t cfuncs; + int32_t ret = g_usbClient.GetCurrentFunctions(cfuncs); + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, "Normal app not allowed"); + } + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, "Permission not allowed"); + } + if (ret != OHOS::USB::UEC_OK) { + ThrowBusinessError(ret, ""); + } + return {FunctionType::key_t(cfuncs)}; +} + +array getPortList() +{ + if (!HasFeature(FEATURE_PORT)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + std::vector ports; + int32_t ret = g_usbClient.GetPorts(ports); + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + } + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + } + if (ret != OHOS::USB::UEC_OK) { + ThrowBusinessError(ret, ""); + } + if (ports.empty()) { + USB_HILOGE(MODULE_JS_NAPI, "ports empty"); + return {}; + } + std::vector<::ohos::usbManager::USBPort> convertedPorts; + convertedPorts.reserve(ports.size()); + for (const auto &port : ports) { + convertedPorts.push_back(ConvertUSBPort(port)); + } + return ::taihe::array<::ohos::usbManager::USBPort>( + taihe::array_view<::ohos::usbManager::USBPort>(convertedPorts.data(), convertedPorts.size())); +} + +PortModeType getPortSupportModes(double portId) +{ + if (!HasFeature(FEATURE_PORT)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + if (portId < 0) { + ThrowBusinessError(OHEC_COMMON_PARAM_ERROR, ""); + } + int32_t result = 0; + int32_t ret = g_usbClient.GetSupportedModes(portId, result); + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + } + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + } + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_NAPI, "false ret = %{public}d", ret); + ThrowBusinessError(ret, ""); + } + return {PortModeType::key_t(result)}; +} + +void setPortRoleTypesSync(double portId, PowerRoleType powerRole, DataRoleType dataRole) +{ + if (!HasFeature(FEATURE_PORT)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + if (portId < 0 || powerRole < 0 || dataRole < 0) { + ThrowBusinessError(OHEC_COMMON_PARAM_ERROR, ""); + } + int ret = g_usbClient.SetPortRole(portId, powerRole, dataRole); + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + } + if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + } + if (ret == OHOS::USB::UEC_SERVICE_NOT_SUPPORT_SWITCH_PORT) { + ThrowBusinessError(UEC_COMMON_PORTROLE_SWITCH_NOT_ALLOWED, ""); + } + if (ret != OHOS::USB::UEC_OK) { + ThrowBusinessError(ret, "false ret: " + std::to_string(ret)); + } +} + +void addAccessoryRight(double tokenId, ohos::usbManager::USBAccessory const &accessory) +{ + if (!HasFeature(FEATURE_PORT)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + int32_t ret = g_usbClient.AddAccessoryRight(tokenId, ConvertUsbDevice(accessory)); + + switch (ret) { + case OHOS::USB::UEC_OK: + return; + case OHOS::USB::UEC_SERVICE_GET_TOKEN_INFO_FAILED: + ThrowBusinessError(OHEC_COMMON_PARAM_ERROR, ""); + case OHOS::USB::UEC_SERVICE_ACCESSORY_NOT_MATCH: + ThrowBusinessError(OHEC_COMMON_PARAM_ERROR, "Get accessory through getAccessoryList"); + case OHOS::USB::UEC_SERVICE_DATABASE_OPERATION_FAILED: + ThrowBusinessError(UEC_COMMON_RIGHT_DATABASE_ERROR, "Database request operation exception"); + case OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI: + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + case OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED: + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + default: + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, "Service exception"); + } +} + +double claimInterface(USBDevicePipe const &pipe, USBInterface const &iface, optional_view force) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + bool forceClaim = force.has_value() ? *force : false; + int ret = internalPipe.ClaimInterface(ConvertToUsbInterface(iface), forceClaim); + if (ret != OHOS::USB::UEC_OK) { + ThrowBusinessError(ret, "pipe call ClaimInterface"); + } + return ret; +} + +double releaseInterface(USBDevicePipe const &pipe, USBInterface const &iface) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + int ret = internalPipe.ReleaseInterface(ConvertToUsbInterface(iface)); + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_NAPI, "releaseInterface failed:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + return ret; +} + +double setConfiguration(USBDevicePipe const &pipe, USBConfiguration const &config) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + int ret = g_usbClient.SetConfiguration(internalPipe, ConvertToUSBConfig(config)); + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_NAPI, "setConfiguration failed:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + return ret; +} + +double setInterface(USBDevicePipe const &pipe, USBInterface const &iface) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + int ret = g_usbClient.SetInterface(internalPipe, ConvertToUsbInterface(iface)); + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_NAPI, "setInterface failed:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + return ret; +} + +array getRawDescriptor(USBDevicePipe const &pipe) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + std::vector bufferData; + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + int ret = g_usbClient.GetRawDescriptors(internalPipe, bufferData); + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_NAPI, "getRawDescriptor failed:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + return ::taihe::array(bufferData); +} + +double getFileDescriptor(USBDevicePipe const &pipe) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + int32_t fd = ERROR; + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + int32_t ret = g_usbClient.GetFileDescriptor(internalPipe, fd); + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_NAPI, "getFileDescriptor failed:%{public}d", ret); + } + return static_cast(fd); +} + +double usbControlTransferSync( + USBDevicePipe const &pipe, USBDeviceRequestParams const &requestparam, optional_view timeout) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return ERROR; + } + OHOS::USB::USBDevicePipe nativePipe; + nativePipe.SetBusNum(static_cast(pipe.busNum)); + nativePipe.SetDevAddr(static_cast(pipe.devAddress)); + int32_t timeOut = 0; + if (timeout.has_value()) { + timeOut = int(timeout.value()); + } + const OHOS::HDI::Usb::V1_2::UsbCtrlTransferParams tctrl = {requestparam.bmRequestType, requestparam.bRequest, + requestparam.wValue, requestparam.wIndex, requestparam.wLength, timeOut}; + + ani_ref bufferRef; + ani_env *env = ::taihe::get_env(); + ani_object array_obj = reinterpret_cast(requestparam.data); + if (ANI_OK != env->Object_GetFieldByName_Ref(array_obj, "buffer", &bufferRef)) { + USB_HILOGE(MODULE_JS_NAPI, "Object_GetFieldByName_Ref failed."); + return ERROR; + } + void *data; + size_t size; + if (ANI_OK != env->ArrayBuffer_GetInfo(static_cast(bufferRef), &data, &size)) { + USB_HILOGE(MODULE_JS_NAPI, "ArrayBuffer_GetInfo failed."); + return ERROR; + } + int32_t ret; + std::vector bufferData(static_cast(data), static_cast(data) + size); + ret = nativePipe.UsbControlTransfer(tctrl, bufferData); + if ((int(requestparam.bmRequestType) & OHOS::USB::USB_ENDPOINT_DIR_MASK) == OHOS::USB::USB_ENDPOINT_DIR_IN) { + ret = memcpy_s(data, size, bufferData.data(), bufferData.size()); + } + if (ret != OHOS::USB::UEC_OK) { + return ERROR; + } + return bufferData.size(); +} + +double bulkTransferSync(::ohos::usbManager::USBDevicePipe const &pipe, ::ohos::usbManager::USBEndpoint const &endpoint, + uintptr_t buffer, optional_view timeout) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return ERROR; + } + ani_ref bufferRef; + ani_env *env = ::taihe::get_env(); + ani_object array_obj = reinterpret_cast(buffer); + if (ANI_OK != env->Object_GetFieldByName_Ref(array_obj, "buffer", &bufferRef)) { + USB_HILOGE(MODULE_JS_NAPI, "Object_GetFieldByName_Ref failed."); + return ERROR; + } + void *data; + size_t size; + if (ANI_OK != env->ArrayBuffer_GetInfo(static_cast(bufferRef), &data, &size)) { + USB_HILOGE(MODULE_JS_NAPI, "ArrayBuffer_GetInfo failed."); + return ERROR; + } + OHOS::USB::USBEndpoint ep; + ParseEndpointObj(endpoint, ep); + std::vector bufferData(static_cast(data), static_cast(data) + size); + OHOS::USB::USBDevicePipe nativePipe; + nativePipe.SetBusNum(static_cast(pipe.busNum)); + nativePipe.SetDevAddr(static_cast(pipe.devAddress)); + int32_t timeOut = 0; + if (timeout.has_value()) { + timeOut = timeout.value(); + } + int32_t ret = nativePipe.BulkTransfer(ep, bufferData, timeOut); + if (ep.GetDirection() == OHOS::USB::USB_ENDPOINT_DIR_IN) { + ret = memcpy_s(data, size, bufferData.data(), bufferData.size()); + } + if (ret == OHOS::USB::UEC_OK) { + return bufferData.size(); + } else { + return ERROR; + } +} + +double closePipe(USBDevicePipe const &pipe) +{ + OHOS::USB::USBDevicePipe nativePipe; + nativePipe.SetBusNum(static_cast(pipe.busNum)); + nativePipe.SetDevAddr(static_cast(pipe.devAddress)); + return nativePipe.Close(); +} + +static OHOS::USB::USBAccessory taihe2Native(ohos::usbManager::USBAccessory accessory) +{ + OHOS::USB::USBAccessory nativeAccessory = {accessory.manufacturer.c_str(), accessory.product.c_str(), + accessory.description.c_str(), accessory.version.c_str(), accessory.serialNumber.c_str()}; + return nativeAccessory; +} + +static ohos::usbManager::USBAccessory native2Taihe(OHOS::USB::USBAccessory accessory) +{ + ohos::usbManager::USBAccessory taiheAccessory = {accessory.GetManufacturer(), accessory.GetProduct(), + accessory.GetDescription(), accessory.GetVersion(), accessory.GetSerialNumber()}; + return taiheAccessory; +} + +bool hasAccessoryRight(ohos::usbManager::USBAccessory const &accessory) +{ + bool result = false; + int32_t ret = g_usbClient.HasAccessoryRight(taihe2Native(accessory), result); + if (ret == OHOS::USB::UEC_OK) { + return result; + } else if (ret == OHOS::USB::UEC_SERVICE_ACCESSORY_NOT_MATCH) { + ThrowBusinessError(UEC_ACCESSORY_NOT_MATCH, "Get accessory through getAccessoryList"); + } else if (ret == OHOS::USB::UEC_SERVICE_DATABASE_OPERATION_FAILED) { + ThrowBusinessError(UEC_COMMON_RIGHT_DATABASE_ERROR, "Database request operation exception"); + } else { + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, "Service exception"); + } + return result; +} + +bool requestAccessoryRightSync(ohos::usbManager::USBAccessory const &accessory) +{ + bool result = false; + int32_t ret = g_usbClient.RequestAccessoryRight(taihe2Native(accessory), result); + if (ret == OHOS::USB::UEC_OK) { + return result; + } else if (ret == OHOS::USB::UEC_SERVICE_ACCESSORY_NOT_MATCH) { + ThrowBusinessError(UEC_ACCESSORY_NOT_MATCH, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_DATABASE_OPERATION_FAILED) { + ThrowBusinessError(UEC_COMMON_RIGHT_DATABASE_ERROR, ""); + } else { + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, ""); + } + return result; +} + +void cancelAccessoryRight(ohos::usbManager::USBAccessory const &accessory) +{ + if (g_accFd != 0) { + close(g_accFd); + g_accFd = 0; + g_usbClient.CloseAccessory(g_accFd); + } + int32_t ret = g_usbClient.CancelAccessoryRight(taihe2Native(accessory)); + if (ret == OHOS::USB::UEC_OK) { + return; + } else if (ret == OHOS::USB::UEC_SERVICE_ACCESSORY_NOT_MATCH) { + ThrowBusinessError(UEC_ACCESSORY_NOT_MATCH, "Get accessory through getAccessoryList"); + } else if (ret == OHOS::USB::UEC_SERVICE_DATABASE_OPERATION_FAILED) { + ThrowBusinessError(UEC_COMMON_RIGHT_DATABASE_ERROR, "Database request operation exception"); + } else { + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, "Service exception"); + } +} + +array getAccessoryList() +{ + std::vector accessoryList; + std::vector results; + int32_t ret = g_usbClient.GetAccessoryList(accessoryList); + if (ret == OHOS::USB::UEC_OK) { + for (const auto &item : accessoryList) { + results.push_back(native2Taihe(item)); + } + } else { + results.clear(); + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, "Service exception"); + } + return array(results); +} + +USBAccessoryHandle openAccessory(ohos::usbManager::USBAccessory const &accessory) +{ + int32_t fd = -1; + int32_t ret = g_usbClient.OpenAccessory(taihe2Native(accessory), fd); + + USBAccessoryHandle handler; + if (ret == OHOS::USB::UEC_OK) { + g_accFd = fd; + handler.accessoryFd = fd; + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED || ret == OHOS::USB::UEC_INTERFACE_PERMISSION_DENIED) { + ThrowBusinessError(UEC_COMMON_HAS_NO_RIGHT, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_ACCESSORY_NOT_MATCH) { + ThrowBusinessError(UEC_ACCESSORY_NOT_MATCH, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_ACCESSORY_OPEN_NATIVE_NODE_FAILED) { + ThrowBusinessError(UEC_ACCESSORY_OPEN_FAILED, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_ACCESSORY_REOPEN) { + ThrowBusinessError(UEC_ACCESSORY_CAN_NOT_REOPEN, ""); + } else { + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, ""); + } + return handler; +} + +void closeAccessory(USBAccessoryHandle const &accessoryHandle) +{ + auto accessoryFd = accessoryHandle.accessoryFd; + if (accessoryFd == 0 || accessoryFd != g_accFd || g_accFd == 0) { + ThrowBusinessError(OHEC_COMMON_PARAM_ERROR, "Parameter accessoryHandle error, need openAccessory first."); + } + close(accessoryFd); + accessoryFd = 0; + int32_t ret = g_usbClient.CloseAccessory(g_accFd); + g_accFd = 0; + if (ret != OHOS::USB::UEC_OK) { + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, "Service exception"); + } + return; +} + +static int32_t UsbSubmitTransferErrorCode(int32_t &error) +{ + switch (error) { + case IO_ERROR: + return USB_SUBMIT_TRANSFER_IO_ERROR; + case INVALID_PARAM: + return OHEC_COMMON_PARAM_ERROR; + case NO_DEVICE: + return USB_SUBMIT_TRANSFER_NO_DEVICE_ERROR; + case NOT_FOUND: + return USB_SUBMIT_TRANSFER_NOT_FOUND_ERROR; + case ERROR_BUSY: + return USB_SUBMIT_TRANSFER_RESOURCE_BUSY_ERROR; + case NO_MEM: + return USB_SUBMIT_TRANSFER_NO_MEM_ERROR; + case OHOS::USB::UEC_SERVICE_PERMISSION_DENIED: + return UEC_COMMON_HAS_NO_RIGHT; + default: + return USB_SUBMIT_TRANSFER_OTHER_ERROR; + } +} + +struct USBTransferAsyncContext { + ani_vm *vm; + OHOS::USB::USBDevicePipe pipe; + int32_t endpoint; + int32_t flags; + int32_t type; + int32_t status; + int32_t timeOut = 0; + int32_t length; + int32_t actualLength; + size_t bufferLength = 0; + sptr ashmem = nullptr; + uint8_t *userData; + uint8_t *buffer; + uint32_t numIsoPackets; + std::string name = "CreateAshmem"; + ani_object callbackRef; +}; + +static bool CreateAndWriteAshmem(USBTransferAsyncContext *asyncContext, OHOS::HDI::Usb::V1_2::USBTransferInfo &obj) +{ + asyncContext->ashmem = Ashmem::CreateAshmem(asyncContext->name.c_str(), asyncContext->length); + if (asyncContext->ashmem == nullptr) { + return false; + } + uint8_t endpointId = static_cast(asyncContext->endpoint) & OHOS::USB::USB_ENDPOINT_DIR_MASK; + if (endpointId == OHOS::USB::USB_ENDPOINT_DIR_OUT) { + std::vector bufferData(asyncContext->buffer, asyncContext->buffer + asyncContext->bufferLength); + obj.length = static_cast(bufferData.size()); + asyncContext->ashmem->MapReadAndWriteAshmem(); + if (!asyncContext->ashmem->WriteToAshmem(asyncContext->buffer, bufferData.size(), 0)) { + asyncContext->ashmem->CloseAshmem(); + return false; + } + } + return true; +} + +static void ReadDataToBuffer(USBTransferAsyncContext *asyncContext, const OHOS::USB::TransferCallbackInfo &info) +{ + uint8_t endpointId = static_cast(asyncContext->endpoint) & OHOS::USB::USB_ENDPOINT_DIR_MASK; + if (endpointId == OHOS::USB::USB_ENDPOINT_DIR_IN) { + asyncContext->ashmem->MapReadAndWriteAshmem(); + auto ashmemBuffer = asyncContext->ashmem->ReadFromAshmem(info.actualLength, 0); + if (ashmemBuffer == nullptr) { + asyncContext->ashmem->UnmapAshmem(); + asyncContext->ashmem->CloseAshmem(); + return; + } + int32_t ret = memcpy_s(asyncContext->buffer, asyncContext->bufferLength, ashmemBuffer, info.actualLength); + if (ret != EOK) { + USB_HILOGE(MODULE_JS_NAPI, "memcpy_s fatal failed error: %{public}d", ret); + } + } + asyncContext->ashmem->UnmapAshmem(); + asyncContext->ashmem->CloseAshmem(); +} + +static ani_object GetDefaultBusinessError(ani_env *env) +{ + static const char *businessErrorName = "L@ohos/base/BusinessError;"; + ani_class cls; + auto status = env->FindClass(businessErrorName, &cls); + if (ANI_OK != status) { + USB_HILOGE(MODULE_JS_NAPI, "Not found class '%{public}s' errcode %{public}d.", businessErrorName, status); + return nullptr; + } + ani_method ctor; + status = env->Class_FindMethod(cls, "", ":V", &ctor); + if (ANI_OK != status) { + USB_HILOGE(MODULE_JS_NAPI, "Not found ctor of '%{public}s' errcode %{public}d.", businessErrorName, status); + return nullptr; + } + ani_object businessErrorObject; + status = env->Object_New(cls, ctor, &businessErrorObject); + if (ANI_OK != status) { + USB_HILOGE(MODULE_JS_NAPI, "Can not create business error errcode %{public}d.", status); + return nullptr; + } + return businessErrorObject; +} + +static thread_local std::shared_ptr mainHandler = nullptr; + +static bool SendEventToMainThread(const std::function func) +{ + if (func == nullptr) { + USB_HILOGE(MODULE_JS_NAPI, "func is nullptr!"); + return false; + } + + if (!mainHandler) { + auto runner = OHOS::AppExecFwk::EventRunner::GetMainEventRunner(); + if (!runner) { + USB_HILOGE(MODULE_JS_NAPI, "get main event runner failed!"); + return false; + } + mainHandler = std::make_shared(runner); + } + mainHandler->PostTask(func, "", 0, OHOS::AppExecFwk::EventQueue::Priority::HIGH, {}); + return true; +} + +static constexpr int32_t LOCAL_SCOPE_SIZE = 16; +static void AniCallBack(USBTransferAsyncContext *asyncContext, const OHOS::USB::TransferCallbackInfo &info, + const std::vector &isoInfo) +{ + USB_HILOGI(MODULE_JS_NAPI, "AniCallBack enter."); + using ::ohos::usbManager::UsbTransferStatus; + ReadDataToBuffer(asyncContext, info); + int32_t actualLength = info.actualLength; + UsbTransferStatus status((UsbTransferStatus::key_t)info.status); + std::vector isoPacketDesc; + for (const auto &isoInfoItem : isoInfo) { + USB_HILOGE(MODULE_JS_NAPI, "AniCallBack has iso info."); + UsbIsoPacketDescriptor descriptor = { + isoInfoItem.isoActualLength, isoInfoItem.isoLength, {(UsbTransferStatus::key_t)isoInfoItem.isoStatus}}; + isoPacketDesc.push_back(descriptor); + } + ::taihe::array isoPacketDescs(isoPacketDesc); + ::ohos::usbManager::SubmitTransferCallback callbackParam = { + std::move(actualLength), std::move(status), std::move(isoPacketDescs)}; + auto task = [asyncContext, callbackParam]() { + ani_env *env = nullptr; + ani_options aniArgs {0, nullptr}; + if (ANI_ERROR == asyncContext->vm->AttachCurrentThread(&aniArgs, ANI_VERSION_1, &env)) { + if (ANI_OK != asyncContext->vm->GetEnv(ANI_VERSION_1, &env)) { + USB_HILOGI(MODULE_JS_NAPI, "GetEnv failed."); + return; + } + } + if (ANI_OK != env->CreateLocalScope(LOCAL_SCOPE_SIZE)) { + USB_HILOGI(MODULE_JS_NAPI, "CreateLocalScope failed."); + return; + } + auto businessError = GetDefaultBusinessError(env); + auto param = ::taihe::into_ani<::ohos::usbManager::SubmitTransferCallback>(env, callbackParam); + auto callbackFunc = asyncContext->callbackRef; + ani_ref ani_argv[] = {businessError, param}; + ani_ref ani_result; + ani_class cls; + env->FindClass("Lstd/core/Function2;", &cls); + ani_boolean ret; + env->Object_InstanceOf(callbackFunc, cls, &ret); + if (!ret) { + USB_HILOGI(MODULE_JS_NAPI, "%{public}s: callbackFunc is not instance Of Function2.", __func__); + } + auto errCode = env->FunctionalObject_Call(static_cast(callbackFunc), 2, ani_argv, &ani_result); + env->DestroyLocalScope(); + USB_HILOGI(MODULE_JS_NAPI, "AniCallBack enter 5 call returned %{public}d.", errCode); + }; + if (!SendEventToMainThread(task)) { + USB_HILOGI(MODULE_JS_NAPI, "SendEventToMainThread failed."); + } +} + +USBTransferAsyncContext* CreateTransferContext(const UsbDataTransferParams& transfer) +{ + auto context = new (std::nothrow) USBTransferAsyncContext(); + if (!context) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return nullptr; + } + context->pipe.SetBusNum(static_cast(transfer.devPipe.busNum)); + context->pipe.SetDevAddr(static_cast(transfer.devPipe.devAddress)); + context->flags = transfer.flags; + context->endpoint = transfer.endpoint; + context->type = transfer.type; + context->timeOut = transfer.timeout; + context->length = transfer.length; + context->numIsoPackets = transfer.isoPacketCount; + return context; +} + +bool ExtractBufferData(USBTransferAsyncContext* context, ani_object array_obj) +{ + ani_ref buffer; + ani_env* env = ::taihe::get_env(); + ani_vm* vm = nullptr; + if (env->GetVM(&vm) != ANI_OK || + env->Object_GetFieldByName_Ref(array_obj, "buffer", &buffer) != ANI_OK) { + return false; + } + void* data; + size_t size; + if (env->ArrayBuffer_GetInfo(static_cast(buffer), &data, &size) != ANI_OK) { + return false; + } + context->vm = vm; + context->buffer = static_cast(data); + context->bufferLength = size; + return true; +} + +bool SetupCallback(USBTransferAsyncContext* context, ani_object callbackObj) +{ + ani_ref callback; + ani_env* env = ::taihe::get_env(); + return env->GlobalReference_Create(callbackObj, &callback) == ANI_OK && + (context->callbackRef = reinterpret_cast(callback)); +} + +OHOS::HDI::Usb::V1_2::USBTransferInfo PrepareTransferInfo( + const UsbDataTransferParams& transfer, USBTransferAsyncContext* context) +{ + OHOS::HDI::Usb::V1_2::USBTransferInfo obj; + obj.endpoint = transfer.endpoint; + obj.type = transfer.type; + obj.timeOut = transfer.timeout; + obj.length = transfer.length; + obj.numIsoPackets = transfer.isoPacketCount; + obj.userData = reinterpret_cast(context); + return obj; +} + +static void TransferCompleteCallback( + const OHOS::USB::TransferCallbackInfo& info, + const std::vector& isoInfo, + uint64_t userData) +{ + USBTransferAsyncContext* context = reinterpret_cast(userData); + AniCallBack(context, info, isoInfo); +} + +void usbSubmitTransfer(UsbDataTransferParams const &transfer) +{ + USB_HILOGE(MODULE_JS_NAPI, "SubmitTransfer enter"); + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return; + } + auto context = CreateTransferContext(transfer); + if (!context) { + return; + } + if (!ExtractBufferData(context, reinterpret_cast(transfer.buffer)) || + !SetupCallback(context, reinterpret_cast(transfer.callback))) { + delete context; + return; + } + auto transferInfo = PrepareTransferInfo(transfer, context); + if (!CreateAndWriteAshmem(context, transferInfo)) { + delete context; + return; + } + USB_HILOGE(MODULE_JS_NAPI, "CreateAndWriteAshmem OK."); + int32_t ret = context->pipe.UsbSubmitTransfer(transferInfo, TransferCompleteCallback, context->ashmem); + USB_HILOGE(MODULE_JS_NAPI, "usbSubmitTransfer ret: %{public}d", ret); + if (ret != OHOS::USB::UEC_OK) { + context->ashmem->CloseAshmem(); + delete context; + ThrowBusinessError(UsbSubmitTransferErrorCode(ret), ""); + } + USB_HILOGE(MODULE_JS_NAPI, "usbSubmitTransfer fin."); +} + +void usbCancelTransfer(UsbDataTransferParams const &transfer) +{ + OHOS::USB::USBDevicePipe nativePipe; + nativePipe.SetBusNum(static_cast(transfer.devPipe.busNum)); + nativePipe.SetDevAddr(static_cast(transfer.devPipe.devAddress)); + int32_t endpoint = transfer.endpoint; + int32_t ret = nativePipe.UsbCancelTransfer(endpoint); + if (ret != OHOS::USB::UEC_OK) { + ret = UsbSubmitTransferErrorCode(ret); + ThrowBusinessError(ret, ""); + } +} + +bool resetUsbDevice(::ohos::usbManager::USBDevicePipe const& pipe) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, "Capability not supported."); + } + OHOS::USB::USBDevicePipe pipe_tmp = ConvertUSBDevicePipe(pipe); + int32_t ret = g_usbClient.ResetDevice(pipe_tmp); + if (ret == OHOS::USB::UEC_OK) { + } else if (ret == HDF_DEV_ERR_NO_DEVICE || ret == OHOS::USB::UEC_INTERFACE_NAME_NOT_FOUND) { + ThrowBusinessError(USB_SUBMIT_TRANSFER_NO_DEVICE_ERROR, + "BusinessError 14400008:No such device (it may have been disconnected)."); + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED) { + ThrowBusinessError(UEC_COMMON_HAS_NO_RIGHT, "No permission."); + } else if (ret == OHOS::USB::USB_RIGHT_FAILURE) { + ThrowBusinessError(USB_DEVICE_PIPE_CHECK_ERROR, "Check devicePipe failed."); + } else if (ret == OHOS::USB::UEC_SERVICE_INVALID_VALUE) { + ThrowBusinessError(UEC_COMMON_SERVICE_EXCEPTION, + "BusinessError 14400004:Service exception. Possible causes:No accessory is plugged in."); + } else { + ThrowBusinessError(USB_SUBMIT_TRANSFER_OTHER_ERROR, "BusinessError 14400010:Other USB error."); + } + bool success = (ret == OHOS::USB::UEC_OK); + return success; +} + +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_getDevices(getDevices); +TH_EXPORT_CPP_API_connectDevice(connectDevice); +TH_EXPORT_CPP_API_hasRight(hasRight); +TH_EXPORT_CPP_API_requestRightSync(requestRightSync); +TH_EXPORT_CPP_API_removeRight(removeRight); +TH_EXPORT_CPP_API_addDeviceAccessRight(addDeviceAccessRight); +TH_EXPORT_CPP_API_getFunctionsFromString(getFunctionsFromString); +TH_EXPORT_CPP_API_getStringFromFunctions(getStringFromFunctions); +TH_EXPORT_CPP_API_setDeviceFunctionsSync(setDeviceFunctionsSync); +TH_EXPORT_CPP_API_getDeviceFunctions(getDeviceFunctions); +TH_EXPORT_CPP_API_getPortList(getPortList); +TH_EXPORT_CPP_API_getPortSupportModes(getPortSupportModes); +TH_EXPORT_CPP_API_setPortRoleTypesSync(setPortRoleTypesSync); +TH_EXPORT_CPP_API_addAccessoryRight(addAccessoryRight); +TH_EXPORT_CPP_API_claimInterface(claimInterface); +TH_EXPORT_CPP_API_releaseInterface(releaseInterface); +TH_EXPORT_CPP_API_setConfiguration(setConfiguration); +TH_EXPORT_CPP_API_setInterface(setInterface); +TH_EXPORT_CPP_API_getRawDescriptor(getRawDescriptor); +TH_EXPORT_CPP_API_getFileDescriptor(getFileDescriptor); +TH_EXPORT_CPP_API_usbControlTransferSync(usbControlTransferSync); +TH_EXPORT_CPP_API_bulkTransferSync(bulkTransferSync); +TH_EXPORT_CPP_API_closePipe(closePipe); +TH_EXPORT_CPP_API_hasAccessoryRight(hasAccessoryRight); +TH_EXPORT_CPP_API_requestAccessoryRightSync(requestAccessoryRightSync); +TH_EXPORT_CPP_API_cancelAccessoryRight(cancelAccessoryRight); +TH_EXPORT_CPP_API_getAccessoryList(getAccessoryList); +TH_EXPORT_CPP_API_openAccessory(openAccessory); +TH_EXPORT_CPP_API_closeAccessory(closeAccessory); +TH_EXPORT_CPP_API_usbSubmitTransfer(usbSubmitTransfer); +TH_EXPORT_CPP_API_usbCancelTransfer(usbCancelTransfer); +TH_EXPORT_CPP_API_resetUsbDevice(resetUsbDevice); +// NOLINTEND diff --git a/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.serial.impl.cpp b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.serial.impl.cpp new file mode 100644 index 00000000..d278da4b --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.serial.impl.cpp @@ -0,0 +1,488 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 "ohos.usbManager.serial.impl.hpp" +#include "ohos.usbManager.serial.proj.hpp" +#include "stdexcept" +#include "taihe/runtime.hpp" + +#include "hilog_wrapper.h" +#include "usb_errors.h" +#include "usb_serial_type.h" +#include "usb_srv_client.h" + +using namespace OHOS; +using namespace OHOS::USB; +using namespace ohos::usbManager::serial; +using namespace taihe; + +namespace { +// To be implemented. + +static UsbSrvClient &g_usbClient = UsbSrvClient::GetInstance(); + +const int32_t ERROR = -1; +enum SerialTaiheErrCode : int32_t { + SYSPARAM_INVALID_INPUT = 401, + SERIAL_SYSAPI_NOPERMISSION_CALL = 201, + SERIAL_SYSAPI_PERMISSION_DENIED = 202, + SERIAL_SERVICE_ABNORMAL = 31400001, + SERIAL_INTERFACE_PERMISSION_DENIED = 31400002, + SERIAL_PORT_NOT_EXIST = 31400003, + SERIAL_PORT_OCCUPIED = 31400004, + SERIAL_PORT_NOT_OPEN = 31400005, + SERIAL_TIMED_OUT = 31400006, + SERIAL_IO_EXCEPTION = 31400007, + UEC_COMMON_RIGHT_DATABASE_ERROR = 14400005, +}; + +int32_t ErrorCodeConversion(int32_t value) +{ + static const std::map errorMap = { + {UEC_SERVICE_PERMISSION_DENIED_SYSAPI, SERIAL_SYSAPI_PERMISSION_DENIED }, + {UEC_SERVICE_PERMISSION_DENIED, SERIAL_INTERFACE_PERMISSION_DENIED}, + {UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED, SERIAL_SYSAPI_NOPERMISSION_CALL }, + {UEC_SERIAL_PORT_REPEAT_OPEN, SERIAL_PORT_OCCUPIED }, + {UEC_SERIAL_PORT_REPEAT_CLOSE, SERIAL_PORT_OCCUPIED }, + {UEC_SERIAL_PORT_OCCUPIED, SERIAL_PORT_OCCUPIED }, + {UEC_SERIAL_DEVICENOTOPEN, SERIAL_PORT_NOT_OPEN }, + {UEC_SERIAL_PORT_NOT_OPEN, SERIAL_PORT_NOT_OPEN }, + {UEC_INTERFACE_TIMED_OUT, SERIAL_TIMED_OUT }, + {UEC_SERIAL_IO_EXCEPTION, SERIAL_IO_EXCEPTION }, + {UEC_SERIAL_PORT_NOT_EXIST, SERIAL_PORT_NOT_EXIST }, + {UEC_SERIAL_DATEBASE_ERROR, UEC_COMMON_RIGHT_DATABASE_ERROR } + }; + auto it = errorMap.find(value); + if (it != errorMap.end()) { + return it->second; + } + return SERIAL_SERVICE_ABNORMAL; +} + +constexpr uint32_t MAX_READ_BUF_SIZE = 8192; +constexpr uint32_t MAX_WRITE_BUF_SIZE = 128000; + +constexpr uint32_t MAX_ATTRIBUTE_TYPE = 4; +enum AttributeType : uint32_t { + BAUDRATE = 0, + DATABITS = 1, + PARITY = 2, + STOPBITS = 3, +}; + +inline bool CheckAndThrowOnError(bool assertion, int errCode, const std::string &errMsg) +{ + if (!assertion) { + USB_HILOGI(MODULE_USB_INNERKIT, "Throw out ErrCode: [%{public}d], Msg: [%{public}s]", errCode, errMsg.c_str()); + taihe::set_business_error(errCode, errMsg.c_str()); + return false; + } + return true; +} + +array GetPortList() +{ + USB_HILOGI(MODULE_USB_INNERKIT, "GetPortList start."); + std::vector portIds; + std::vector tempPortList; + int32_t ret = g_usbClient.SerialGetPortList(portIds); + if (ret < 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "GetPortList failed, ErrCode: %{public}d", ret); + array portList(tempPortList); + return portList; + } + for (const auto &port : portIds) { + SerialPort serialPort {.portId = static_cast(port.portId_), + .deviceName = std::to_string(port.busNum_) + "-" + std::to_string(port.devAddr_)}; + tempPortList.push_back(serialPort); + } + USB_HILOGI( + MODULE_USB_INNERKIT, "GetPortList finish. ErrCode: %{public}d, size: %{public}d", ret, tempPortList.size()); + array portList(tempPortList); + return portList; +} + +bool HasSerialRight(double portId) +{ + USB_HILOGI(MODULE_USB_INNERKIT, "HasSerialRight start."); + int32_t port = static_cast(portId); + if (!CheckAndThrowOnError((port >= 0), SYSPARAM_INVALID_INPUT, "HasSerialRight failed.")) { + USB_HILOGE(MODULE_USB_INNERKIT, "HasSerialRight failed, invalid portId [%{public}d]", port); + return false; + } + bool hasRight = false; + int32_t ret = g_usbClient.HasSerialRight(port, hasRight); + CheckAndThrowOnError((ret == 0), ErrorCodeConversion(ret), "HasSerialRight failed."); + USB_HILOGI(MODULE_USB_INNERKIT, "HasSerialRight finish. ErrCode: %{public}d, ret: %{public}d", ret, hasRight); + return hasRight; +} + +bool RequestSerialRight(double portId) +{ + USB_HILOGI(MODULE_USB_INNERKIT, "RequestSerialRight start."); + int32_t port = static_cast(portId); + if (!CheckAndThrowOnError((port >= 0), SYSPARAM_INVALID_INPUT, "RequestSerialRight failed.")) { + USB_HILOGE(MODULE_USB_INNERKIT, "RequestSerialRight failed, invalid portId [%{public}d]", port); + return false; + } + bool hasRight = false; + int32_t ret = g_usbClient.RequestSerialRight(port, hasRight); + CheckAndThrowOnError((ret == 0), ErrorCodeConversion(ret), "RequestSerialRight failed."); + USB_HILOGI( + MODULE_USB_INNERKIT, "RequestSerialRight finish. ErrCode: %{public}d, ret: %{public}d", ret, hasRight); + return hasRight; +} + +void AddSerialRight(double tokenId, double portId) +{ + USB_HILOGI(MODULE_USB_INNERKIT, "AddSerialRight start."); + int32_t token = static_cast(tokenId); + int32_t port = static_cast(portId); + if (!CheckAndThrowOnError((token > 0), SYSPARAM_INVALID_INPUT, "AddSerialRight failed.")) { + USB_HILOGI(MODULE_USB_INNERKIT, "AddSerialRight failed, invalid tockenId [%{public}d]", token); + return; + } + if (!CheckAndThrowOnError((port >= 0), SYSPARAM_INVALID_INPUT, "AddSerialRight failed.")) { + USB_HILOGI(MODULE_USB_INNERKIT, "AddSerialRight failed, invalid portId [%{public}d]", port); + return; + } + int32_t ret = g_usbClient.AddSerialRight(tokenId, port); + CheckAndThrowOnError((ret == 0), ErrorCodeConversion(ret), "AddSerialRight failed."); + USB_HILOGI(MODULE_USB_INNERKIT, "AddSerialRight finish. ErrCode: %{public}d", ret); +} + +void CancelSerialRight(double portId) +{ + USB_HILOGI(MODULE_USB_INNERKIT, "CancelSerialRight start."); + int32_t port = static_cast(portId); + if (!CheckAndThrowOnError((port >= 0), SYSPARAM_INVALID_INPUT, "CancelSerialRight failed.")) { + USB_HILOGI(MODULE_USB_INNERKIT, "CancelSerialRight failed, invalid portId [%{public}d]", port); + return; + } + int32_t ret = g_usbClient.CancelSerialRight(port); + CheckAndThrowOnError((ret == 0), ErrorCodeConversion(ret), "CancelSerialRight failed."); + USB_HILOGI(MODULE_USB_INNERKIT, "CancelSerialRight finish. ErrCode: %{public}d", ret); +} + +void OpenSerial(double portId) +{ + USB_HILOGI(MODULE_USB_INNERKIT, "OpenSerial start."); + int32_t port = static_cast(portId); + if (!CheckAndThrowOnError((port >= 0), SYSPARAM_INVALID_INPUT, "OpenSerial failed.")) { + USB_HILOGI(MODULE_USB_INNERKIT, "OpenSerial failed, invalid portId [%{public}d]", port); + return; + } + int ret = g_usbClient.SerialOpen(port); + CheckAndThrowOnError((ret == 0), ErrorCodeConversion(ret), "OpenSerial failed."); + USB_HILOGI(MODULE_USB_INNERKIT, "OpenSerial finish. ErrCode: %{public}d", ret); +} + +void CloseSerial(double portId) +{ + USB_HILOGI(MODULE_USB_INNERKIT, "CloseSerial start."); + int32_t port = static_cast(portId); + if (!CheckAndThrowOnError((port >= 0), SYSPARAM_INVALID_INPUT, "CloseSerial failed.")) { + USB_HILOGI(MODULE_USB_INNERKIT, "CloseSerial failed, invalid portId [%{public}d]", port); + return; + } + int ret = g_usbClient.SerialClose(port); + CheckAndThrowOnError((ret == 0), ErrorCodeConversion(ret), "CloseSerial failed."); + USB_HILOGI(MODULE_USB_INNERKIT, "CloseSerial finish. ErrCode: %{public}d", ret); +} + +uint32_t GetAttributeValueByBaudRateKey(BaudRates::key_t key) +{ + BaudRates baudRate(key); + return baudRate.get_value(); +} + +uint8_t GetAttributeValueByDataBitsKey(DataBits::key_t key) +{ + DataBits dataBit(key); + return dataBit.get_value(); +} + +uint8_t GetAttributeValueByParityKey(Parity::key_t key) +{ + Parity parity(key); + return parity.get_value(); +} + +uint8_t GetAttributeValueByStopBitsKey(StopBits::key_t key) +{ + StopBits stopBit(key); + return stopBit.get_value(); +} + +void SerialAttributeToTaihe(const UsbSerialAttr serialAttribute, SerialAttribute &taiheSerialAttribute) +{ + for (uint32_t i = 0; i < MAX_ATTRIBUTE_TYPE; i++) { + switch (i) { + case BAUDRATE: + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_50) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_50; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_75) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_75; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_110) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_110; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_134) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_134; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_150) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_150; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_200) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_200; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_300) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_300; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_600) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_600; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_1200) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_1200; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_1800) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_1800; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_2400) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_2400; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_4800) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_4800; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_9600) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_9600; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_19200) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_19200; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_38400) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_38400; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_57600) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_57600; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_115200) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_115200; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_230400) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_230400; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_460800) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_460800; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_500000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_500000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_576000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_576000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_921600) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_921600; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_1000000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_1000000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_1152000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_1152000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_1500000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_1500000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_2000000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_2000000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_2500000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_2500000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_3000000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_3000000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_3500000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_3500000; + if (GetAttributeValueByBaudRateKey(BaudRates::key_t::BAUDRATE_4000000) == serialAttribute.baudRate_) + taiheSerialAttribute.baudRate = BaudRates::key_t::BAUDRATE_4000000; + break; + case DATABITS: + if (GetAttributeValueByDataBitsKey(DataBits::key_t::DATABIT_8) == serialAttribute.dataBits_) + taiheSerialAttribute.dataBits = optional::make(DataBits(DataBits::key_t::DATABIT_8)); + if (GetAttributeValueByDataBitsKey(DataBits::key_t::DATABIT_7) == serialAttribute.dataBits_) + taiheSerialAttribute.dataBits = optional::make(DataBits(DataBits::key_t::DATABIT_7)); + if (GetAttributeValueByDataBitsKey(DataBits::key_t::DATABIT_6) == serialAttribute.dataBits_) + taiheSerialAttribute.dataBits = optional::make(DataBits(DataBits::key_t::DATABIT_6)); + if (GetAttributeValueByDataBitsKey(DataBits::key_t::DATABIT_5) == serialAttribute.dataBits_) + taiheSerialAttribute.dataBits = optional::make(DataBits(DataBits::key_t::DATABIT_5)); + if (GetAttributeValueByDataBitsKey(DataBits::key_t::DATABIT_4) == serialAttribute.dataBits_) + taiheSerialAttribute.dataBits = optional::make(DataBits(DataBits::key_t::DATABIT_4)); + break; + case PARITY: + if (GetAttributeValueByParityKey(Parity::key_t::PARITY_NONE) == serialAttribute.parity_) + taiheSerialAttribute.parity = optional::make(Parity(Parity::key_t::PARITY_NONE)); + if (GetAttributeValueByParityKey(Parity::key_t::PARITY_ODD) == serialAttribute.parity_) + taiheSerialAttribute.parity = optional::make(Parity(Parity::key_t::PARITY_ODD)); + if (GetAttributeValueByParityKey(Parity::key_t::PARITY_EVEN) == serialAttribute.parity_) + taiheSerialAttribute.parity = optional::make(Parity(Parity::key_t::PARITY_EVEN)); + if (GetAttributeValueByParityKey(Parity::key_t::PARITY_MARK) == serialAttribute.parity_) + taiheSerialAttribute.parity = optional::make(Parity(Parity::key_t::PARITY_MARK)); + if (GetAttributeValueByParityKey(Parity::key_t::PARITY_SPACE) == serialAttribute.parity_) + taiheSerialAttribute.parity = optional::make(Parity(Parity::key_t::PARITY_SPACE)); + break; + case STOPBITS: + if (GetAttributeValueByStopBitsKey(StopBits::key_t::STOPBIT_1) == serialAttribute.stopBits_) + taiheSerialAttribute.stopBits = optional::make(StopBits(StopBits::key_t::STOPBIT_1)); + if (GetAttributeValueByStopBitsKey(StopBits::key_t::STOPBIT_1P5) == serialAttribute.stopBits_) + taiheSerialAttribute.stopBits = optional::make(StopBits(StopBits::key_t::STOPBIT_1P5)); + if (GetAttributeValueByStopBitsKey(StopBits::key_t::STOPBIT_2) == serialAttribute.stopBits_) + taiheSerialAttribute.stopBits = optional::make(StopBits(StopBits::key_t::STOPBIT_2)); + break; + default: + break; + } + } +} + +::ohos::usbManager::serial::SerialAttribute GetAttribute(double portId) +{ + int32_t iportId = static_cast(portId); + USB_HILOGI(MODULE_USB_INNERKIT, "getAttribute start. portId: %{public}d", iportId); + SerialAttribute taiheSerialAttribute = {BaudRates::key_t::BAUDRATE_50}; + if (iportId < 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "portId is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "portId is invalid!"); + return taiheSerialAttribute; + } + + UsbSerialAttr serialAttribute; + int32_t ret = g_usbClient.SerialGetAttribute(iportId, serialAttribute); + if (ret != 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "Failed to get attribute. errorCode: %{public}d", ErrorCodeConversion(ret)); + set_business_error(ErrorCodeConversion(ret), "Failed to get attribute!"); + return taiheSerialAttribute; + } + SerialAttributeToTaihe(serialAttribute, taiheSerialAttribute); + USB_HILOGI(MODULE_USB_INNERKIT, "getAttribute finish, status: %{public}d", ret); + return taiheSerialAttribute; +} + +void SetAttribute(double portId, ::ohos::usbManager::serial::SerialAttribute const& attribute) +{ + int32_t iportId = static_cast(portId); + USB_HILOGI(MODULE_USB_INNERKIT, "setAttribute start. portId: %{public}d", iportId); + if (iportId < 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "portId is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "portId is invalid!"); + return; + } + + UsbSerialAttr serialAttribute; + serialAttribute.baudRate_ = attribute.baudRate.get_value(); + + if (attribute.dataBits.has_value()) { + serialAttribute.dataBits_ = attribute.dataBits.value(); + } else { + USB_HILOGE(MODULE_USB_INNERKIT, "attribute.dataBits is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "attribute.dataBits is invalid!"); + return; + } + + if (attribute.parity.has_value()) { + serialAttribute.parity_ = attribute.parity.value(); + } else { + USB_HILOGE(MODULE_USB_INNERKIT, "attribute.parity is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "attribute.parity is invalid!"); + return; + } + + if (attribute.stopBits.has_value()) { + serialAttribute.stopBits_ = attribute.stopBits.value(); + } else { + USB_HILOGE(MODULE_USB_INNERKIT, "attribute.stopBits is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "attribute.stopBits is invalid!"); + return; + } + + int ret = g_usbClient.SerialSetAttribute(iportId, serialAttribute); + if (ret != 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "Failed to set attribute. errorCode: %{public}d", ErrorCodeConversion(ret)); + set_business_error(ErrorCodeConversion(ret), "Failed to set attribute!"); + } + USB_HILOGI(MODULE_USB_INNERKIT, "setAttribute finish, status: %{public}d", ret); +} + +double ReadSync(double portId, ::taihe::array_view buffer, ::taihe::optional_view timeout) +{ + int32_t iportId = static_cast(portId); + USB_HILOGI(MODULE_USB_INNERKIT, "readSync start. portId: %{public}d", iportId); + if (iportId < 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "portId is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "portId is invalid!"); + return ERROR; + } + + if (buffer.size() > MAX_READ_BUF_SIZE) { + USB_HILOGE(MODULE_USB_INNERKIT, "buffer size > 8192 byte!"); + set_business_error(SYSPARAM_INVALID_INPUT, "buffer size > 8192 byte!"); + return ERROR; + } + + std::vector bufferData(buffer.size(), 0); + uint32_t actualSize = 0; + uint32_t utimeout = 0; + if (timeout.has_value()) { + utimeout = static_cast(timeout.value()); + } else { + USB_HILOGE(MODULE_USB_INNERKIT, "timeout is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "timeout is invalid!"); + return ERROR; + } + int32_t ret = g_usbClient.SerialRead(iportId, bufferData, buffer.size(), actualSize, utimeout); + if (ret != 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "readSync Failed. errorCode: %{public}d", ErrorCodeConversion(ret)); + set_business_error(ErrorCodeConversion(ret), "readSync Failed!"); + return ERROR; + } + buffer = bufferData; + USB_HILOGI(MODULE_USB_INNERKIT, "readSync finish, status: %{public}d", ret); + return actualSize; +} + +double WriteSync(double portId, ::taihe::array_view buffer, ::taihe::optional_view timeout) +{ + int32_t iportId = static_cast(portId); + USB_HILOGI(MODULE_USB_INNERKIT, "writeSync start. portId: %{public}d", iportId); + if (iportId < 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "portId is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "portId is invalid!"); + return ERROR; + } + + if (buffer.size() > MAX_WRITE_BUF_SIZE) { + USB_HILOGE(MODULE_USB_INNERKIT, "buffer size > 128kb!"); + set_business_error(SYSPARAM_INVALID_INPUT, "buffer size > 128kb!"); + return ERROR; + } + + uint32_t actualSize = 0; + std::vector bufferVector(buffer.data(), buffer.data() + buffer.size()); + uint32_t utimeout = 0; + if (timeout.has_value()) { + utimeout = static_cast(timeout.value()); + } else { + USB_HILOGE(MODULE_USB_INNERKIT, "timeout is invalid!"); + set_business_error(SYSPARAM_INVALID_INPUT, "timeout is invalid!"); + return ERROR; + } + int32_t ret = g_usbClient.SerialWrite(iportId, bufferVector, buffer.size(), actualSize, utimeout); + if (ret != 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "writeSync Failed. errorCode: %{public}d", ErrorCodeConversion(ret)); + set_business_error(ErrorCodeConversion(ret), "readSync Failed!"); + return ERROR; + } + USB_HILOGI(MODULE_USB_INNERKIT, "writeSync finish, status: %{public}d", ret); + return actualSize; +} +} // namespace + +// Since these macros are auto-generate, lint will cause false positive. +// NOLINTBEGIN +TH_EXPORT_CPP_API_getPortList(GetPortList); +TH_EXPORT_CPP_API_hasSerialRight(HasSerialRight); +TH_EXPORT_CPP_API_requestSerialRightSync(RequestSerialRight); +TH_EXPORT_CPP_API_addSerialRight(AddSerialRight); +TH_EXPORT_CPP_API_cancelSerialRight(CancelSerialRight); +TH_EXPORT_CPP_API_open(OpenSerial); +TH_EXPORT_CPP_API_close(CloseSerial); +TH_EXPORT_CPP_API_getAttribute(GetAttribute); +TH_EXPORT_CPP_API_setAttribute(SetAttribute); +TH_EXPORT_CPP_API_readSync(ReadSync); +TH_EXPORT_CPP_API_writeSync(WriteSync); +// NOLINTEND diff --git a/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.usbManager.impl.cpp b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.usbManager.impl.cpp deleted file mode 100644 index 4ff09de9..00000000 --- a/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.usbManager.impl.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright (C) 2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT 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 "ohos.usbManager.usbManager.proj.hpp" -#include "ohos.usbManager.usbManager.impl.hpp" -#include "taihe/runtime.hpp" -#include "stdexcept" -#include "usb_srv_client.h" - -using namespace taihe; -using namespace ohos::usbManager::usbManager; - -namespace { -constexpr int32_t CAPACITY_NOT_SUPPORT = 801; - -static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance(); - -enum UsbManagerFeature { - FEATURE_HOST = 0, - FEATURE_DEVICE = 1, - FEATURE_PORT = 2, -}; - -static bool HasFeature(UsbManagerFeature feature) -{ - switch (feature) { - case FEATURE_HOST: -#ifndef USB_MANAGER_FEATURE_HOST - return false; -#else - return true; -#endif // USB_MANAGER_FEATURE_HOST - case FEATURE_DEVICE: -#ifndef USB_MANAGER_FEATURE_DEVICE - return false; -#else - return true; -#endif // USB_MANAGER_FEATURE_DEVICE - case FEATURE_PORT: -#ifndef USB_MANAGER_FEATURE_PORT - return false; -#else - return true; -#endif // USB_MANAGER_FEATURE_PORT - default:; - } - return false; -} - -static ohos::usbManager::usbManager::USBEndpoint ParseToUSBEndpoint(const OHOS::USB::USBEndpoint &usbEndpoint) -{ - auto directionKey = usbEndpoint.GetDirection() == OHOS::USB::USB_ENDPOINT_DIR_OUT - ? ohos::usbManager::usbManager::USBRequestDirection::key_t::USB_REQUEST_DIR_TO_DEVICE - : ohos::usbManager::usbManager::USBRequestDirection::key_t::USB_REQUEST_DIR_FROM_DEVICE; - return { - .address = usbEndpoint.GetAddress(), - .attributes = usbEndpoint.GetAttributes(), - .interval = usbEndpoint.GetInterval(), - .maxPacketSize = usbEndpoint.GetMaxPacketSize(), - .direction = ohos::usbManager::usbManager::USBRequestDirection(directionKey), - .endpointAddr = usbEndpoint.GetEndpointNumber(), - .type = usbEndpoint.GetType(), - .interfaceId = usbEndpoint.GetInterfaceId() - }; -} - -static ohos::usbManager::usbManager::USBInterface ParseToUSBInterface(OHOS::USB::UsbInterface &usbInterface) -{ - std::vector endpoints; - for (const auto &endpoint : usbInterface.GetEndpoints()) { - endpoints.push_back(ParseToUSBEndpoint(endpoint)); - } - return { - .id = usbInterface.GetId(), - .protocol = usbInterface.GetProtocol(), - .clazz = usbInterface.GetClass(), - .subClass = usbInterface.GetSubClass(), - .alternateSetting = usbInterface.GetAlternateSetting(), - .name = usbInterface.GetName(), - .endpoints = array(endpoints) - }; -} - -static ohos::usbManager::usbManager::USBConfiguration ParseToUSBConfiguration(OHOS::USB::USBConfig &usbConfig) -{ - std::vector interfaces; - for (auto &interface : usbConfig.GetInterfaces()) { - interfaces.push_back(ParseToUSBInterface(interface)); - } - return { - .id = usbConfig.GetId(), - .attributes = usbConfig.GetAttributes(), - .maxPower = usbConfig.GetMaxPower(), - .name = usbConfig.GetName(), - .isRemoteWakeup = usbConfig.IsRemoteWakeup(), - .isSelfPowered = usbConfig.IsSelfPowered(), - .interfaces = array(interfaces) - }; -} - -static ohos::usbManager::usbManager::USBDevice ParseToUSBDevice(OHOS::USB::UsbDevice &usbDevice) -{ - std::vector configs; - for (auto &config : usbDevice.GetConfigs()) { - configs.push_back(ParseToUSBConfiguration(config)); - } - return { - .busNum = usbDevice.GetBusNum(), - .devAddress = usbDevice.GetDevAddr(), - .serial = usbDevice.GetmSerial(), - .name = usbDevice.GetName(), - .manufacturerName = usbDevice.GetManufacturerName(), - .productName = usbDevice.GetProductName(), - .version = usbDevice.GetVersion(), - .vendorId = usbDevice.GetVendorId(), - .productId = usbDevice.GetProductId(), - .clazz = usbDevice.GetClass(), - .subClass = usbDevice.GetSubclass(), - .protocol = usbDevice.GetProtocol(), - .configs = array(configs) - }; -} - -array getDevices() -{ - std::vector res; - if (!HasFeature(FEATURE_HOST)) { - set_business_error(CAPACITY_NOT_SUPPORT, ""); - return array(res); - } - std::vector deviceList; - auto ret = g_usbClient.GetDevices(deviceList); - if (ret != 0) { - return array(res); - } - for (auto &usbDevice : deviceList) { - res.push_back(ParseToUSBDevice(usbDevice)); - } - return array(res); -} -} // namespace - -TH_EXPORT_CPP_API_getDevices(getDevices); diff --git a/frameworks/ets/taihe/usb_manager/test/unittest/BUILD copy.gn b/frameworks/ets/taihe/usb_manager/test/unittest/BUILD copy.gn new file mode 100644 index 00000000..518acf73 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/unittest/BUILD copy.gn @@ -0,0 +1,41 @@ +import("//build/test.gni") +import("//build/ohos/taihe_idl/taihe.gni") +import("../../../../../../batterystats.gni") + +module_output_path = "battery_statistics/battery_statistics" + +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + "${taihe_generated_file_path}/include", + "${taihe_toolchain_path}/include" + ] +} + +ohos_unittest("stats_taihe_native_test") { + module_out_path = module_output_path + + sources = [ + "stats_ani_constructor_test.cpp", + "stats_taihe_native_test.cpp", + "../../src/ohos.batteryStatistics.impl.cpp", + ] + + configs = [ + ":module_private_config", + "${batterystats_utils_path}:coverage_flags", + ] + + deps = [ + "${batterystats_frameworks_path}/ets/taihe/battery_stats:batterystats_taihe_native", + "${batterystats_frameworks_path}/ets/taihe/battery_stats:run_taihe", + "${batterystats_inner_api}:batterystats_client", + "${batterystats_utils_path}:batterystats_utils" + ] + + external_deps = [ + "googletest:gtest_main", + "runtime_core:ani", + ] +} diff --git a/frameworks/ets/taihe/usb_manager/test/unittest/BUILD.gn b/frameworks/ets/taihe/usb_manager/test/unittest/BUILD.gn new file mode 100644 index 00000000..03fe9645 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/unittest/BUILD.gn @@ -0,0 +1,46 @@ +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") +import("//base/usb/usb_manager/usbmgr.gni") + +module_output_path = "usb_manager/unittest" + +config("module_private_config") { + visibility = [ ":*" ] + + include_dirs = [ + # "${taihe_generated_file_path}/include", + # "${taihe_toolchain_path}/include" + "$taihe_file_path/out/usb/usb_manager/include" + ] +} + +ohos_unittest("stats_taihe_native_test") { + module_out_path = module_output_path + + sources = [ + "stats_ani_constructor_test.cpp", + "stats_taihe_native_test.cpp", + "stats_serial_taihe_native_test.cpp", + ] + + configs = [ + ":module_private_config", + # "${batterystats_utils_path}:coverage_flags", + ] + + deps = [ + # "${usb_manager_path}/framework/ets/taihe/usb_manager:usbManager_taihe", + # "${usb_manager_path}/framework/ets/taihe/usb_manager:usbmanager_etc", + "${usb_manager_path}/frameworks/ets/taihe/usb_manager:usb_manager_taihe_native", + # "${usb_manager_path}/framework/ets/taihe/usb_manager:usbmanager_serial_etc", + # "${}/ets/taihe/battery_stats:run_taihe", + # "${batterystats_inner_api}:batterystats_client", + # "${batterystats_utils_path}:batterystats_utils" + ] + + external_deps = [ + "googletest:gtest_main", + "runtime_core:ani", + ] +} diff --git a/frameworks/ets/taihe/usb_manager/test/unittest/stats_ani_constructor_test.cpp b/frameworks/ets/taihe/usb_manager/test/unittest/stats_ani_constructor_test.cpp new file mode 100644 index 00000000..f642e723 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/unittest/stats_ani_constructor_test.cpp @@ -0,0 +1,126 @@ +#include "gtest/gtest.h" +#include "ohos.usbManager.ani.hpp" +#include "ohos.usbManager.serial.ani.hpp" +#include "ani_vm.h" + +using namespace testing; +using namespace ohos::usbManager; + +class MockAniEnv { +public: + MOCK_METHOD(ani_status, RegisterModule, (const char* name, const ani_module_entry* entry)); +}; + +class MockAniVm { +public: + MOCK_METHOD(ani_status, GetEnv, (uint32_t version, ani_env** env)); +}; + +static ani_status MockUsbManagerRegister(ani_env* env) { + return static_cast(env)->RegisterModule("usbManager", nullptr); +} + +static ani_status MockUsbSerialRegister(ani_env* env) { + return static_cast(env)->RegisterModule("usbManager.serial", nullptr); +} + +#define ohos::usbManager::ANIRegister MockUsbManagerRegister +#define ohos::usbManager::serial::ANIRegister MockUsbSerialRegister + +class UsbAniInterfaceTest : public ::testing::Test { +protected: + void SetUp() override { + mockVm = new MockAniVm(); + mockEnv = new MockAniEnv(); + } + + void TearDown() override { + delete mockVm; + delete mockEnv; + } + + MockAniVm* mockVm = nullptr; + MockAniEnv* mockEnv = nullptr; +}; + +TEST_F(UsbAniInterfaceTest, AniInitializationSuccess) { + EXPECT_CALL(*mockVm, GetEnv(ANI_VERSION_1, _)) + .WillOnce(DoAll(SetArgPointee<1>(reinterpret_cast(mockEnv)), Return(ANI_OK))); + + EXPECT_CALL(*mockEnv, RegisterModule("usbManager", _)) + .WillOnce(Return(ANI_OK)); + EXPECT_CALL(*mockEnv, RegisterModule("usbManager.serial", _)) + .WillOnce(Return(ANI_OK)); + + uint32_t resultVersion = 0; + ani_status status = ANI_Constructor(reinterpret_cast(mockVm), &resultVersion); + + EXPECT_EQ(status, ANI_OK); + EXPECT_EQ(resultVersion, ANI_VERSION_1); +} + +TEST_F(UsbAniInterfaceTest, GetEnvFailure) { + EXPECT_CALL(*mockVm, GetEnv(ANI_VERSION_1, _)) + .WillOnce(Return(ANI_ERROR)); + + uint32_t resultVersion = 0; + ani_status status = ANI_Constructor(reinterpret_cast(mockVm), &resultVersion); + + EXPECT_EQ(status, ANI_ERROR); + EXPECT_EQ(resultVersion, 0); +} + +TEST_F(UsbAniInterfaceTest, UsbManagerRegisterFailure) { + EXPECT_CALL(*mockVm, GetEnv(ANI_VERSION_1, _)) + .WillOnce(DoAll(SetArgPointee<1>(reinterpret_cast(mockEnv)), Return(ANI_OK))); + + EXPECT_CALL(*mockEnv, RegisterModule("usbManager", _)) + .WillOnce(Return(ANI_ERROR)); + + uint32_t resultVersion = 0; + ani_status status = ANI_Constructor(reinterpret_cast(mockVm), &resultVersion); + + EXPECT_EQ(status, ANI_ERROR); + EXPECT_EQ(resultVersion, 0); +} + +TEST_F(UsbAniInterfaceTest, UsbSerialRegisterFailure) { + EXPECT_CALL(*mockVm, GetEnv(ANI_VERSION_1, _)) + .WillOnce(DoAll(SetArgPointee<1>(reinterpret_cast(mockEnv)), Return(ANI_OK))); + + EXPECT_CALL(*mockEnv, RegisterModule("usbManager", _)) + .WillOnce(Return(ANI_OK)); + EXPECT_CALL(*mockEnv, RegisterModule("usbManager.serial", _)) + .WillOnce(Return(ANI_ERROR)); + + uint32_t resultVersion = 0; + ani_status status = ANI_Constructor(reinterpret_cast(mockVm), &resultVersion); + + EXPECT_EQ(status, ANI_ERROR); + EXPECT_EQ(resultVersion, 0); +} + +TEST_F(UsbAniInterfaceTest, VersionCompatibility) { + EXPECT_CALL(*mockVm, GetEnv(ANI_VERSION_1, _)) + .WillOnce(DoAll(SetArgPointee<1>(reinterpret_cast(mockEnv)), Return(ANI_OK))); + + EXPECT_CALL(*mockEnv, RegisterModule("usbManager", _)) + .WillOnce(Return(ANI_OK)); + EXPECT_CALL(*mockEnv, RegisterModule("usbManager.serial", _)) + .WillOnce(Return(ANI_OK)); + + uint32_t resultVersion = 0; + ani_status status = ANI_Constructor(reinterpret_cast(mockVm), &resultVersion); + + EXPECT_EQ(status, ANI_OK); + EXPECT_EQ(resultVersion, ANI_VERSION_1); +} + +TEST_F(UsbAniInterfaceTest, NullPointerCheck) { + EXPECT_DEATH(ANI_Constructor(nullptr, nullptr), ""); +} + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/unittest/stats_serial_taihe_native_test.cpp b/frameworks/ets/taihe/usb_manager/test/unittest/stats_serial_taihe_native_test.cpp new file mode 100644 index 00000000..0e5ffa78 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/unittest/stats_serial_taihe_native_test.cpp @@ -0,0 +1,209 @@ +#include "gtest/gtest.h" +#include "ohos.usbManager.serial.impl.hpp" +#include "usb_srv_client.h" +#include "usb_serial_type.h" + +using namespace testing; +using namespace OHOS::USB; +using namespace ohos::usbManager::serial; + +class MockUsbSrvClient : public UsbSrvClient { +public: + MockUsbSrvClient() : UsbSrvClient() {} + + int32_t SerialGetPortList(std::vector &portIds) override { + if (mockGetPortListRet_) { + UsbSerialPort port; + port.portId_ = 1; + port.busNum_ = 1; + port.devAddr_ = 2; + portIds.push_back(port); + } + return mockGetPortListRet_; + } + + int32_t HasSerialRight(int32_t port, bool &hasRight) override { + hasRight = mockHasRight_; + return mockHasSerialRightRet_; + } + + int32_t RequestSerialRight(int32_t port, bool &hasRight) override { + hasRight = mockRequestRight_; + return mockRequestSerialRightRet_; + } + + int32_t AddSerialRight(double tokenId, int32_t port) override { + return mockAddSerialRightRet_; + } + + int32_t CancelSerialRight(int32_t port) override { + return mockCancelSerialRightRet_; + } + + int32_t SerialOpen(int32_t port) override { + return mockSerialOpenRet_; + } + + int32_t SerialClose(int32_t port) override { + return mockSerialCloseRet_; + } + + int32_t SerialGetAttribute(int32_t port, UsbSerialAttr &attr) override { + if (mockGetAttributeRet_) { + attr.baudRate_ = 9600; + attr.dataBits_ = 8; + attr.parity_ = 0; + attr.stopBits_ = 1; + } + return mockGetAttributeRet_; + } + + int32_t SerialSetAttribute(int32_t port, const UsbSerialAttr &attr) override { + return mockSetAttributeRet_; + } + + int32_t SerialRead(int32_t port, std::vector &buffer, uint32_t size, + uint32_t &actualSize, uint32_t timeout) override { + if (mockReadRet_) { + buffer = {0x01, 0x02, 0x03}; + actualSize = 3; + } + return mockReadRet_; + } + + int32_t SerialWrite(int32_t port, const std::vector &buffer, uint32_t size, + uint32_t &actualSize, uint32_t timeout) override { + actualSize = size; + return mockWriteRet_; + } + + int32_t mockGetPortListRet_ = 0; + bool mockHasRight_ = true; + int32_t mockHasSerialRightRet_ = 0; + bool mockRequestRight_ = true; + int32_t mockRequestSerialRightRet_ = 0; + int32_t mockAddSerialRightRet_ = 0; + int32_t mockCancelSerialRightRet_ = 0; + int32_t mockSerialOpenRet_ = 0; + int32_t mockSerialCloseRet_ = 0; + int32_t mockGetAttributeRet_ = 0; + int32_t mockSetAttributeRet_ = 0; + int32_t mockReadRet_ = 0; + int32_t mockWriteRet_ = 0; +}; + +class UsbSerialManagerTest : public ::testing::Test { +protected: + void SetUp() override { + originalClient_ = &g_usbClient; + g_usbClient = MockUsbSrvClient::GetInstance(); + mockClient_ = static_cast(&g_usbClient); + } + + void TearDown() override { + g_usbClient = originalClient_; + } + + MockUsbSrvClient* mockClient_ = nullptr; + UsbSrvClient* originalClient_ = nullptr; +}; + +TEST_F(UsbSerialManagerTest, GetPortListTest) { + mockClient_->mockGetPortListRet_ = 0; + auto ports = GetPortList(); + EXPECT_FALSE(ports.empty()); + EXPECT_EQ(ports[0].portId, 1.0); + EXPECT_EQ(ports[0].deviceName, "1-2"); + + mockClient_->mockGetPortListRet_ = -1; + ports = GetPortList(); + EXPECT_TRUE(ports.empty()); +} + +TEST_F(UsbSerialManagerTest, HasSerialRightTest) { + mockClient_->mockHasRight_ = true; + mockClient_->mockHasSerialRightRet_ = 0; + bool result = HasSerialRight(1); + EXPECT_TRUE(result); + + mockClient_->mockHasRight_ = false; + result = HasSerialRight(1); + EXPECT_FALSE(result); + + mockClient_->mockHasSerialRightRet_ = -1; + EXPECT_THROW(HasSerialRight(1), std::exception); +} + +TEST_F(UsbSerialManagerTest, RequestSerialRightTest) { + mockClient_->mockRequestRight_ = true; + mockClient_->mockRequestSerialRightRet_ = 0; + bool result = RequestSerialRight(1); + EXPECT_TRUE(result); + + mockClient_->mockRequestRight_ = false; + result = RequestSerialRight(1); + EXPECT_FALSE(result); +} + +TEST_F(UsbSerialManagerTest, OpenCloseSerialTest) { + mockClient_->mockSerialOpenRet_ = 0; + OpenSerial(1); + + mockClient_->mockSerialCloseRet_ = 0; + CloseSerial(1); + + mockClient_->mockSerialOpenRet_ = -1; + EXPECT_THROW(OpenSerial(1), std::exception); +} + +TEST_F(UsbSerialManagerTest, AttributeManagementTest) { + mockClient_->mockGetAttributeRet_ = 0; + auto attribute = GetAttribute(1); + EXPECT_EQ(attribute.baudRate.get_value(), BaudRates::key_t::BAUDRATE_9600); + EXPECT_TRUE(attribute.dataBits.has_value()); + EXPECT_EQ(attribute.dataBits.value().get_value(), 8); + + mockClient_->mockSetAttributeRet_ = 0; + SerialAttribute newAttr; + newAttr.baudRate = BaudRates::key_t::BAUDRATE_115200; + newAttr.dataBits = optional::make(DataBits(DataBits::key_t::DATABIT_8)); + newAttr.parity = optional::make(Parity(Parity::key_t::PARITY_NONE)); + newAttr.stopBits = optional::make(StopBits(StopBits::key_t::STOPBIT_1)); + SetAttribute(1, newAttr); +} + +TEST_F(UsbSerialManagerTest, DataTransferTest) { + mockClient_->mockReadRet_ = 0; + array_view readBuffer(3); + double bytesRead = ReadSync(1, readBuffer, optional_view::make(1000)); + EXPECT_EQ(bytesRead, 3); + EXPECT_EQ(readBuffer[0], 0x01); + + mockClient_->mockWriteRet_ = 0; + uint8_t writeData[] = {0xA1, 0xA2, 0xA3}; + array_view writeBuffer(writeData, 3); + double bytesWritten = WriteSync(1, writeBuffer, optional_view::make(1000)); + EXPECT_EQ(bytesWritten, 3); +} + +TEST_F(UsbSerialManagerTest, ErrorHandlingTest) { + EXPECT_THROW(GetPortList(), std::exception); + + mockClient_->mockHasSerialRightRet_ = UEC_SERVICE_PERMISSION_DENIED; + EXPECT_THROW(HasSerialRight(1), std::exception); +} + +TEST_F(UsbSerialManagerTest, BoundaryConditionsTest) { + uint8_t largeBuffer[MAX_READ_BUF_SIZE]; + array_view largeReadBuffer(largeBuffer, MAX_READ_BUF_SIZE); + ReadSync(1, largeReadBuffer, optional_view::make(1000)); + + uint8_t tooLargeBuffer[MAX_WRITE_BUF_SIZE + 1]; + array_view tooLargeWriteBuffer(tooLargeBuffer, MAX_WRITE_BUF_SIZE + 1); + EXPECT_THROW(WriteSync(1, tooLargeWriteBuffer, optional_view::make(1000)), std::exception); +} + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/unittest/stats_taihe_native_test.cpp b/frameworks/ets/taihe/usb_manager/test/unittest/stats_taihe_native_test.cpp new file mode 100644 index 00000000..441cd738 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/unittest/stats_taihe_native_test.cpp @@ -0,0 +1,246 @@ +#include "gtest/gtest.h" +#include "ohos.usbManager.impl.hpp" +#include "stats_log.h" +#include "usb_srv_client.h" +#include "v1_2/usb_types.h" + +using namespace testing; +using namespace OHOS::PowerMgr; +using namespace OHOS::USB; +using namespace ohos::usbManager; + +// 模拟UsbSrvClient实现 +class MockUsbSrvClient : public UsbSrvClient { +public: + MockUsbSrvClient() : UsbSrvClient() {} + + // 重写关键方法以便测试 + int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pipe) override { + if (mockOpenDeviceRet_) { + pipe.SetBusNum(1); + pipe.SetDevAddr(2); + return UEC_OK; + } + return mockOpenDeviceRet_; + } + + int32_t GetDevices(std::vector &deviceList) override { + if (mockGetDevicesRet_) { + UsbDevice device; + device.SetDevAddr(1); + deviceList.push_back(device); + } + return mockOpenDeviceRet_; + } + + bool HasRight(const std::string &deviceName) override { + return mockHasRight_; + } + + int32_t RequestRight(const std::string &deviceName) override { + return mockRequestRightRet_; + } + + // 其他方法模拟... + + // 测试用模拟参数 + int32_t mockOpenDeviceRet_ = UEC_OK; + int32_t mockGetDevicesRet_ = UEC_OK; + bool mockHasRight_ = true; + int32_t mockRequestRightRet_ = UEC_OK; +}; + +// 测试夹具,设置测试环境 +class UsbManagerTest : public ::testing::Test { +protected: + void SetUp() override { + // 保存原始实例并替换为模拟实例 + originalClient_ = &g_usbClient; + g_usbClient = MockUsbSrvClient::GetInstance(); + mockClient_ = static_cast(&g_usbClient); + + // 重置全局状态 + g_accFd = 0; + } + + void TearDown() override { + // 恢复原始实例 + g_usbClient = originalClient_; + } + + MockUsbSrvClient* mockClient_ = nullptr; + UsbSrvClient* originalClient_ = nullptr; +}; + +// --------------------- USB设备发现与连接测试 --------------------- +TEST_F(UsbManagerTest, GetDevicesTest) { + // 测试正常获取设备 + mockClient_->mockGetDevicesRet_ = UEC_OK; + auto devices = getDevices(); + EXPECT_FALSE(devices.empty()); + + // 测试获取设备失败 + mockClient_->mockGetDevicesRet_ = UEC_SERVICE_EXCEPTION; + devices = getDevices(); + EXPECT_TRUE(devices.empty()); +} + +TEST_F(UsbManagerTest, ConnectDeviceTest) { + // 准备测试数据 + USBDevice device; + device.devAddress = 1; + device.busNum = 1; + + // 测试连接成功 + mockClient_->mockOpenDeviceRet_ = UEC_OK; + auto pipe = connectDevice(device); + EXPECT_NE(pipe.busNum, 0); + EXPECT_NE(pipe.devAddress, 0); + + // 测试权限拒绝 + mockClient_->mockOpenDeviceRet_ = UEC_INTERFACE_PERMISSION_DENIED; + pipe = connectDevice(device); + EXPECT_EQ(pipe.busNum, 0); + EXPECT_EQ(pipe.devAddress, 0); +} + +// --------------------- 权限管理测试 --------------------- +TEST_F(UsbManagerTest, HasRightTest) { + // 测试有权限 + mockClient_->mockHasRight_ = true; + bool result = hasRight("testDevice"); + EXPECT_TRUE(result); + + // 测试无权限 + mockClient_->mockHasRight_ = false; + result = hasRight("testDevice"); + EXPECT_FALSE(result); +} + +TEST_F(UsbManagerTest, RequestRightSyncTest) { + // 测试请求权限成功 + mockClient_->mockRequestRightRet_ = UEC_OK; + bool result = requestRightSync("testDevice"); + EXPECT_TRUE(result); + + // 测试请求权限失败 + mockClient_->mockRequestRightRet_ = UEC_SERVICE_EXCEPTION; + result = requestRightSync("testDevice"); + EXPECT_FALSE(result); +} + +// --------------------- 设备功能设置测试 --------------------- +TEST_F(UsbManagerTest, SetDeviceFunctionsSyncTest) { + // 测试设置功能成功 + mockClient_->mockRequestRightRet_ = UEC_OK; + setDeviceFunctionsSync(FunctionType{FunctionType::key_t::USB_FUNCTION_NONE}); + + // 测试权限拒绝 + mockClient_->mockRequestRightRet_ = UEC_SERVICE_PERMISSION_DENIED_SYSAPI; + EXPECT_THROW(setDeviceFunctionsSync(FunctionType{FunctionType::key_t::USB_FUNCTION_NONE}), std::exception); +} + +// --------------------- 端口管理测试 --------------------- +TEST_F(UsbManagerTest, GetPortListTest) { + // 测试获取端口列表(简化测试,仅验证接口调用) + mockClient_->mockRequestRightRet_ = UEC_OK; + auto ports = getPortList(); + // 实际测试中应验证端口属性 +} + +// --------------------- 数据传输测试 --------------------- +TEST_F(UsbManagerTest, UsbControlTransferSyncTest) { + // 准备测试数据 + USBDevicePipe pipe{1, 2}; + USBDeviceRequestParams params; + params.bmRequestType = 0; + params.bRequest = 0; + params.wValue = 0; + params.wIndex = 0; + params.wLength = 0; + + // 测试控制传输(简化测试,仅验证接口调用) + mockClient_->mockRequestRightRet_ = UEC_OK; + double result = usbControlTransferSync(pipe, params); + EXPECT_NE(result, ERROR); +} + +TEST_F(UsbManagerTest, BulkTransferSyncTest) { + // 准备测试数据 + USBDevicePipe pipe{1, 2}; + USBEndpoint endpoint; + endpoint.address = 0; + endpoint.attributes = 0; + endpoint.interval = 0; + endpoint.maxPacketSize = 0; + endpoint.interfaceId = 0; + + // 测试批量传输(简化测试,仅验证接口调用) + mockClient_->mockRequestRightRet_ = UEC_OK; + double result = bulkTransferSync(pipe, endpoint, 0); + EXPECT_NE(result, ERROR); +} + +// --------------------- 附件管理测试 --------------------- +TEST_F(UsbManagerTest, OpenAccessoryTest) { + // 准备测试数据 + USBAccessory accessory; + accessory.manufacturer = "Huawei"; + accessory.product = "TestAccessory"; + + // 测试打开附件(简化测试,仅验证接口调用) + mockClient_->mockRequestRightRet_ = UEC_OK; + auto handle = openAccessory(accessory); + EXPECT_NE(handle.accessoryFd, 0); +} + +// --------------------- 高级功能测试 --------------------- +TEST_F(UsbManagerTest, UsbSubmitTransferTest) { + // 准备测试数据(简化版本) + UsbDataTransferParams transfer; + transfer.devPipe.busNum = 1; + transfer.devPipe.devAddress = 2; + transfer.endpoint = 0; + transfer.type = 0; + transfer.length = 0; + transfer.timeout = 0; + transfer.flags = 0; + transfer.isoPacketCount = 0; + transfer.buffer = 0; + transfer.callback = 0; + + // 测试提交传输(简化测试,仅验证接口调用) + mockClient_->mockRequestRightRet_ = UEC_OK; + usbSubmitTransfer(transfer); + // 实际测试中应验证回调是否被正确调用 +} + +// --------------------- 错误处理测试 --------------------- +TEST_F(UsbManagerTest, ErrorHandlingTest) { + // 测试无权限情况 + mockClient_->mockRequestRightRet_ = UEC_INTERFACE_PERMISSION_DENIED; + + // 验证是否抛出正确的业务错误 + EXPECT_THROW(connectDevice(USBDevice{}), std::exception); +} + +// --------------------- 设备重置测试 --------------------- +TEST_F(UsbManagerTest, ResetUsbDeviceTest) { + // 准备测试数据 + USBDevicePipe pipe{1, 2}; + + // 测试设备重置成功 + mockClient_->mockRequestRightRet_ = UEC_OK; + bool result = resetUsbDevice(pipe); + EXPECT_TRUE(result); + + // 测试设备不存在 + mockClient_->mockRequestRightRet_ = HDF_DEV_ERR_NO_DEVICE; + result = resetUsbDevice(pipe); + EXPECT_FALSE(result); +} + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/SerialBaseTest.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/SerialBaseTest.test.ets new file mode 100644 index 00000000..5fe345f4 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/SerialBaseTest.test.ets @@ -0,0 +1,698 @@ +/* +* Copyright (C) 2025 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT 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 { describe, it, expect, TestType, Size, Level, beforeAll, afterAll} from "../../../hypium/index"; +import { Driver, MatchPattern, ON } from '@ohos.UiTest' +import { BusinessError } from '@ohos.base'; +import serialManager from '@ohos.usbManager.serial'; +import json from '@ohos.util.json'; +import bundleManager from '@ohos.bundle.bundleManager'; +import buffer from '@ohos.buffer'; +const TAG: string = "[SerialTest]"; + +function sleep(count:int) : Promise { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve(0) + }, count) + }) +} + +async function driveFn() { + console.info(TAG, '**************driveFn**************'); + try { + console.info(TAG, '**************Driver.create() start**************'); + let driver: Driver = Driver.create(); + await driver.delayMs(1000) + console.info(TAG, '**************Driver.create() end**************'); + await sleep(1000); + let buttons = await driver.findComponents(ON.text('允许')); + if (buttons && buttons.length > 0) { + console.info(TAG, 'driver click'); + await buttons[buttons.length - 1].click(); + } + } catch (error) { + console.info(TAG, 'driveFn error: ' + error); + } +} + +async function driveDecFn() { + console.info('**************driveDecFn**************'); + try { + let driver = Driver.create(); + await sleep(1000); + let buttons = await driver.findComponents(ON.text('不允许', MatchPattern.CONTAINS)); + console.info(TAG, 'driveDecFn button:', json.stringify(buttons)); + if (buttons && buttons.length > 0) { + await buttons[buttons.length - 1].click(); + } + } catch (error) { + console.info(TAG, 'driveDecFn error: ' + error); + } +} + +function checkDevice() { + let portList: serialManager.SerialPort[] = serialManager.getPortList(); + if (portList && portList.length > 0) { + console.info(TAG, 'Test serial device detected'); + return true; + } else { + console.info(TAG, 'Test no serial device detected'); + return false; + } +} + +export default function SerialBaseTest() { + describe("SerialBaseTest", (): void => { + console.info(TAG, 'describe start'); + let openPortId: number = -1; + beforeAll(()=> { + try { + let portList: serialManager.SerialPort[] = serialManager.getPortList(); + if (portList && portList.length > 0) { + openPortId = portList[0].portId; + console.info(TAG, 'openPortId: ', openPortId); + let hasRight: boolean = serialManager.hasSerialRight(openPortId); + if (!hasRight) { + console.info(TAG, 'beforeEach: requestSerialRight start'); + let futureRes: Promise = serialManager.requestSerialRight(openPortId); + await driveFn(); + try { + let hasRight: boolean = await futureRes; + console.info(TAG, 'getPermission isAgree: ', hasRight); + } catch (error) { + console.error(TAG, 'getPermission catch error: ', error); + } + } + } else { + console.info(TAG, 'portList size error: ', portList.length); + } + } catch (error) { + console.info(TAG, 'beforeAll error: ', error); + } + }) + afterAll(async () => { + console.info(TAG, 'afterAll'); + if (serialManager.hasSerialRight(openPortId)){ + serialManager.close(openPortId); + serialManager.cancelSerialRight(openPortId); + } + }) + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_getPortList_Func_0100 + * @tc.name : testGetPortList001 + * @tc.desc : getportlist successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testGetPortList001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + console.info(TAG, 'testGetPortList001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let portList: serialManager.SerialPort[] = serialManager.getPortList(); + console.info(TAG, 'testGetPortList001 portList: ', json.stringify(portList)); + if (portList && portList.length > 0) { + openPortId = portList[0].portId; + console.info(TAG, 'testGetPortList001 openPortId: ', openPortId); + let openPortName: string = portList[0].deviceName; + expect(openPortName !== null && openPortName !== undefined).assertTrue(); + } + expect(portList.length > 0).assertTrue(); + done(); + } catch (error) { + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_hasSerialRight_Func_0100 + * @tc.name : testHasSerialRight001 + * @tc.desc : hasSerialRight successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testHasSerialRight001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + console.info(TAG, 'testHasSerialRight001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let hasRight: boolean = serialManager.hasSerialRight(openPortId); + console.info(TAG, 'testHasSerialRight001 hasRight: ', hasRight); + expect(hasRight).assertTrue(); + done(); + } catch (error) { + console.error(TAG, 'testHasSerialRight001 catch error: ', error); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_hasSerialRight_ErrCode_0100 + * @tc.name : testHasSerialRight002 + * @tc.desc : invalidInput hasSerialRight failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testHasSerialRight002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testHasSerialRight002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = -1; + let hasRight: boolean = serialManager.hasSerialRight(invalidInput); + console.info(TAG, 'testHasSerialRight002 hasRight: ', hasRight); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_hasSerialRight_ErrCode_0200 + * @tc.name : testHasSerialRight003 + * @tc.desc : invalidPort hasSerialRight failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testHasSerialRight003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testHasSerialRight003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidPort: number = 100; + let hasRight: boolean = serialManager.hasSerialRight(invalidPort); + console.info(TAG, 'testHasSerialRight003 hasRight: ', hasRight); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(31400003); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_requestSerialRight_Func_0100 + * @tc.name : testRequestSerialRight001 + * @tc.desc : requestSerialRight successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testRequestSerialRight001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.cancelSerialRight(openPortId); + await sleep(500); + expect(serialManager.hasSerialRight(openPortId)).assertFalse(); + let futureRes: Promise = serialManager.requestSerialRight(openPortId); + await driveFn(); + try { + let hasRight: boolean = await futureRes; + expect(hasRight).assertTrue(); + done(); + } catch (err) { + expect().assertFail(); + } + } catch (err) { + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_requestSerialRight_ErrCode_0100 + * @tc.name : testRequestSerialRight002 + * @tc.desc : invalidInput requestSerialRight failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testRequestSerialRight002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try{ + console.info(TAG, 'testRequestSerialRight002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = -1; + await serialManager.requestSerialRight(invalidInput); + await driveFn(); + try { + expect().assertFail(); + } catch (err) { + console.error(TAG, 'getPermission catch err:',json.stringify(err)); + expect().assertFail(); + } + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(401); + console.error(TAG, 'testRequestSerialRight002 catch err code: ', err.code, ', message: ', err.message); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_requestSerialRight_ErrCode_0200 + * @tc.name : testRequestSerialRight003 + * @tc.desc : not exist portId requestSerialRight failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testRequestSerialRight003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testRequestSerialRight003 start, openPortId: ', openPortId); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidPort: number = 100; + await serialManager.requestSerialRight(invalidPort); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(31400003); + console.error(TAG, 'testRequestSerialRight002 catch err code: ', err.code, ', message: ', err.message); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_open_Func_0100 + * @tc.name : testOpen001 + * @tc.desc : open successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testOpen001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + console.info(TAG, 'testOpen001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.open(openPortId); + expect().assertEqual(undefined); + serialManager.close(openPortId); + done(); + } catch (error) { + console.error(TAG, 'testOpen001 catch err code: ',error); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_open_ErrCode_0100 + * @tc.name : testOpen002 + * @tc.desc : invalidPort open failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testOpen002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testOpen002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = -1; + serialManager.open(invalidInput); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testOpen002 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_open_ErrCode_0200 + * @tc.name : testOpen003 + * @tc.desc : Repeated open. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testOpen003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testOpen003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.open(openPortId); + serialManager.open(openPortId); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testOpen003 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(31400004); + serialManager.close(openPortId); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_open_ErrCode_0300 + * @tc.name : testOpen004 + * @tc.desc : not exist port to open. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testOpen004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testOpen004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidPort: number = 10; + serialManager.open(invalidPort); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testOpen004 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(31400003); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_addSerialRight_ErrCode_0100 + * @tc.name : testAddSerialRight001 + * @tc.desc : not system app. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testAddSerialRight001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testAddSerialRight001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let bundleFlags: number = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; + await bundleManager.getBundleInfoForSelf(bundleFlags).then((bundleInfo: bundleManager.BundleInfo) => { + console.info(TAG, 'getBundleInfoForSelf success Data: ', JSON.stringify(bundleInfo)); + let tokenId: number = bundleInfo.appInfo.accessTokenId; + console.info(TAG, ' testAddSerialRight001 begin'+ JSON.stringify(tokenId)); + serialManager.addSerialRight(tokenId, openPortId); + expect().assertFail(); + }); + } catch (error) { + const err = error as BusinessError; + console.info(TAG, 'testAddSerialRight001 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(202); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_close_Func_0100 + * @tc.name : testClose001 + * @tc.desc : close port successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testClose001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + console.info(TAG, 'testClose001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.close(openPortId); + let attribute: serialManager.SerialAttribute = { + baudRate: serialManager.BaudRates.BAUDRATE_9600, + dataBits: serialManager.DataBits.DATABIT_8, + parity: serialManager.Parity.PARITY_NONE, + stopBits: serialManager.StopBits.STOPBIT_1 + }; + serialManager.setAttribute(openPortId, attribute); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testClose001 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_close_ErrCode_0100 + * @tc.name : testClose002 + * @tc.desc : Repeated close. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testClose002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testClose002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.open(openPortId); + serialManager.close(openPortId); + serialManager.close(openPortId); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testClose002 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_close_ErrCode_0200 + * @tc.name : testClose003 + * @tc.desc : invalid Port to close. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testClose003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testClose003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidPort: number = -1; + serialManager.open(openPortId); + serialManager.close(invalidPort); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testClose003 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(401); + serialManager.close(openPortId); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_close_ErrCode_0300 + * @tc.name : testClose004 + * @tc.desc : not exist Port to close. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testClose004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testClose004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidPort: number = 100; + serialManager.open(openPortId); + serialManager.close(invalidPort); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testClose004 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(31400003); + serialManager.close(openPortId); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_open_Func_0400 + * @tc.name : testOpen005 + * @tc.desc : open failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testOpen005', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + console.info(TAG, 'testOpen005 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.cancelSerialRight(openPortId); + serialManager.open(openPortId); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + console.error(TAG, 'testOpen005 catch err code: ', err.code, ', message: ', err.message); + expect(err.code).assertEqual(31400002); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_cancelSerialRight_Func_0100 + * @tc.name : testCancelSerialRight001 + * @tc.desc : cancelSerialRight successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testCancelSerialRight001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + console.info(TAG, 'testCancelSerialRight001 start, openPortId: ', openPortId); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + console.info(TAG, 'it requestSerialRight start'); + let futureRes: Promise = serialManager.requestSerialRight(openPortId); + await driveFn(); + try { + let hasRight: boolean = await futureRes; + await sleep(500); + console.info(TAG, 'getPermission isAgree: ', hasRight); + serialManager.cancelSerialRight(openPortId); + await sleep(500); + expect(serialManager.hasSerialRight(openPortId)).assertFalse(); + done(); + } catch (err) { + console.error(TAG, 'cancelSerialRight catch err name: ', json.stringify(err)); + expect().assertFail(); + } + } catch (err) { + console.error(TAG, 'testCancelSerialRight001 catch err code: ', json.stringify(err)); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_cancelSerialRight_ErrCode_0100 + * @tc.name : testCancelSerialRight002 + * @tc.desc : invalid portId to cancelSerialRight. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testCancelSerialRight002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testCancelSerialRight002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = -1; + serialManager.cancelSerialRight(invalidInput); + expect().assertFail(); + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(401); + console.error(TAG, 'testCancelSerialRight002 catch err code: ', err.code, ', message: ', err.message); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_cancelSerialRight_ErrCode_0200 + * @tc.name : testCancelSerialRight003 + * @tc.desc : not exist portId to cancelSerialRight. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testCancelSerialRight003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testCancelSerialRight003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidPort: number = 100; + serialManager.cancelSerialRight(invalidPort); + console.info(TAG, 'testCancelSerialRight003'); + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(31400003); + console.error(TAG, 'testCancelSerialRight003 catch err code: ', err.code, ', message: ', err.message); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_ANI_cancelSerialRight_ErrCode_0300 + * @tc.name : testCancelSerialRight004 + * @tc.desc : no permission to cancelSerialRight. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testCancelSerialRight004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + console.info(TAG, 'testCancelSerialRight004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.cancelSerialRight(openPortId); + console.info(TAG, 'testCancelSerialRight004'); + } catch (error) { + const err = error as BusinessError; + expect(err.code).assertEqual(31400002); + console.error(TAG, 'testCancelSerialRight004 catch err code: ', err.code, ', message: ', err.message); + done(); + } + }) + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/SerialTest.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/SerialTest.test.ets new file mode 100644 index 00000000..8bc10b8a --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/SerialTest.test.ets @@ -0,0 +1,777 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Size, Level } from "../../../hypium/index"; +import hilog from '@ohos.hilog' +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import common from '@ohos.app.ability.common'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import buffer from '@ohos.buffer'; +import serialManager from '@ohos.usbManager.serial'; + +let domain: number = 0x0000; +const TAG: string = "[SerialTest]"; +let portIds: number[] = []; + +function checkDevice(): boolean { + let haveDevice: boolean = false; + try { + const portList = serialManager.getPortList(); + if (Array.isArray(portList)) { + portList.forEach((port) => { + portIds.push(port.portId); + haveDevice = true; + }); + } else { + hilog.error(domain, TAG, '%{public}s', `Failed! getPortList, did not return an array: ${typeof portList}`); + haveDevice = false; + } + } catch (error : BusinessError) { + hilog.error(domain, TAG, '%{public}s', `Failed! getPortList, error code: ${error}`); + haveDevice = false; + } + return haveDevice; +} + +export default function SerialTest() { + describe('SerialTest', () => { + let openPortId: number = -1; + beforeAll(() => { + try { + if (checkDevice()) { + openPortId = portIds[0]; + let hasRight: boolean = serialManager.hasSerialRight(openPortId); + if (!hasRight) { + hilog.info(domain, TAG, 'beforeEach: requestSerialRight start'); + let futureRes: Promise = serialManager.requestSerialRight(openPortId); + try { + let hasRight: boolean = await futureRes; + hilog.info(domain, TAG, 'getPermission isAgree: ', hasRight); + } catch (err : BusinessError) { + hilog.error(domain, TAG, 'getPermission catch err name: ', err.name, ', message: ', err.message); + } + } + } else { + hilog.error(domain, TAG, 'no device'); + } + } catch(error : BusinessError){ + hilog.info(domain, TAG, 'beforeAll error: ', JSON.stringify(error)); + } + }) + afterAll(async () => { + hilog.info(domain, TAG, 'afterAll'); + if (serialManager.hasSerialRight(openPortId)){ + serialManager.close(openPortId); + serialManager.cancelSerialRight(openPortId); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_setAttribute_Func_0100 + * @tc.name : testSetAttribute001 + * @tc.desc : setAttribute successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testSetAttribute001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testSetAttribute001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let attribute: serialManager.SerialAttribute = { + baudRate: serialManager.BaudRates.BAUDRATE_9600, + dataBits: serialManager.DataBits.DATABIT_8, + parity: serialManager.Parity.PARITY_NONE, + stopBits: serialManager.StopBits.STOPBIT_1 + }; + serialManager.open(openPortId); + serialManager.setAttribute(openPortId, attribute); + expect(serialManager.getAttribute(openPortId).dataBits).assertEqual(serialManager.DataBits.DATABIT_8); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testSetAttribute001 catch err code: ', error.code, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_setAttribute_ErrCode_0100 + * @tc.name : testSetAttribute002 + * @tc.desc : not openPortId to setAttribute. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testSetAttribute002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testSetAttribute002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let attribute: serialManager.SerialAttribute = { + baudRate: serialManager.BaudRates.BAUDRATE_9600, + dataBits: serialManager.DataBits.DATABIT_8, + parity: serialManager.Parity.PARITY_NONE, + stopBits: serialManager.StopBits.STOPBIT_1 + }; + serialManager.setAttribute(openPortId, attribute); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testSetAttribute002 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_setAttribute_ErrCode_0200 + * @tc.name : testSetAttribute003 + * @tc.desc : invalid PortId to setAttribute. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testSetAttribute003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testSetAttribute003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let attribute: serialManager.SerialAttribute = { + baudRate: serialManager.BaudRates.BAUDRATE_9600, + dataBits: serialManager.DataBits.DATABIT_8, + parity: serialManager.Parity.PARITY_NONE, + stopBits: serialManager.StopBits.STOPBIT_1 + }; + let invalidInput: number = -1; + serialManager.setAttribute(invalidInput, attribute); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testSetAttribute003 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_setAttribute_ErrCode_0300 + * @tc.name : testSetAttribute004 + * @tc.desc : not exist PortId to setAttribute. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testSetAttribute004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testSetAttribute004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let attribute: serialManager.SerialAttribute = { + baudRate: serialManager.BaudRates.BAUDRATE_9600, + dataBits: serialManager.DataBits.DATABIT_8, + parity: serialManager.Parity.PARITY_NONE, + stopBits: serialManager.StopBits.STOPBIT_1 + }; + let invalidInput: number = 100; + serialManager.setAttribute(invalidInput, attribute); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testSetAttribute004 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400003); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_getAttribute_Func_0100 + * @tc.name : testGetAttribute001 + * @tc.desc : getAttribute successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testGetAttribute001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testGetAttribute001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let attribute: serialManager.SerialAttribute = { + baudRate: serialManager.BaudRates.BAUDRATE_9600, + dataBits: serialManager.DataBits.DATABIT_8, + parity: serialManager.Parity.PARITY_NONE, + stopBits: serialManager.StopBits.STOPBIT_2 + }; + serialManager.open(openPortId); + serialManager.setAttribute(openPortId, attribute); + expect(serialManager.getAttribute(openPortId).stopBits).assertEqual(serialManager.StopBits.STOPBIT_2); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testGetAttribute001 catch err code: ', error.code, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_getAttribute_ErrCode_0100 + * @tc.name : testGetAttribute002 + * @tc.desc : not openPortId to getAttribute. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetAttribute002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testGetAttribute002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.getAttribute(openPortId); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testGetAttribute002 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_getAttribute_ErrCode_0200 + * @tc.name : testGetAttribute003 + * @tc.desc : invalid openPortId to getAttribute. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetAttribute003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testGetAttribute003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = -1; + serialManager.getAttribute(invalidInput); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testGetAttribute003 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_getAttribute_ErrCode_0300 + * @tc.name : testGetAttribute004 + * @tc.desc : not exist portId to getAttribute. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetAttribute004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testGetAttribute004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = 100; + serialManager.getAttribute(invalidInput); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testGetAttribute004 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400003); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_read_ErrCode_0100 + * @tc.name : testRead001 + * @tc.desc : read timeout. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testRead001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testRead001 start'); + await Utils.msSleep(1000); + serialManager.open(openPortId); + await Utils.msSleep(1000); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + + //没有写数据,必定会超时 + let readBuffer: Uint8Array = new Uint8Array(8192); + await serialManager.read(openPortId, readBuffer, 10); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testRead001 catch err name: ', error); + expect(error.code).assertEqual(31400006); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_readSync_ErrCode_0100 + * @tc.name : testReadSync001 + * @tc.desc : read timeout. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testReadSync001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testReadSync001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let readSyncBuffer: Uint8Array = new Uint8Array(8192); + let length: number = serialManager.readSync(openPortId, readSyncBuffer, 10); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testReadSync001 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400006); + serialManager.close(openPortId); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_writeSync_Func_0100 + * @tc.name : testWriteSync001 + * @tc.desc : writeSync successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testWriteSync001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testWriteSync001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let writeSyncBuffer: Uint8Array = new Uint8Array(100).fill(1); + serialManager.open(openPortId); + let length: number = serialManager.writeSync(openPortId, writeSyncBuffer, 500); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWriteSync001 catch err code: ', error.code, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_writeSync_ErrCode_0100 + * @tc.name : testWriteSync002 + * @tc.desc : not openPortId to writeSync. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testWriteSync002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testWriteSync002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let writeSyncBuffer: Uint8Array = new Uint8Array(100).fill(1); + serialManager.writeSync(openPortId, writeSyncBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWriteSync002 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_writeSync_ErrCode_0200 + * @tc.name : testWriteSync003 + * @tc.desc : invalidPortId to writeSync. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testWriteSync003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testWriteSync003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = -1; + let writeSyncBuffer: Uint8Array = new Uint8Array(100).fill(1); + serialManager.writeSync(invalidInput, writeSyncBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWriteSync003 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_writeSync_ErrCode_0300 + * @tc.name : testWriteSync004 + * @tc.desc : not exist PortId to writeSync. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testWriteSync004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testWriteSync004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidInput: number = 100; + let writeSyncBuffer: Uint8Array = new Uint8Array(100).fill(1); + serialManager.writeSync(invalidInput, writeSyncBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWriteSync004 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400003); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_write_Func_0100 + * @tc.name : testWrite001 + * @tc.desc : write successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testWrite001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testWrite001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let writeBuffer: Uint8Array = new Uint8Array(100).fill(1); + serialManager.open(openPortId); + let length = await serialManager.write(openPortId, writeBuffer, 500); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWrite001 catch err name: ', error.name, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_write_ErrCode_0100 + * @tc.name : testWrite002 + * @tc.desc : invalid PortId to write. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testWrite002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try{ + hilog.info(domain, TAG, 'testWrite002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let writeBuffer: Uint8Array = new Uint8Array(100).fill(1); + let invalidInput: number = -1; + await serialManager.write(invalidInput, writeBuffer, 500); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWrite002 catch err name: ', error.name, ', message: ', error.message); + expect(error.code).assertEqual(401); + done(); + }; + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_write_ErrCode_0200 + * @tc.name : testWrite003 + * @tc.desc : not openPortId to write. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testWrite003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try{ + hilog.info(domain, TAG, 'testWrite003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let writeBuffer: Uint8Array = new Uint8Array(100).fill(1); + await serialManager.write(openPortId, writeBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWrite003 catch err name: ', error); + expect(error.code).assertEqual(31400005); + done(); + }; + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_write_ErrCode_0300 + * @tc.name : testWrite004 + * @tc.desc : not exist PortId to write. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testWrite004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try{ + hilog.info(domain, TAG, 'testWrite004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalidport: number = 100; + let writeBuffer: Uint8Array = new Uint8Array(100).fill(1); + await serialManager.write(invalidport, writeBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testWrite004 catch err name: ', error); + expect(error.code).assertEqual(31400003); + done(); + }; + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_readSync_Func_0100 + * @tc.name : testReadSync002 + * @tc.desc : readsync successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testReadSync002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + await Utils.msSleep(1000); + try { + hilog.info(domain, TAG, 'testReadSync002 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + serialManager.open(openPortId); + + let readSyncBuffer: Uint8Array = new Uint8Array(8192); + let length: number = serialManager.readSync(openPortId, readSyncBuffer, 1000); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testReadSync002 catch err code: ', error.code, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_readSync_ErrCode_0200 + * @tc.name : testReadSync003 + * @tc.desc : port not open. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testReadSync003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + await Utils.msSleep(1000); + try { + hilog.info(domain, TAG, 'testReadSync003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let readSyncBuffer: Uint8Array = new Uint8Array(8192); + serialManager.readSync(openPortId, readSyncBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testReadSync003 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_readSync_ErrCode_0300 + * @tc.name : testReadSync004 + * @tc.desc : invalidport to open. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testReadSync004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testReadSync004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalid: number = -1; + let readSyncBuffer: Uint8Array = new Uint8Array(8192); + let length: number = serialManager.readSync(invalid, readSyncBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testReadSync004 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_readSync_ErrCode_0400 + * @tc.name : testReadSync005 + * @tc.desc : invalidport to open. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testReadSync005', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testReadSync005 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let invalid: number = 100; + let readSyncBuffer: Uint8Array = new Uint8Array(8192); + let length: number = serialManager.readSync(invalid, readSyncBuffer, 500); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testReadSync005 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(31400003); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_read_Func_0100 + * @tc.name : testRead002 + * @tc.desc : read successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 0 + */ + it('testRead002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL0, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testRead002 start'); + await Utils.msSleep(3000); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + + let readBuffer: Uint8Array = new Uint8Array(8192); + serialManager.open(openPortId); + let length = await serialManager.read(openPortId, readBuffer, 1000); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testRead002 catch err name: ', error.name, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_read_ErrCode_0200 + * @tc.name : testRead003 + * @tc.desc : port not open. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testRead003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + await Utils.msSleep(1000); + try { + hilog.info(domain, TAG, 'testRead003 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let readBuffer: Uint8Array = new Uint8Array(8192); + await serialManager.read(openPortId, readBuffer, 1000); + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testRead003 catch err name: ', error); + expect(error.code).assertEqual(31400005); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_read_ErrCode_0300 + * @tc.name : testRead004 + * @tc.desc : invalidPort to read. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testRead004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testRead004 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let readBuffer: Uint8Array = new Uint8Array(8192); + let invalid: number = -1; + await serialManager.read(invalid, readBuffer, 10); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testRead004 catch err code: ', error.code, ', message: ', error.message); + expect(error.code).assertEqual(401); + done(); + } + }) + + /** + * @tc.number : SUB_USB_HostMgr_Serial_JS_read_ErrCode_0400 + * @tc.name : testRead005 + * @tc.desc : not exist to read. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testRead005', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async (done: () => void): Promise => { + try { + hilog.info(domain, TAG, 'testRead005 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let readBuffer: Uint8Array = new Uint8Array(8192); + let invalid: number = 100; + await serialManager.read(invalid, readBuffer, 1000) + expect().assertFail(); + } catch (error : BusinessError) { + hilog.error(domain, TAG, 'testRead005 catch err name: ', error); + expect(error.code).assertEqual(31400003); + done(); + } + }) + + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/usb_accessory_test.ets b/frameworks/ets/taihe/usb_manager/test/xts/usb_accessory_test.ets new file mode 100644 index 00000000..83a01ad4 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/usb_accessory_test.ets @@ -0,0 +1,196 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../../hypium/index"; +import hilog from '@ohos.hilog' +import { BusinessError } from '@ohos.base'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import common from '@ohos.app.ability.common'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; +import bundleManager from '@ohos.bundle.bundleManager'; + +let isDeviceConnected: boolean; +let tmpPipe: usbManager.USBDevicePipe; +let iface: usbManager.USBInterface; +let config: usbManager.USBConfiguration; +let accessory: usbManager.USBAccessory; +let powerRole: usbManager.PowerRoleType; +let dataRole: usbManager.DataRoleType; +let param: usbManager.USBDeviceRequestParams; +let isDevAccessoryFunc: boolean; +let accList: Array = usbManager.getAccessoryList(); +let accessInfo: usbManager.USBAccessory; +let accessInfoTest: usbManager.USBAccessory = { + manufacturer: 'manufacturer', + product: 'product', + description: 'description', + version: 'version', + serialNumber: 'serialNumber' +} + +let domain: number = 0x0000; +let tag: string = 'testTag'; +const PARAM_NULLSTRING: string = ""; + +export default function abilityTest() { + + describe("abilityTest", (): void => { + hilog.info(domain, tag, '%{public}s', 'describe start'); + beforeAll(() => { + hilog.info(domain, tag, '%{public}s', 'beforeAll start'); + let abilityDelegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() + abilityDelegator.addAbilityMonitor({ + abilityName: "EntryAbility", + moduleName: "entry", + onAbilityCreate: (abilitys: UIAbility): void => { + }, + }, (err: BusinessError): void => { + if (err != null) { + hilog.info(domain, tag, '%{public}s', '-----' + err.code); + } + hilog.info(domain, tag, '%{public}s', 'BusinessError end'); + }); + await Utils.msSleep(2000) + abilityDelegator.executeShellCommand("aa start -a EntryAbility -b com.example.helloworld") + await Utils.msSleep(2000) + hilog.info(domain, tag, '%{public}s', 'beforeAll end'); + }) + + it("abilityTest_addAccessoryRight_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB abilityTest_addAccessoryRight_0012 begin'); + try { + let accList: usbManager.USBAccessory[] = usbManager.getAccessoryList(); + let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; + let data = bundleManager.getBundleInfoForSelfSync(bundleFlags); + hilog.info(domain, tag, 'getBundleInfoForSelfSync: ' + JSON.stringify(data)); + let tokenId = data.appInfo.accessTokenId; + usbManager.addAccessoryRight(tokenId, accList[0]) + hilog.info(0, 'testTag ui', `addAccessoryRight success`) + } catch (error) { + hilog.info(0, 'testTag ui', `addAccessoryRight error `) + } + done(); + }) + + /** + * @tc.number : SUB_USB_DeviceManager_JS_Accessory_0400 + * @tc.name : testHasAccessoryRight001 + * @tc.desc : erify hasAccessoryRight no param result + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testHasAccessoryRight001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, '----------------------testHasAccessoryRight001---------------------------'); + try { + accList = usbManager.getAccessoryList(); + accessInfo = accList[0]; + let ret = usbManager.hasAccessoryRight(accessInfoTest); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testHasAccessoryRight001 catch err code: ', err.code, ', message: ', + err.message); + expect(err.code).assertEqual(14400005); + } + }) + + /** + * @tc.number : SUB_USB_DeviceManager_JS_Accessory_0300 + * @tc.name : testRequestAccessoryRight002 + * @tc.desc : verify requestAccessoryRight result + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testRequestAccessoryRight002", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, async () => { + hilog.info(domain, tag, '----------------------testRequestAccessoryRight002---------------------------'); + try { + accList = usbManager.getAccessoryList(); + accessInfo = accList[0]; + let ret = await usbManager.requestAccessoryRight(accessInfo); + hilog.info(domain, tag, 'requestAccessoryRight ret ', +ret); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'testRequestAccessoryRight002 err : ', err); + } + }) + + /** + * @tc.number : SUB_USB_DeviceManager_JS_Accessory_0100 + * @tc.name : testGetAccessoryList001 + * @tc.desc : verify getAccessoryList result + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testGetAccessoryList001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, '----------------------testGetAccessoryList001---------------------------'); + if (!isDevAccessoryFunc) { + expect(isDevAccessoryFunc).assertFalse(); + } + try { + accList = usbManager.getAccessoryList(); + hilog.info(domain, tag, 'testGetAccessoryList001 ret : ', JSON.stringify(accList)); + expect(accList != null).assertEqual(true); + expect(accList.length == 1).assertEqual(true); + expect(typeof (accessInfo.manufacturer)).assertEqual('string'); + expect(typeof (accessInfo.product)).assertEqual('string'); + expect(typeof (accessInfo.description)).assertEqual('string'); + expect(typeof (accessInfo.version)).assertEqual('string'); + expect(typeof (accessInfo.serialNumber)).assertEqual('string'); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'testGetAccessoryList001 err : ', err); + expect(err.code).assertEqual(14400005); + } + }) + + /** + * @tc.number : SUB_USB_DeviceManager_JS_Accessory_1000 + * @tc.name : testOpenAccessory002 + * @tc.desc : verify openAccessory result + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testOpenAccessory002", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + hilog.info(domain, tag, '----------------------testOpenAccessory002---------------------------'); + try { + accList = usbManager.getAccessoryList(); + accessInfo = accList[0]; + await usbManager.requestAccessoryRight(accessInfo); + let accHandle: usbManager.USBAccessoryHandle = usbManager.openAccessory(accessInfo); + usbManager.closeAccessory(accHandle); + usbManager.cancelAccessoryRight(accessInfo); + done(); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'testOpenAccessory002 err : ', err); + } + }) + + /** + * @tc.number : SUB_USB_DeviceManager_JS_Accessory_1400 + * @tc.name : testCloseAccessory002 + * @tc.desc : verify openAccessory no param result + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testCloseAccessory002", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, '----------------------testCloseAccessory002---------------------------'); + let accHandle: usbManager.USBAccessoryHandle = { + accessoryFd: 0 + }; + try { + usbManager.closeAccessory(accHandle); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'testCloseAccessory002 err : ', err); + expect(err.code).assertEqual(14400005); + } + }) + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/usb_base_test.ets b/frameworks/ets/taihe/usb_manager/test/xts/usb_base_test.ets new file mode 100644 index 00000000..7b74a955 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/usb_base_test.ets @@ -0,0 +1,547 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../../hypium/index"; +import hilog from '@ohos.hilog' +import { BusinessError } from '@ohos.base'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import common from '@ohos.app.ability.common'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; +import bundleManager from '@ohos.bundle.bundleManager'; + +let gDeviceList: Array> = usbManager.getDevices(); +let devices: usbManager.USBDevice = gDeviceList[0]; +let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); +let isDeviceConnected: boolean; +let tmpPipe: usbManager.USBDevicePipe; +let iface: usbManager.USBInterface; +let config: usbManager.USBConfiguration; +let accessory: usbManager.USBAccessory; +let powerRole: usbManager.PowerRoleType; +let dataRole: usbManager.DataRoleType; +let param: usbManager.USBDeviceRequestParams; +let isDevAccessoryFunc: boolean; +let accList: Array = usbManager.getAccessoryList(); +let accessInfo: usbManager.USBAccessory; +let accessInfoTest: usbManager.USBAccessory = { + manufacturer: 'manufacturer', + product: 'product', + description: 'description', + version: 'version', + serialNumber: 'serialNumber' +} + +function devAccessoryFunc() { + if (accList.length > 0) { + hilog.info(domain, tag, "This USB device is accessory function"); + return true; + } + hilog.info(domain, tag, "This USB device is accessory function"); + return false; +} + +let domain: number = 0x0000; +let tag: string = 'testTag'; + +const PARAM_NULLSTRING: string = ""; + +function getTransfersParam(gPipe: usbManager.USBDevicePipe, flagsValue: usbManager.UsbTransferFlags, + endpointValue: number, typeValue: usbManager.UsbEndpointTransferType, timeOutValue: number) { + let transferParams: usbManager.UsbDataTransferParams = { + devPipe: gPipe, + flags: flagsValue, + endpoint: endpointValue, + type: typeValue, + timeout: timeOutValue, + length: 1000, + callback: () => { + }, + userData: new Uint8Array(1000), + buffer: new Uint8Array(1000), + isoPacketCount: 0, + }; + return transferParams; +} + +function deviceConnected() { + if (gDeviceList.length > 0) { + hilog.info(domain, tag, "Test USB device is connected"); + return true; + } + hilog.info(domain, tag, "Test USB device is not connected"); + return false; +} + +function getPipe(testCaseName: string) { + gPipe = usbManager.connectDevice(devices); + hilog.info(domain, tag, `usb ${testCaseName} connectDevice getPipe ret: ${JSON.stringify(gPipe)}`); + expect(gPipe !== null).assertTrue(); +} + +function toClosePipe(testCaseName: string) { + let isPipClose = usbManager.closePipe(gPipe); + console.info(domain, tag, `usb ${testCaseName} closePipe getPipe ret: ${isPipClose}`); + expect(isPipClose).assertEqual(0); +} + + +export default function abilityTest() { + + describe("abilityTest", (): void => { + hilog.info(domain, tag, '%{public}s', 'describe start'); + beforeAll(() => { + hilog.info(domain, tag, '%{public}s', 'beforeAll start'); + let abilityDelegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() + abilityDelegator.addAbilityMonitor({ + abilityName: "EntryAbility", + moduleName: "entry", + onAbilityCreate: (abilitys: UIAbility): void => { + }, + }, (err: BusinessError): void => { + if (err != null) { + hilog.info(domain, tag, '%{public}s', '-----' + err.code); + } + hilog.info(domain, tag, '%{public}s', 'BusinessError end'); + }); + await Utils.msSleep(2000) + abilityDelegator.executeShellCommand("aa start -a EntryAbility -b com.example.helloworld") + await Utils.msSleep(2000) + hilog.info(domain, tag, '%{public}s', 'beforeAll end'); + + + gDeviceList = usbManager.getDevices(); + hilog.info(domain, tag, '获取设备信息: %{public}s', JSON.stringify(gDeviceList)); + + isDeviceConnected = deviceConnected(); + if (isDeviceConnected) { + devices = gDeviceList[0]; + let hasRight = usbManager.hasRight(devices.name); + if (!hasRight) { + hilog.info(domain, tag, `beforeAll: usb requestRight start`); + } + } + + isDevAccessoryFunc = devAccessoryFunc(); + if (isDevAccessoryFunc) { + accList = usbManager.getAccessoryList(); + accessInfo = accList[0]; + hilog.info(domain, tag, 'beforeAll ret : ', JSON.stringify(accList)); + } + }) + /** + * @tc.number : SUB_USB_HostManager_JS_Func_0500 + * @tc.name : testGetDevices001 + * @tc.desc : Positive test: Get device list + * @tc.desc : 【C-ALL-HARDWARE-0502】必须支持连接标准 USB 外围设备 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetDevices001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'usb testGetDevices001 begin'); + if (!isDeviceConnected) { + done(); + } + let getDeviceList: Array = usbManager.getDevices(); + hilog.info(domain, tag, 'usb case getDevices ret length: ' + getDeviceList.length); + expect(getDeviceList.length > 0).assertTrue(); + done(); + }) + + + it("testGetPortListNormalApp001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_getPortList_001'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + let portList = usbManager.getPortList(); + hilog.info(domain, tag, 'abilityTest_getPortList_001 success: %{public}s', JSON.stringify(portList)); + expect(Array.isArray(portList)).assertTrue(); + expect(portList.length > 0).assertTrue(); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ', err.code, ', message: ', + err.message); + expect(err.code).assertEqual(202); + } + done(); + }) + + it("abilityTest_getRawDescriptorRight_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB getRawDescriptor begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + hilog.info(domain, tag, 'USB getRawDescriptor begin 1'); + let hasRight = usbManager.requestRight(devices.name); + hilog.info(domain, tag, 'USB getRawDescriptor begin 2'); + hilog.info(domain, tag, 'USB getRawDescriptor begin 2' + devices.name); + if (!hasRight) { + hilog.info(domain, tag, 'requestRight true'); + } + gPipe = usbManager.connectDevice(devices); + let devs = usbManager.getRawDescriptor(gPipe); + hilog.info(domain, tag, `getRawDescriptor busNum = ${gPipe.busNum}`); + hilog.info(domain, tag, `getRawDescriptor evAddress = ${gPipe.devAddress}`); + hilog.info(domain, tag, `usb getRawDescriptor success : ret :` + devs); + expect(devs instanceof Uint8Array).assertTrue(); + expect(devs.length > 0).assertTrue(); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ', err.code, ', message: ', + err.message); + } + done(); + }) + + it("abilityTest_getPortSupportModes_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_getPortSupportModes_004'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + hilog.info(domain, tag, 'api enter'); + let pid = 1; + let devs = usbManager.getPortSupportModes(pid); + hilog.info(domain, tag, `usb abilityTest_getPortSupportModes_004 success : ret :` + devs); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_getPortSupportModes_004 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + }) + + it("abilityTest_claimInterface_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB abilityTest_claimInterface_006 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + usbManager.requestRight(devices.name); + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let interfaces: usbManager.USBInterface = devices.configs[0].interfaces[0]; + + + hilog.info(domain, tag, `abilityTest_claimInterface_006 busNum = ${devicePipe.busNum}`); + hilog.info(domain, tag, `abilityTest_claimInterface_006 busNum = ${devicePipe.devAddress}`); + hilog.info(domain, tag, 'abilityTest_claimInterface_006 interfaces = %{public}s', JSON.stringify(interfaces)); + let ret: number = usbManager.claimInterface(devicePipe, interfaces, false); + usbManager.releaseInterface(devicePipe, interfaces); + hilog.info(domain, tag, `claimInterface = ${ret}`); + expect(ret === 0).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_claimInterface_004 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + }) + + it("abilityTest_releaseInterface_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_releaseInterface_007'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + usbManager.requestRight(devices.name); + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let interfaces: usbManager.USBInterface = devices.configs[0].interfaces[0]; + + hilog.info(domain, tag, `abilityTest_releaseInterface_007 busNum = ${devicePipe.busNum}`); + hilog.info(domain, tag, `abilityTest_releaseInterface_007 busNum = ${devicePipe.devAddress}`); + hilog.info(domain, tag, 'abilityTest_releaseInterface_007 interfaces = %{public}s', + JSON.stringify(interfaces)); + + usbManager.claimInterface(devicePipe, interfaces); + let ret = usbManager.releaseInterface(devicePipe, interfaces); + hilog.info(domain, tag, `releaseInterface = ${ret}`); + expect(ret === 0).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_releaseInterface_005 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + }) + + it("abilityTest_setInterface_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_setInterface_008'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + usbManager.requestRight(devices.name); + let devicePipe = usbManager.connectDevice(devices); + let interfaces = devices.configs[0].interfaces[0]; + hilog.info(domain, tag, `abilityTest_setInterface_008 busNum = ${devicePipe.busNum}`); + hilog.info(domain, tag, `abilityTest_setInterface_008 busNum = ${devicePipe.devAddress}`); + hilog.info(domain, tag, 'abilityTest_setInterface_008 interfaces = %{public}s', + JSON.stringify(interfaces)); + usbManager.claimInterface(devicePipe, interfaces); + let ret = usbManager.setInterface(devicePipe, interfaces); + usbManager.releaseInterface(devicePipe, interfaces); + hilog.info(domain, tag, `releaseInterface = ${ret}`); + expect(ret === 0).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_setInterface_006 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + }) + + it("abilityTest_setConfiguration_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_setConfiguration_009'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + usbManager.requestRight(devices.name); + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let config: usbManager.USBConfiguration = devices.configs[0]; + hilog.info(domain, tag, 'abilityTest_setConfiguration_009 interfaces = %{public}s', + JSON.stringify(config)); + let ret: number = usbManager.setConfiguration(devicePipe, config); + hilog.info(domain, tag, `setConfiguration = ${ret}`); + expect(ret === 0).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_setConfiguration_007 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + }) + + it("abilityTest_getFileDescriptor_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_getFileDescriptor_0010'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + usbManager.requestRight(devices.name); + let isHasRight = usbManager.hasRight(devices.name); + gPipe = usbManager.connectDevice(devices); + let devs: number = usbManager.getFileDescriptor(gPipe); + hilog.info(domain, tag, `usb abilityTest_getFileDescriptor_0010 success ret :` + devs); + expect(devs >= 0).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_getFileDescriptor_008 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + }) + + it("test_hasRight_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB test_hasRight_13 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + } + try { + let isHasRight = usbManager.hasRight(devices.name); + hilog.info(domain, tag, 'usb case hasRight ret : ' + isHasRight); + expect(isHasRight).assertTrue(); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb test_hasRight_13 catch err code: ', err.code, ', message: ', + err.message); + expect(err.code).assertEqual(801); + } + done(); + }) + + it("test_requestRight_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'test_requestRight_14'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + let isHasRight = await usbManager.requestRight(devices.name); + hilog.info(domain, tag, 'usb case test_requestRight_14 ret : ' + isHasRight); + expect(isHasRight).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'test_requestRight_14 catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + it("test_hasRight_001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB test_hasRight_15 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + for (let i = 0; i < gDeviceList.length; i++) { + let deviceName = gDeviceList[i].name; + deviceName = deviceName + "123"; + let isHasRight = usbManager.hasRight(deviceName); + hilog.info(domain, tag, 'usb [', deviceName, '] hasRight ret : ' + isHasRight); + expect(isHasRight).assertFalse(); + } + } catch (err) { + hilog.info(domain, tag, 'test_hasRight_15 catch err : ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + it("test_removeRight001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'test_removeRight17'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + } + try { + let remRight = usbManager.removeRight(devices.name); + hilog.info(domain, tag, 'usb case test_removeRight17 ret : ' + remRight); + expect(remRight).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'test_removeRight17 catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + it("test_connectDevice001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB test_connectDevice18 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + } + try { + let deviceName = devices.name; + let isHasRight: boolean = await usbManager.requestRight(deviceName); + if (isHasRight) { + hilog.info(domain, tag, 'requestRight is true'); + } + gPipe = usbManager.connectDevice(devices); + hilog.info(domain, tag, 'test_connectDevice18 success gPipe.busNum : ' + gPipe.busNum); + hilog.info(domain, tag, 'test_connectDevice18 success gPipe.devAddress : ' + gPipe.devAddress); + expect(gPipe.busNum > 0).assertTrue(); + expect(gPipe.devAddress > 0).assertTrue(); + + expect(gPipe.busNum < 256).assertTrue(); + expect(gPipe.devAddress < 128).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'test_connectDevice18 catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + it("tes_addDeviceAccessRight001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB tes_addDeviceAccessRight19 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + } + try { + let isHasRight = await usbManager.requestRight(devices.name); + let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; + let data = bundleManager.getBundleInfoForSelfSync(bundleFlags); + hilog.info(domain, tag, 'getBundleInfoForSelfSync: ' + JSON.stringify(data)); + let tokenId = data.appInfo.accessTokenId; + + hilog.info(domain, tag, 'accessTokenId: ' + JSON.stringify(tokenId)); + let ret = usbManager.addDeviceAccessRight(JSON.stringify(tokenId), devices.name); + if (ret) { + hilog.info(domain, tag, 'tes_addDeviceAccessRight19 success:' + ret); + } else { + hilog.info(domain, tag, 'tes_addDeviceAccessRight19 failed:' + ret); + } + expect(ret).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'tes_addDeviceAccessRight19 catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + + it("test_getFunctionsFromString001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB test_getFunctionsFromString20 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + let ret = usbManager.getFunctionsFromString('acm'); + if (ret) { + hilog.info(domain, tag, 'test_getFunctionsFromString20 success:' + ret); + } else { + hilog.info(domain, tag, 'test_getFunctionsFromString20 failed:' + ret); + } + expect(ret === 1).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'test_getFunctionsFromString20 catch err code: ' + JSON.stringify(err)); + } + done(); + }) + + + it("test_getStringFromFunctions001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'test_getStringFromFunctions21'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + + let ret = usbManager.getStringFromFunctions(usbManager.FunctionType.ACM); + if (ret) { + hilog.info(domain, tag, 'getStringFromFunctions success:' + ret); + } else { + hilog.info(domain, tag, 'getStringFromFunctions failed:' + ret); + } + expect(ret).assertEqual('acm'); + } catch (err) { + hilog.info(domain, tag, 'test_getStringFromFunctions catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + + it("test_getDeviceFunctions001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB test_getDeviceFunctions23 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + let ret = usbManager.getDeviceFunctions(); + } catch (err) { + hilog.info(domain, tag, 'test_getDeviceFunctions catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + it("test_setDeviceFunctions", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'usb testsetDeviceFunctionsSync001 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + } + try { + + let ret = usbManager.setDeviceFunctions(usbManager.FunctionType.ACM); + if (ret) { + hilog.info(domain, tag, 'setDeviceFunctions success:' + ret); + } else { + hilog.info(domain, tag, 'setDeviceFunctions failed:' + ret); + } + + } catch (err) { + hilog.info(domain, tag, 'test_setDeviceFunctions catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + hilog.info(domain, tag, 'usb test_setDeviceFunctions end'); + done(); + }) + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/usb_resetDevice_test.ets b/frameworks/ets/taihe/usb_manager/test/xts/usb_resetDevice_test.ets new file mode 100644 index 00000000..d4610f23 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/usb_resetDevice_test.ets @@ -0,0 +1,153 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../../hypium/index"; +import hilog from '@ohos.hilog' +import { BusinessError } from '@ohos.base'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import common from '@ohos.app.ability.common'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; +import bundleManager from '@ohos.bundle.bundleManager'; + +let gDeviceList: Array> = usbManager.getDevices(); +let devices: usbManager.USBDevice = gDeviceList[0]; +let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); +let isDeviceConnected: boolean; +let tmpPipe: usbManager.USBDevicePipe; +let iface: usbManager.USBInterface; +let config: usbManager.USBConfiguration; +let accessory: usbManager.USBAccessory; +let powerRole: usbManager.PowerRoleType; +let dataRole: usbManager.DataRoleType; +let param: usbManager.USBDeviceRequestParams; +let isDevAccessoryFunc: boolean; +let accList: Array = usbManager.getAccessoryList(); +let accessInfo: usbManager.USBAccessory; +let accessInfoTest: usbManager.USBAccessory = { + manufacturer: 'manufacturer', + product: 'product', + description: 'description', + version: 'version', + serialNumber: 'serialNumber' +} + +let domain: number = 0x0000; +let tag: string = 'testTag'; +const PARAM_NULLSTRING: string = ""; + +function devAccessoryFunc() { + if (accList.length > 0) { + hilog.info(domain, tag, "This USB device is accessory function"); + return true; + } + hilog.info(domain, tag, "This USB device is accessory function"); + return false; +} + +function getTransfersParam(gPipe: usbManager.USBDevicePipe, flagsValue: usbManager.UsbTransferFlags, + endpointValue: number, typeValue: usbManager.UsbEndpointTransferType, timeOutValue: number) { + let transferParams: usbManager.UsbDataTransferParams = { + devPipe: gPipe, + flags: flagsValue, + endpoint: endpointValue, + type: typeValue, + timeout: timeOutValue, + length: 1000, + callback: () => { + }, + userData: new Uint8Array(1000), + buffer: new Uint8Array(1000), + isoPacketCount: 0, + }; + return transferParams; +} + +function deviceConnected() { + if (gDeviceList.length > 0) { + hilog.info(domain, tag, "Test USB device is connected"); + return true; + } + hilog.info(domain, tag, "Test USB device is not connected"); + return false; +} + +function getPipe(testCaseName: string) { + gPipe = usbManager.connectDevice(devices); + hilog.info(domain, tag, `usb ${testCaseName} connectDevice getPipe ret: ${JSON.stringify(gPipe)}`); + expect(gPipe !== null).assertTrue(); +} + +function toClosePipe(testCaseName: string) { + let isPipClose = usbManager.closePipe(gPipe); + console.info(domain, tag, `usb ${testCaseName} closePipe getPipe ret: ${isPipClose}`); + expect(isPipClose).assertEqual(0); +} + + +export default function abilityTest() { + + describe("abilityTest", (): void => { + hilog.info(domain, tag, '%{public}s', 'describe start'); + beforeAll(() => { + hilog.info(domain, tag, '%{public}s', 'beforeAll start'); + let abilityDelegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() + abilityDelegator.addAbilityMonitor({ + abilityName: "EntryAbility", + moduleName: "entry", + onAbilityCreate: (abilitys: UIAbility): void => { + }, + }, (err: BusinessError): void => { + if (err != null) { + hilog.info(domain, tag, '%{public}s', '-----' + err.code); + } + hilog.info(domain, tag, '%{public}s', 'BusinessError end'); + }); + await Utils.msSleep(2000) + abilityDelegator.executeShellCommand("aa start -a EntryAbility -b com.example.helloworld") + await Utils.msSleep(2000) + hilog.info(domain, tag, '%{public}s', 'beforeAll end'); + + + gDeviceList = usbManager.getDevices(); + hilog.info(domain, tag, '获取设备信息: %{public}s', JSON.stringify(gDeviceList)); + + isDeviceConnected = deviceConnected(); + if (isDeviceConnected) { + devices = gDeviceList[0]; + let hasRight = usbManager.hasRight(devices.name); + if (!hasRight) { + hilog.info(domain, tag, `beforeAll: usb requestRight start`); + } + } + + isDevAccessoryFunc = devAccessoryFunc(); + if (isDevAccessoryFunc) { + accList = usbManager.getAccessoryList(); + accessInfo = accList[0]; + hilog.info(domain, tag, 'beforeAll ret : ', JSON.stringify(accList)); + } + }) + it("test_resetUsbDevice001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, ' resetUsbDevice begin'); + + try { + let devicesList: Array = usbManager.getDevices(); + if (devicesList.length == 0) { + hilog.info(domain, tag, 'device list is empt'); + } + + usbManager.requestRight(devicesList[0].name); + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]); + let ret: boolean = usbManager.resetUsbDevice(devicePipe); + hilog.info(domain, tag, `resetUsbDevice ret =${ret}`); + expect(ret == true).assertTrue(); + let ret0: number = usbManager.closePipe(devicePipe); + } catch (err) { + hilog.info(domain, tag, '%{public}s', 'test_resetUsbDevice001'); + } + hilog.info(domain, tag, 'usb test_resetUsbDevice end'); + done(); + }) + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/usb_transfer_test.ets b/frameworks/ets/taihe/usb_manager/test/xts/usb_transfer_test.ets new file mode 100644 index 00000000..2285d40c --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/usb_transfer_test.ets @@ -0,0 +1,345 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../../hypium/index"; +import hilog from '@ohos.hilog' +import { BusinessError } from '@ohos.base'; +import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import common from '@ohos.app.ability.common'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; +import bundleManager from '@ohos.bundle.bundleManager'; + +let gDeviceList: Array> = usbManager.getDevices(); +let devices: usbManager.USBDevice = gDeviceList[0]; +let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); +let isDeviceConnected: boolean; +let tmpPipe: usbManager.USBDevicePipe; +let iface: usbManager.USBInterface; +let config: usbManager.USBConfiguration; +let accessory: usbManager.USBAccessory; +let powerRole: usbManager.PowerRoleType; +let dataRole: usbManager.DataRoleType; +let param: usbManager.USBDeviceRequestParams; +let isDevAccessoryFunc: boolean; +let accList: Array = usbManager.getAccessoryList(); +let accessInfo: usbManager.USBAccessory; +let accessInfoTest: usbManager.USBAccessory = { + manufacturer: 'manufacturer', + product: 'product', + description: 'description', + version: 'version', + serialNumber: 'serialNumber' +} + +let domain: number = 0x0000; +let tag: string = 'testTag'; +const PARAM_NULLSTRING: string = ""; + +function devAccessoryFunc() { + if (accList.length > 0) { + hilog.info(domain, tag, "This USB device is accessory function"); + return true; + } + hilog.info(domain, tag, "This USB device is accessory function"); + return false; +} + +function getTransfersParam(gPipe: usbManager.USBDevicePipe, flagsValue: usbManager.UsbTransferFlags, + endpointValue: number, typeValue: usbManager.UsbEndpointTransferType, timeOutValue: number) { + let transferParams: usbManager.UsbDataTransferParams = { + devPipe: gPipe, + flags: flagsValue, + endpoint: endpointValue, + type: typeValue, + timeout: timeOutValue, + length: 1000, + callback: () => { + }, + userData: new Uint8Array(1000), + buffer: new Uint8Array(1000), + isoPacketCount: 0, + }; + return transferParams; +} + +function deviceConnected() { + if (gDeviceList.length > 0) { + hilog.info(domain, tag, "Test USB device is connected"); + return true; + } + hilog.info(domain, tag, "Test USB device is not connected"); + return false; +} + +function getPipe(testCaseName: string) { + gPipe = usbManager.connectDevice(devices); + hilog.info(domain, tag, `usb ${testCaseName} connectDevice getPipe ret: ${JSON.stringify(gPipe)}`); + expect(gPipe !== null).assertTrue(); +} + +function toClosePipe(testCaseName: string) { + let isPipClose = usbManager.closePipe(gPipe); + console.info(domain, tag, `usb ${testCaseName} closePipe getPipe ret: ${isPipClose}`); + expect(isPipClose).assertEqual(0); +} + + +export default function abilityTest() { + + describe("abilityTest", (): void => { + hilog.info(domain, tag, '%{public}s', 'describe start'); + beforeAll(() => { + hilog.info(domain, tag, '%{public}s', 'beforeAll start'); + let abilityDelegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() + abilityDelegator.addAbilityMonitor({ + abilityName: "EntryAbility", + moduleName: "entry", + onAbilityCreate: (abilitys: UIAbility): void => { + }, + }, (err: BusinessError): void => { + if (err != null) { + hilog.info(domain, tag, '%{public}s', '-----' + err.code); + } + hilog.info(domain, tag, '%{public}s', 'BusinessError end'); + }); + await Utils.msSleep(2000) + abilityDelegator.executeShellCommand("aa start -a EntryAbility -b com.example.helloworld") + await Utils.msSleep(2000) + hilog.info(domain, tag, '%{public}s', 'beforeAll end'); + + + gDeviceList = usbManager.getDevices(); + hilog.info(domain, tag, '获取设备信息: %{public}s', JSON.stringify(gDeviceList)); + + isDeviceConnected = deviceConnected(); + if (isDeviceConnected) { + devices = gDeviceList[0]; + let hasRight = usbManager.hasRight(devices.name); + if (!hasRight) { + hilog.info(domain, tag, `beforeAll: usb requestRight start`); + } + } + + isDevAccessoryFunc = devAccessoryFunc(); + if (isDevAccessoryFunc) { + accList = usbManager.getAccessoryList(); + accessInfo = accList[0]; + hilog.info(domain, tag, 'beforeAll ret : ', JSON.stringify(accList)); + } + }) + it("testUsbSubmitTransfer001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'interrupt testUsbSubmitTransfer003 enter'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb testUsbSubmitTransfer001 No device is connected'); + expect(isDeviceConnected).assertFalse(); + done() + } + let devicesList: Array = usbManager.getDevices(); + if (devicesList.length == 0) { + hilog.info(domain, tag, 'device list is empty'); + } + + let devices: usbManager.USBDevice = devicesList[0]; + usbManager.requestRight(devices.name); + let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let tmpInterface: usbManager.USBInterface = devices.configs[0].interfaces[0]; + let flags: usbManager.UsbTransferFlags = usbManager.UsbTransferFlags.USB_TRANSFER_FREE_BUFFER; + let type: usbManager.UsbEndpointTransferType = usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT; + let transferParams: usbManager.UsbDataTransferParams = getTransfersParam(gPipe, flags, 129, type, 2000); + usbManager.claimInterface(gPipe, tmpInterface, true); + try { + transferParams.callback = (err: BusinessError, callBackData: usbManager.SubmitTransferCallback) => { + hilog.info(domain, tag, 'callBackData = ' + JSON.stringify(callBackData)); + hilog.info(domain, tag, + 'testUsbSubmitTransfer003 transfer success, result = ' + transferParams.buffer.toString()); + hilog.info(domain, tag, 'status = ' + callBackData.status); + expect(callBackData.status == 2).assertEqual(true); + usbManager.closePipe(gPipe); + hilog.info(domain, tag, 'interrupt testUsbSubmitTransfer003 end'); + done() + } + usbManager.usbSubmitTransfer(transferParams); + } catch (error) { + let err: BusinessError = error as BusinessError; + hilog.info(domain, tag, 'interrupt error:', err.code); + usbManager.closePipe(gPipe); + done() + } + }) + + /** + * @tc.number : SUB_USB_Host_JS_usbCancelTransfer_Func_0100 + * @tc.name : testUsbCancelTransfer001 + * @tc.desc : interrupt transfer cancel successfully. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testUsbCancelTransfer001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'interrupt testUsbCancelTransfer004 enter'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb testUsbCancelTransfer004 No device is connected'); + expect(isDeviceConnected).assertFalse(); + done() + } + let devicesList: Array = usbManager.getDevices(); + if (devicesList.length == 0) { + hilog.info(domain, tag, 'device list is empty'); + } + let devices: usbManager.USBDevice = devicesList[0]; + usbManager.requestRight(devices.name); + let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let endpoint = devices.configs[0].interfaces[0]?.endpoints.find((value) => { + return value.direction === 0 && value.type === 2 + }) + let flags: usbManager.UsbTransferFlags = usbManager.UsbTransferFlags.USB_TRANSFER_FREE_BUFFER; + let type: usbManager.UsbEndpointTransferType = usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT; + let transferParams: usbManager.UsbDataTransferParams = getTransfersParam(gPipe, flags, 129, type, 2000); + // let err = 0; + try { + // transferParams.endpoint = endpoint?.address as number; + // transferParams.callback = (err: BusinessError, callBackData: usbManager.SubmitTransferCallback) => { + // hilog.info(domain, tag, 'callBackData ==============' + JSON.stringify(callBackData)); + // } + usbManager.usbSubmitTransfer(transferParams); + usbManager.usbCancelTransfer(transferParams); + hilog.info(domain, tag, 'USB transfer request submitted.'); + } catch (error: BusinessError) { + hilog.info(domain, tag, 'testUsbCancelTransfer004 catch err code================: ' + JSON.stringify(error)); + } + done(); + }) + + /** + * @tc.number : SUB_USB_Host_JS_usbCancelTransfer_ErrCode_0100 + * @tc.name : testUsbCancelTransfer002 + * @tc.desc : interrupt transfer cancel failed. + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it("testUsbCancelTransfer001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'interrupt testUsbCancelTransfer005 enter'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb testUsbCancelTransfer004 No device is connected'); + expect(isDeviceConnected).assertFalse(); + done() + } + let devicesList: Array = usbManager.getDevices(); + if (devicesList.length == 0) { + hilog.info(domain, tag, 'device list is empty'); + } + let devices: usbManager.USBDevice = devicesList[0]; + usbManager.requestRight(devices.name); + let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let endpoint = devices.configs[0].interfaces[0]?.endpoints.find((value) => { + return value.direction === 0 && value.type === 2 + }) + let flags: usbManager.UsbTransferFlags = usbManager.UsbTransferFlags.USB_TRANSFER_FREE_BUFFER; + let type: usbManager.UsbEndpointTransferType = usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT; + let transferParams: usbManager.UsbDataTransferParams = getTransfersParam(gPipe, flags, 129, type, 2000); + // let err = 0; + try { + usbManager.usbCancelTransfer(transferParams); + expect().assertFail(); + hilog.info(domain, tag, 'USB transfer request submitted.'); + } catch (error: BusinessError) { + hilog.info(domain, tag, 'interrupt cancel failed:' + error.code); + expect(error.code).assertEqual(14400011); + } + done(); + }) + + it("test_usbControlTransfer01", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'usb usbControlTransfer begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + let param: usbManager.USBDeviceRequestParams = { + bmRequestType: 0x80, + bRequest: 0x06, + wValue: (0x01 << 8) | 0x00, + wIndex: 0x00, + wLength: 18, + data: new Uint8Array(18), + }; + try { + let devicesList: Array = usbManager.getDevices(); + if (devicesList.length == 0) { + hilog.info(domain, tag, 'device list is empty'); + } + + usbManager.requestRight(devicesList[0].name); + hilog.info(domain, tag, `usbControlTransfer name = ${devicesList[0].name}`); + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(devicesList[0]); + let timeout: number | undefined = 30.0; + + hilog.info(domain, tag, `usbControlTransfer device.name = ${devicesList[0].name}`); + let ret = usbManager.usbControlTransfer(devicePipe, param, timeout).then((ret: number) => { + hilog.info(domain, tag, `usbControlTransfer size= ${ret}`); + expect(ret == 18).assertEqual(true); + }) + usbManager.closePipe(devicePipe); + } catch (error: BusinessError) { + hilog.info(0, 'testTag ui', `closeAccessory error `) + hilog.info(domain, tag, 'usbControlTransfer end'); + let err: BusinessError = error as BusinessError; + hilog.info(domain, tag, `usbControlTransferlnn0 err.code= ${err.code}`); + } + done(); + }) + + it("test_bulkTransfer02", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'usb test_bulkTransfer02 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + + try { + let devicesList: Array = usbManager.getDevices(); + if (devicesList.length == 0) { + hilog.info(domain, tag, 'device list is empty'); + } + + let device: usbManager.USBDevice = devicesList[0]; + usbManager.requestRight(device.name); + + let devicePipe: usbManager.USBDevicePipe = usbManager.connectDevice(device); + hilog.info(domain, tag, `usbManager.connectDevice(device) = ${devicePipe.busNum}`); + hilog.info(domain, tag, `usbManager.connectDevice(device) = ${devicePipe.devAddress}`); + let interfaces: usbManager.USBInterface = device.configs[0].interfaces[0]; + let endpoint: usbManager.USBEndpoint = + device.configs[0].interfaces[0].endpoints[0]; //read 0x81 光驱 ; 1 U盘 write + hilog.info(domain, tag, `usbManager.USBEndpoint = ${endpoint}`); + let ret: number = usbManager.claimInterface(devicePipe, interfaces, true); + hilog.info(domain, tag, `bulkTransfer begin = ${ret}`); + if (ret == 0) { + hilog.info(domain, tag, 'USB claim sucess'); + let bufferTransfer = new Uint8Array(128); + + hilog.info(domain, tag, `test_bulkTransfer name = ${devicesList[0].name}`); + hilog.info(domain, tag, `test_bulkTransfer buffer = ${bufferTransfer}`); + let timeout: number | undefined = 8000.0; + + usbManager.bulkTransfer(devicePipe, endpoint, bufferTransfer, timeout).then((retVal: number) => { + hilog.info(domain, tag, `test_bulkTransfer02 retVal = ${retVal}`); + expect(retVal == 128).assertTrue(); + }); + } + let ret0 = usbManager.releaseInterface(devicePipe, interfaces); + console.log(`releaseInterface = ${ret0}`); + hilog.info(domain, tag, `bulkTransfer end `); + usbManager.closePipe(devicePipe); + } catch (error: BusinessError) { + hilog.info(domain, tag, `bulkTransfer error `) + hilog.info(domain, tag, `bulkTransfer err.code= ${error.code}`); + } + done(); + }) + }) +} \ No newline at end of file -- Gitee