diff --git a/bundle.json b/bundle.json index b25043334244477a667257643d4deddf8f447e65..486e9332e947ee5c952e07f14bf88519da004469 100644 --- a/bundle.json +++ b/bundle.json @@ -58,7 +58,8 @@ "cJSON", "bounds_checking_function", "hitrace", - "runtime_core" + "runtime_core", + "eventhandler" ] }, "build": { @@ -68,8 +69,8 @@ "//base/usb/usb_manager/interfaces/innerkits:usbsrv_client", "//base/usb/usb_manager/interfaces/kits/js/napi:usbmanager", "//base/usb/usb_manager/interfaces/kits/js/napi:usb", - "//base/usb/usb_manager/frameworks/dialog/dialog_ui/usb_right_dialog:dialog_hap", "//base/usb/usb_manager/frameworks/ets/taihe:usb_taihe", + "//base/usb/usb_manager/frameworks/dialog/dialog_ui/usb_right_dialog:dialog_hap", "//base/usb/usb_manager/interfaces/kits/js/napi:serial" ], "service_group": [ diff --git a/frameworks/ets/taihe/BUILD.gn b/frameworks/ets/taihe/BUILD.gn index 3e49595f2566128e629e5840fe5203fd6157e55c..1fdd4a897efe60e4a1fbd1d8b797ca3fe4382736 100644 --- a/frameworks/ets/taihe/BUILD.gn +++ b/frameworks/ets/taihe/BUILD.gn @@ -1,19 +1,19 @@ -# 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/ohos.gni") - -group("usb_taihe") { - deps = [ "usb_manager:usbManager_taihe" ] -} +# 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/ohos.gni") + +group("usb_taihe") { + deps = [ "usb_manager:usbManager_taihe" ] +} diff --git a/frameworks/ets/taihe/usb_manager/BUILD.gn b/frameworks/ets/taihe/usb_manager/BUILD.gn index a9358c34a4a8b8206ed38799397fc287194c34dc..90cb4571d92323ea2c8c69adcc5be38c36e11329 100644 --- a/frameworks/ets/taihe/usb_manager/BUILD.gn +++ b/frameworks/ets/taihe/usb_manager/BUILD.gn @@ -1,93 +1,129 @@ -# 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", - ] -} +import("//build/config/components/ets_frontend/ets2abc_config.gni") +import("//build/ohos.gni") +import("//build/ohos/taihe_idl/taihe.gni") + +import("./../../../../usbmgr.gni") + +copy_taihe_idl("copy_usbManager") { + sources = [ + "idl/ohos.usbManager.taihe", + "idl/ohos.usbManager.serial.taihe" + ] + # external_deps = [] +} + +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") + + include_dirs = [ + "../common/include", + ] + sources += [ + "src/ani_constructor.cpp", + "src/ohos.usbManager.impl.cpp", + "src/ohos.usbManager.serial.impl.cpp" + ] + + configs = [ + "${utils_path}:utils_config", + ] + + 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("usbmanager_abc") { + base_url = "$taihe_generated_file_path" + files = [ "$taihe_generated_file_path/@ohos.usbManager.ets" ] + is_boot_abc = "True" + device_dst_file = "/system/framework/usbmanager_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/usbmanager_abc.abc" + module_install_dir = "framework" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps = [ ":usbmanager_abc" ] +} + +ohos_prebuilt_etc("usbmanager_serial_etc") { + source = "$target_out_dir/usbmanager_serial_abc.abc" + part_name = "$part_name" + subsystem_name = "$subsystem_name" + deps=[":usbmanager_serial_abc"] +} + +generate_static_abc("usbmanager_test") { + base_url = "./" + files = ["test/usbmanager_test.ets"] + is_boot_abc = "True" + device_dst_file = "/system/framework/usbmanager_test.abc" + dependencies = [":run_taihe"] +} + +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 0000000000000000000000000000000000000000..3afee05dfc66895c3f1bf6e058bab044ae5337dd --- /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("usbmanager_serial_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 0000000000000000000000000000000000000000..12e2432a539013be6431aca95e13118dd16ab1b3 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/idl/ohos.usbManager.taihe @@ -0,0 +1,386 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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; + + endpointNumber: 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 3d2724826141748a8e7811b48cf19f3e2eb59577..0000000000000000000000000000000000000000 --- 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; - endpointNumber: 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 e14b885e71d290c9c7ec64b7782882b8f75bb101..a03b7b8c1529ff75bbee4969052be4fcd351636f 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) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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 0000000000000000000000000000000000000000..1e22bf0fe46f6cf1e616709af6a835b0a25283d6 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.impl.cpp @@ -0,0 +1,1252 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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.1.h" + +using namespace taihe; +// using namespace taihe::usbManager; +using namespace ohos::usbManager; +using OHOS::Ashmem; +using OHOS::sptr; +using OHOS::USB::MODULE_JS_ANI; +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; + +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), + .endpointNumber = 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_ANI, "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, ""); + } + bool result = g_usbClient.HasRight(std::string(deviceName)); + return result; +} + +bool requestRightSync(string_view deviceName) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + bool bRet = false; + int32_t ret = g_usbClient.RequestRight(std::string(deviceName)); + if (ret == OHOS::USB::UEC_OK) { + bRet = true; + } else { + USB_HILOGE(MODULE_JS_ANI, "RequestRight failed, return code:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + + return bRet; +} + +bool removeRight(string_view deviceName) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + bool bResult = false; + int32_t ret = g_usbClient.RemoveRight(std::string(deviceName)); + if (ret == OHOS::USB::UEC_OK) { + bResult = true; + } else { + USB_HILOGE(MODULE_JS_ANI, "RemoveRight failed, return code:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + return bResult; +} + +bool addDeviceAccessRight(string_view tokenId, string_view deviceName) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + bool bResult = false; + 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"); + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, "Permission not allowed"); + } else { + ThrowBusinessError(ret, ""); + } + return bResult; +} + +double getFunctionsFromString(string_view funcs) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(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, ""); + } + if (numFuncs == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + } + return static_cast(numFuncs); +} + +string getStringFromFunctions(FunctionType funcs) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + std::string strFuncs = g_usbClient.UsbFunctionsToString(funcs); + if (strFuncs == OHOS::USB::PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_NORMAL_APP_NOT_ALLOWED, ""); + } + if (strFuncs == OHOS::USB::SYS_APP_PERMISSION_DENIED_SYSAPI) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + } + return strFuncs; +} + +void setDeviceFunctionsSync(FunctionType funcs) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + 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, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_DENIED_SYSAPI_FAILED) { + ThrowBusinessError(OHEC_COMMON_PERMISSION_NOT_ALLOWED, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_PERMISSION_CHECK_HDC) { + ThrowBusinessError(UEC_COMMON_HDC_NOT_ALLOWED, ""); + } else if (ret == OHOS::USB::UEC_SERVICE_FUNCTION_NOT_SUPPORT) { + ThrowBusinessError(UEC_COMMON_FUNCTION_NOT_SUPPORT, ""); + } else { + USB_HILOGE(MODULE_JS_ANI, "setDeviceFunctionsSync failed, return code:%{public}d", ret); + ThrowBusinessError(ret, ""); + } +} + +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_ANI, "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_ANI, "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_ANI, "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_ANI, "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_ANI, "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_ANI, "getRawDescriptor failed:%{public}d", ret); + ThrowBusinessError(ret, ""); + } + return ::taihe::array(taihe::array_view(bufferData.data(), bufferData.size())); +} + +double getFileDescriptor(USBDevicePipe const &pipe) +{ + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + } + int32_t fd = -1; + OHOS::USB::USBDevicePipe internalPipe = ConvertUSBDevicePipe(pipe); + int32_t ret = g_usbClient.GetFileDescriptor(internalPipe, fd); + if (ret != OHOS::USB::UEC_OK) { + USB_HILOGE(MODULE_JS_ANI, "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 -1; + } + std::cerr << "usbControlTransferSync enter." << std::endl; + OHOS::USB::USBDevicePipe nativePipe; + nativePipe.SetBusNum(static_cast(pipe.busNum)); + nativePipe.SetDevAddr(static_cast(pipe.devAddress)); + std::cerr << "busNum: " << pipe.busNum << std::endl; + std::cerr << "devAddress: " << pipe.devAddress << std::endl; + int32_t timeOut = 0; + if (timeout.has_value()) { + timeOut = int(timeout.value()); + } + std::cerr << "timeout: " << timeOut << std::endl; + const OHOS::HDI::Usb::V1_2::UsbCtrlTransferParams tctrl = {requestparam.bmRequestType, requestparam.bRequest, + requestparam.wValue, requestparam.wIndex, requestparam.wLength, timeOut}; + std::cerr << "bmRequestType: " << requestparam.bmRequestType << std::endl; + std::cerr << "bRequest: " << requestparam.bRequest << std::endl; + std::cerr << "wValue: " << requestparam.wValue << std::endl; + std::cerr << "wIndex: " << requestparam.wIndex << std::endl; + std::cerr << "wLength: " << requestparam.wLength << std::endl; + + 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)) { + std::cerr << "Object_GetFieldByName_Ref failed." << std::endl; + return -1; + } + void *data; + size_t size; + if (ANI_OK != env->ArrayBuffer_GetInfo(static_cast(bufferRef), &data, &size)) { + std::cerr << "ArrayBuffer_GetInfo failed." << std::endl; + return -1; + } + + std::cerr << "size: " << size << std::endl; + + 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 -1; + } + + 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 -1; + } + + 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)) { + std::cerr << "Object_GetFieldByName_Ref failed." << std::endl; + return -1; + } + void *data; + size_t size; + if (ANI_OK != env->ArrayBuffer_GetInfo(static_cast(bufferRef), &data, &size)) { + std::cerr << "ArrayBuffer_GetInfo failed." << std::endl; + return -1; + } + + 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 -1; + } +} + +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_ANI, "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_HILOGI(MODULE_JS_ANI, "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_HILOGI(MODULE_JS_ANI, "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_HILOGI(MODULE_JS_ANI, "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_HILOGI(MODULE_JS_ANI, "func is nullptr!"); + return false; + } + + if (!mainHandler) { + auto runner = OHOS::AppExecFwk::EventRunner::GetMainEventRunner(); + if (!runner) { + USB_HILOGI(MODULE_JS_ANI, "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_ANI, "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_HILOGI(MODULE_JS_ANI, "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_ANI, "GetEnv failed."); + return; + } + } + if (ANI_OK != env->CreateLocalScope(LOCAL_SCOPE_SIZE)) { + USB_HILOGI(MODULE_JS_ANI, "CreateLocalScope failed."); + return; + } + auto businessError = GetDefaultBusinessError(env); + auto param = ohos_usbManager_SubmitTransferCallback_intoANI(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_ANI, "%{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_ANI, "AniCallBack enter 5 call returned %{public}d.", errCode); + }; + if (!SendEventToMainThread(task)) { + USB_HILOGI(MODULE_JS_ANI, "SendEventToMainThread failed."); + } +} + +void usbSubmitTransfer(UsbDataTransferParams const &transfer) +{ + USB_HILOGE(MODULE_JS_ANI, "SubmitTransfer enter"); + if (!HasFeature(FEATURE_HOST)) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return; + } + std::cerr << "usbSubmitTransfer enter." << std::endl; + auto asyncContext = new (std::nothrow) USBTransferAsyncContext(); + if (asyncContext == nullptr) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return; + } + asyncContext->pipe.SetBusNum(static_cast(transfer.devPipe.busNum)); + asyncContext->pipe.SetDevAddr(static_cast(transfer.devPipe.devAddress)); + asyncContext->flags = transfer.flags; + asyncContext->endpoint = transfer.endpoint; + asyncContext->type = transfer.type; + asyncContext->timeOut = transfer.timeout; + asyncContext->length = transfer.length; + asyncContext->numIsoPackets = transfer.isoPacketCount; + + ani_ref buffer; + ani_env *env = ::taihe::get_env(); + ani_vm *vm = nullptr; + auto status = env->GetVM(&vm); + if (ANI_OK != status) { + ThrowBusinessError(CAPABILITY_NOT_SUPPORT, ""); + return; + } + asyncContext->vm = vm; + ani_object array_obj = reinterpret_cast(transfer.buffer); + if (ANI_OK != env->Object_GetFieldByName_Ref(array_obj, "buffer", &buffer)) { + std::cerr << "Object_GetFieldByName_Ref failed." << std::endl; + return; + } + void *data; + size_t size; + if (ANI_OK != env->ArrayBuffer_GetInfo(static_cast(buffer), &data, &size)) { + std::cerr << "ArrayBuffer_GetInfo failed." << std::endl; + return; + } + asyncContext->buffer = static_cast(data); + asyncContext->bufferLength = size; + ani_ref callback; + env->GlobalReference_Create(reinterpret_cast(transfer.callback), &callback); + asyncContext->callbackRef = reinterpret_cast(callback); + USB_HILOGE(MODULE_JS_ANI, "bufferLength:%{public}d", asyncContext->bufferLength); + + 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; + std::uintptr_t ptrValue = reinterpret_cast(asyncContext); + obj.userData = static_cast(ptrValue); + + if (!CreateAndWriteAshmem(asyncContext, obj)) { + return; + } + + USB_HILOGE(MODULE_JS_ANI, "CreateAndWriteAshmem OK."); + + static auto func = [](const OHOS::USB::TransferCallbackInfo &info, + const std::vector &isoInfo, + uint64_t userData) -> void { + USBTransferAsyncContext *asyncContext = reinterpret_cast(userData); + return AniCallBack(asyncContext, info, isoInfo); + }; + + int32_t ret = asyncContext->pipe.UsbSubmitTransfer(obj, func, asyncContext->ashmem); + USB_HILOGE(MODULE_JS_ANI, "usbSubmitTransfer ret: %{public}d", ret); + if (ret != OHOS::USB::UEC_OK) { + asyncContext->ashmem->CloseAshmem(); + delete asyncContext; + ret = UsbSubmitTransferErrorCode(ret); + ThrowBusinessError(ret, ""); + } + USB_HILOGE(MODULE_JS_ANI, "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) +{ + TH_THROW(std::runtime_error, "resetUsbDevice not implemented"); +} + +} // 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 0000000000000000000000000000000000000000..2230c0d19b1f9448bbf326d539f50364446ed9e0 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/src/ohos.usbManager.serial.impl.cpp @@ -0,0 +1,468 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT 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(); + +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; + int32_t ret = g_usbClient.SerialGetPortList(portIds); + if (ret < 0) { + USB_HILOGE(MODULE_USB_INNERKIT, "GetPortList failed, ErrCode: %{public}d", ret); + } + std::vector tempPortList; + 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!"); + 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)); + 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!"); + 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!"); + return; + } + + if (attribute.parity.has_value()) { + serialAttribute.parity_ = attribute.parity.value(); + } else { + USB_HILOGE(MODULE_USB_INNERKIT, "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!"); + 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)); + } + 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!"); + return -1; + } + + if (buffer.size() > MAX_READ_BUF_SIZE) { + USB_HILOGE(MODULE_USB_INNERKIT, "buffer size > 8192 byte!"); + return -1; + } + + 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!"); + } + 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)); + return ErrorCodeConversion(ret); + } + buffer = bufferData; + USB_HILOGI(MODULE_USB_INNERKIT, "readSync finish, status: %{public}d", ret); + return ret; +} + +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!"); + return -1; + } + + if (buffer.size() > MAX_WRITE_BUF_SIZE) { + USB_HILOGE(MODULE_USB_INNERKIT, "buffer size > 128kb!"); + return -1; + } + + 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!"); + } + 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)); + return ErrorCodeConversion(ret); + } + USB_HILOGI(MODULE_USB_INNERKIT, "writeSync finish, status: %{public}d", ret); + return ret; +} +} // 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 9a44600133fa16b9f3518661fb749fe579e8f2e1..0000000000000000000000000000000000000000 --- 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), - .endpointNumber = 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/xts/List.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..6c0e575950159bdf8a394d229a60a95467e4f285 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/List.test.ets @@ -0,0 +1,9 @@ +import abilityTest from "./USBmanger.test"; +import abilityBaseTest from "./USBSerialBase.test" +import SerialTest from "./USBSerial.test" + +export default function testsuite() { + abilityBaseTest(); + SerialTest(); + abilityTest(); +} 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 0000000000000000000000000000000000000000..ec6729ffab01527e03b891b65c8f3100564d58c8 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/SerialBaseTest.test.ets @@ -0,0 +1,677 @@ +/* +* 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 "../../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 SerialTest() { + describe("SerialTest", (): 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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(); + } + 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 0000000000000000000000000000000000000000..99163a7d3de994ac0149e1e95ffe88672b06c1c1 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/SerialTest.test.ets @@ -0,0 +1,795 @@ +/* +* 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, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Size, Level } from "../../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 usbManager from '@ohos.usbManager'; +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]; + // hilog.info(domain, TAG, 'openPortId: ', openPortId); + // 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(); + done(); + } 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(); + serialManager.close(openPortId); + done(); + } 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(8192).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(8192).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(8192).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(8192).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 => { + hilog.info(domain, TAG, 'testWrite001 start'); + if (checkDevice() === false) { + done(); + return Promise.resolve(); + } + let writeBuffer: Uint8Array = new Uint8Array(8192).fill(1); + serialManager.open(openPortId); + serialManager.write(openPortId, writeBuffer, 500) + .then((length: number) => { + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + }) + .catch((error: Error) => { + 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(8192).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(8192).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(8192).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, 500); + 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 => { + 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); + serialManager.read(openPortId, readBuffer, 1000) + .then((length: number) => { + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + }) + .catch((error: Error) => { + 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/USBSerial.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/USBSerial.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..294afe476ef3a80d0831f90b1ef44428246aec50 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/USBSerial.test.ets @@ -0,0 +1,286 @@ +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Size, Level } from "../../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 Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; + +//import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect, TestType, Size, Level } from '@ohos/hypium' +import { Driver, On } from '@ohos.UiTest'; +import json from '@ohos.util.json'; +//import { bundleManager } from "@kit.AbilityKit"; +import buffer from '@ohos.buffer'; +import serialManager from '@ohos.usbManager.serial'; + +const TAG: string = "[SerialTest]"; + +let portIds: number[] = []; + +let domain: number = 0x0000; + +// function sleep(ms: number): Promise { +// return new Promise(resolve => setTimeout(resolve, ms)); +// } + +// async function getPermission(gPortList: Readonly[]) { +// console.info('**************getPermission**************'); +// try { +// serialManager.requestSerialRight(gPortList[0].portId).then(hasRight => { +// console.info(TAG, `usb requestRight success, hasRight: ${hasRight}`); +// }); +// } catch (err : BusinessError) { +// console.info(TAG, `usb getPermission to requestRight hasRight fail: `, err); +// return; +// } +// } + +// async function driveFn() { +// console.info('**************driveFn**************'); +// try { +// let driver = Driver.create(); +// console.info(TAG, ` come in driveFn`); +// console.info(TAG, `driver is ${JSON.stringify(driver)}`); +// await Utils.msSleep(1000); +// let on : On; +// let button = await driver.findComponent(on.text('允许')); +// console.info(TAG, `button is ${JSON.stringify(button)}`); +// await Utils.msSleep(1000); +// await Promise.resolve(button.click()); +// } catch (err : BusinessError) { +// console.info(TAG, 'err is ' + err); +// } +// } + +// async function driveDecFn() { +// console.info('**************driveDecFn**************'); +// try { +// let driver = await Driver.create(); +// console.info(TAG, ` come in driveDecFn`); +// console.info(TAG, `driver is ${JSON.stringify(driver)}`); +// await sleep(1000); +// let button = await driver.findComponent(On.text('不允许')); +// console.info(TAG, `button is ${JSON.stringify(button)}`); +// await sleep(1000); +// await button.click(); +// } catch (err : BusinessError) { +// console.info(TAG, 'err is ' + err); +// return; +// } +// } + +function checkDevice(): boolean { + let haveDevice: boolean = false; + try { + const portList = serialManager.getPortList(); + hilog.error(domain, TAG, JSON.stringify(portList)); + if (Array.isArray(portList)) { + portList.forEach((port) => { + try { + hilog.info(domain, TAG, '%{public}s', + `Success! getPortList port deviceName: ${port.deviceName}, portId: ${port.portId}`); + portIds.push(port.portId); + haveDevice = true; + } catch (innerError) { + hilog.error(domain, TAG, '%{public}s', `Failed! getPortList ${innerError}`); + } + }); + } else { + hilog.error(domain, TAG, '%{public}s', `Failed! getPortList, did not return an array: ${typeof portList}`); + haveDevice = false; + } + } catch (error) { + 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 { + //let portList: serialManager.SerialPort[] = serialManager.getPortList(); + if (checkDevice()) { + openPortId = portIds[0]; + 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 (err : BusinessError) { + console.error(TAG, 'getPermission catch err name: ', err.name, ', message: ', err.message); + } + } + } else { + //done(); + hilog.error(domain, TAG, 'no device'); + } + } catch (error : BusinessError) { + console.info(TAG, 'beforeAll error: ', JSON.stringify(error)); + } + }) + afterAll(async () => { + console.info(TAG, 'afterAll'); + serialManager.cancelSerialRight(openPortId); + serialManager.close(openPortId); + }) + + /** + * @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 { + // console.info(TAG, 'testGetAttribute001 start'); + // // if (await checkDevice() === false) { + // // done(); + // // return; + // // } + // 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) { + // console.error(TAG, 'testGetAttribute001 catch err code: ', error.code, ', message: ', error.message); + // expect().assertFail(); + // } + // }) + + /** + * @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 { + console.info(TAG, 'testReadSync002 start'); + // if (await checkDevice() === false) { + // done(); + // return; + // } + serialManager.open(openPortId); + let readSyncBuffer: Uint8Array = new Uint8Array(8192); + let length: number = serialManager.readSync(openPortId, readSyncBuffer, 500); + console.info(TAG, 'testReadSync002 length = ' + length); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + console.error(TAG, 'testReadSync002 catch err code: ', error.code, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @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 => { + console.info(TAG, 'testRead002 start'); + await Utils.msSleep(3000); + // if (await checkDevice() === false) { + // done(); + // return; + // } + let readBuffer: Uint8Array = new Uint8Array(8192); + serialManager.open(openPortId); + serialManager.read(openPortId, readBuffer, 1000) + .then((length: number) => { + console.info(TAG, 'testRead002 length = ' + length); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + }) + .catch((error: Error) => { + console.error(TAG, 'testRead002 catch err name: ', error.name, ', message: ', error.message); + expect().assertFail(); + }); + }) + + /** + * @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 { + console.info(TAG, 'testWriteSync001 start'); + // if (await checkDevice() === false) { + // done(); + // return; + // } + //let writeSyncBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf-8').buffer); + let writeSyncBuffer: Uint8Array = new Uint8Array(8192); + serialManager.open(openPortId); + let length: number = serialManager.writeSync(openPortId, writeSyncBuffer, 500); + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + } catch (error : BusinessError) { + console.error(TAG, 'testWriteSync001 catch err code: ', error.code, ', message: ', error.message); + expect().assertFail(); + } + }) + + /** + * @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 => { + console.info(TAG, 'testWrite001 start'); + // if (await checkDevice() === false) { + // done(); + // return; + // } + // let writeBuffer: Uint8Array = new Uint8Array(buffer.from('Hello World', 'utf8').buffer); + let writeBuffer: Uint8Array = new Uint8Array(8192); + serialManager.open(openPortId); + serialManager.write(openPortId, writeBuffer, 500) + .then((length: number) => { + expect(length >= 0).assertTrue(); + serialManager.close(openPortId); + done(); + }) + .catch((error: Error) => { + console.error(TAG, 'testWrite001 catch err name: ', error.name, ', message: ', error.message); + expect().assertFail(); + }); + }) + + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/USBSerialBase.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/USBSerialBase.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..6e08e4091ea8891779e292166e9cd1fff268dc47 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/USBSerialBase.test.ets @@ -0,0 +1,161 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../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 Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import serialManager from '@ohos.usbManager.serial'; +import usbManager from '@ohos.usbManager'; +import { bundleManager } from '@kit.AbilityKit'; + +let domain: number = 0x0000; +let tag: string = 'testTag'; +let testAbilityContext: common.UIAbilityContext; +let portIds: number[] = []; + +export default function abilityBaseTest() { + + describe("abilityBaseTest", (): 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 => { + testAbilityContext = abilitys.context + hilog.info(domain, tag, '%{public}s', 'onAbilityCreate end'); + + }, + }, (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'); + }) + + // afterAll(async () => { + // portIds.forEach((port) => { + // serialManager.close(port); + // }) + // }) + + // 测试 getPortList 接口 + it("testGetPortList", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, (done: () => void): void => { + try { + const portList = serialManager.getPortList(); + if (Array.isArray(portList)) { + portList.forEach((port) => { + try { + hilog.info(domain, tag, '%{public}s', + `Success! getPortList port deviceName: ${port.deviceName}, portId: ${port.portId}`); + portIds.push(port.portId); + } catch (innerError) { + hilog.error(domain, tag, '%{public}s', `Failed! getPortList ${innerError}`); + } + }); + } else { + hilog.error(domain, tag, '%{public}s', `Failed! getPortList, did not return an array: ${typeof portList}`); + } + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! getPortList, error code: ${error}`); + } + done(); + }); + + // 测试 open 接口 + it("testOpenSerialPort", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, (done: () => void): void => { + portIds.forEach((port) => { + try { + serialManager.open(port); + hilog.info(domain, tag, '%{public}s', `Success! open the serial port of port ID ${port}`); + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! open ID ${port}, error code: ${error}`); + } + done(); + }); + }); + + // 测试 hasSerialRight 接口 + it("testHasSerialRight", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, (done: () => void): void => { + portIds.forEach((port) => { + try { + const hasRight = serialManager.hasSerialRight(port); + hilog.info(domain, tag, '%{public}s', + `Success! hasSerialRight port ID ${port} have serial port permission: ${hasRight}`); + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! hasSerialRight ID ${port}, error code: ${error}`); + } + done(); + }); + }); + + + // 测试 requestSerialRight 接口 + it("testRequestSerialRightSync", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, (done: () => void): void => { + portIds.forEach((port) => { + try { + const hasRight = await serialManager.requestSerialRight(port); + hilog.info(domain, tag, '%{public}s', + `Success! requestSerialRight portId: ${port}, request for serial port permission of port ID: ${hasRight}`); + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! requestSerialRight ID ${port}, error code: ${error}`); + } + done(); + }); + }); + + // 测试 addSerialRight 接口 + it("testAddSerialRight", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + portIds.forEach((port) => { + 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; + try { + serialManager.addSerialRight(tokenId, port); + hilog.info(domain, tag, '%{public}s', + `Success! addSerialRight serial port permission for port ID ${port}, token ID: ${tokenId}`); + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! addSerialRight ID ${port}, error code: ${error}`); + } + done(); + }); + }); + + // 测试 cancelSerialRight 接口 + it("testCancelSerialRight", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, (done: () => void): void => { + portIds.forEach((port) => { + try { + serialManager.cancelSerialRight(port); + hilog.info(domain, tag, '%{public}s', `Success! cancelled serial port permission for port ID ${port}`); + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! cancelSerialRight ID ${port}, error code: ${error}`); + } + done(); + }); + }); + + // 测试 close 接口 + it("testCloseSerialPort", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, (done: () => void): void => { + portIds.forEach((port) => { + try { + serialManager.close(port); + hilog.info(domain, tag, '%{public}s', `Success! closed the serial port of port ID ${port}`); + } catch (error) { + hilog.error(domain, tag, '%{public}s', `Failed! close ID ${port}, error code: ${error}`); + } + done(); + }); + }); + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/USBmanger.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/USBmanger.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..bd41940ae8f380f672cfdc9e25beaa3d69681140 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/USBmanger.test.ets @@ -0,0 +1,827 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../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 abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@ohos.base'; + +// import { fileIo as fs } from '@kit.CoreFileKit'; + +let gDeviceList: Array>; +let devices: usbManager.USBDevice; +let gPipe: usbManager.USBDevicePipe; +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 type: usbManager.UsbEndpointTransferType; +// let transferParams: usbManager.UsbDataTransferParams; + + +let domain: number = 0x0000; //日志标识,0x0000作为测试框架的业务标识 +let tag: string = 'testTag'; //日志标识字符串,作为tag标识当前runner类下的测试行为 +//let testAbilityContext:common.UIAbilityContext; + +const PARAM_NULLSTRING: string = ""; + +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`); + } + tmpPipe.busNum = gDeviceList[0].busNum; + tmpPipe.devAddress = gDeviceList[0].devAddress; + } + }) + + 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_003", 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 { + let hasRight = usbManager.requestRight(devices.name); + if (!hasRight) { + hilog.info(domain, tag, 'requestRight true'); + } + gPipe = usbManager.connectDevice(devices); + let devs = usbManager.getRawDescriptor(gPipe); + 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_004", 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_006", 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]; + 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_007", 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]; + 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_008", 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]; + 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_009", 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]; + 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(); + }) + + + // 注意基于setenforce 0 + it("abilityTest_getFileDescriptor_0010", 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(); + }) + + // 88080504 服务器不支持切换端口 + /*it("abilityTest_setPortRoleType_0011", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'abilityTest_setPortRoleType_0011'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + let portList = usbManager.getPortList(); + let pid = 1; + let devs = usbManager.setPortRoleTypes(pid, usbManager.PowerRoleType.SOURCE, usbManager.DataRoleType.HOST); + hilog.info(domain, tag, 'setPortRoleTypesSync ret : %{public}s', JSON.stringify(devs)); + } catch (err) { + hilog.info(domain, tag, 'abilityTest_setPortRoleType_009 catch err code:%{public}s', JSON.stringify(err)); + } + done(); + })*/ + + // 会挂 + it("abilityTest_addAccessoryRight_0012", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB abilityTest_addAccessoryRight_0012 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + 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(); + }) + + it("test_hasRight_13", 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_14", 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_15", 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_requestRight16", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'test_requestRight16'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + } + try { + for (let i = 0; i < gDeviceList.length; i++) { + let deviceName = gDeviceList[i].name; + deviceName = deviceName + "abc"; + let isHasRight = await usbManager.requestRight(devices.name); + hilog.info(domain, tag, 'usb [', deviceName, '] requestRight ret : ' + isHasRight); + expect(isHasRight).assertFalse(); + } + } catch (err) { + hilog.info(domain, tag, 'test_requestRight16 catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + })*/ + + it("test_removeRight17", 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_connectDevice18", 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); + // expect(CheckEmptyUtils.isEmpty(gPipe)).assertFalse(); + hilog.info(domain, tag, 'test_connectDevice18 success gPipe.busNum : ' + gPipe.busNum); + hilog.info(domain, tag, 'test_connectDevice18 success gPipe.devAddress : ' + gPipe.devAddress); + } catch (err) { + hilog.info(domain, tag, 'test_connectDevice18 catch err code: ' + JSON.stringify(err)); + expect(err !== null).assertFalse(); + } + done(); + }) + + it("tes_addDeviceAccessRight19", 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_getFunctionsFromString20", 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_getStringFromFunctions21", 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_setDeviceFunctions22", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB test_setDeviceFunctions20 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + + let ret = usbManager.setDeviceFunctions(usbManager.FunctionType.ACM); + if (ret) { + hilog.info(domain, tag, 'setDeviceFunctions success:' + JSON.stringify(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(); + })*/ + + it("test_getDeviceFunctions23", 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(); + }) + + + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0600 + * @tc.name : testGetPortListNormalApp001 + * @tc.desc : getPortList Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + + /*it('testGetPortListNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + try { + let portList = usbManager.getPortList(); + hilog.info(domain, tag, 'testGetPortListNormalApp001 success %{public}s', + JSON.stringify(portList)); + expect(portList === null).assertTrue(); + } catch (error) { + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ' + 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() + } + }); + + /** + * @tc.number : SUB_USB_HostManager_JS_Func_0700 + * @tc.name : testGetRawDescriptor001 + * @tc.desc : Positive test: Get the original USB descriptor + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetRawDescriptor001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetRawDescriptor001 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetRawDescriptor001'); + let descriptor = usbManager.getRawDescriptor(gPipe); + hilog.info(domain, tag, 'usb case testGetRawDescriptor001 ret: ' + JSON.stringify(descriptor)); + expect(descriptor.length).assertLarger(0); + toClosePipe('testGetRawDescriptor001'); + }) + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0700 + * @tc.name : testGetPortSupportModesNormalApp001 + * @tc.desc : getPortSupportModes Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetPortSupportModesNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let portId: number = 1; + try { + let portMode = usbManager.getPortSupportModes(portId); + hilog.info(domain, tag, 'Test USB getPortSupportModes maskCode: ' + JSON.stringify(portMode)); + expect(portMode === null).assertTrue(); + } catch (error) { + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ' + 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() + } + }); + + /** + * @tc.number : SUB_USB_HostManager_JS_Func_0600 + * @tc.name : testGetFileDescriptor001 + * @tc.desc : Positive test: Get file descriptor + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + // 基于setenforce 0 + /*it('testGetFileDescriptor001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor001 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor001'); + let fileDescriptor = usbManager.getFileDescriptor(gPipe); + hilog.info(domain, tag, 'usb case testGetFileDescriptor001 ret: ' + fileDescriptor); + expect(fileDescriptor >= 0).assertTrue(); + toClosePipe('testGetFileDescriptor001'); + }) + + /** + * @tc.number : SUB_USB_HostManager_JS_Compatibility_2900 + * @tc.name : testGetFileDescriptor002 + * @tc.desc : Negative test: Get file descriptor, error busNum=255 devAddress=255 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor002 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor002'); + gPipe.busNum = 255; + gPipe.devAddress = 255; + hilog.info(domain, tag, 'usb case testGetFileDescriptor002 param: ' + JSON.stringify(gPipe)); + let fileDescriptor = usbManager.getFileDescriptor(gPipe); + hilog.info(domain, tag, 'usb case testGetFileDescriptor001 ret: ' + fileDescriptor); + expect(fileDescriptor).assertEqual(-1); + toClosePipe('testGetFileDescriptor002'); + }) + + /** + * @tc.number : SUB_USB_HostManager_JS_Compatibility_3000 + * @tc.name : testGetFileDescriptor003 + * @tc.desc : Negative test: Get file descriptor,error busNum=255 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor003 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor003'); + + const tempPipe: usbManager.USBDevicePipe = { + busNum: 255, + devAddress: gPipe?.devAddress + }; + // let tempPipe: usbManager.USBDevicePipe = { + // busNum: 255, devAddress: gPipe?.devAddress + // }; + hilog.info(domain, tag, 'usb case testGetFileDescriptor002 param: ' + JSON.stringify(tempPipe)); + let fileDescriptor = usbManager.getFileDescriptor(tempPipe); + hilog.info(domain, tag, 'usb case testGetFileDescriptor001 ret: ' + fileDescriptor); + expect(fileDescriptor).assertEqual(-1); + toClosePipe('testGetFileDescriptor003'); + })*/ + + /** + * @tc.number : SUB_USB_HostManager_JS_Compatibility_3100 + * @tc.name : testGetFileDescriptor004 + * @tc.desc : Negative test: Get file descriptor,error devAddress=255 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor004 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor004'); + let tempPipe: usbManager.USBDevicePipe = { + busNum: gPipe?.busNum, devAddress: 255 + }; + hilog.info(domain, tag, 'usb case testGetFileDescriptor004 param: ' + JSON.stringify(tempPipe)); + let fileDescriptor = usbManager.getFileDescriptor(tempPipe); + expect(fileDescriptor).assertEqual(-1); + hilog.info(domain, tag, 'usb case testGetFileDescriptor004 ret: ' + fileDescriptor); + toClosePipe('testGetFileDescriptor004'); + })*/ + + /** + * @tc.number : SUB_USB_HostManager_JS_ErrCode_0700 + * @tc.name : testGetFileDescriptor005 + * @tc.desc : Negative test: Get file descriptor, parameter type error "invalid" + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor005', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor005 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + try { + let maskCode = usbManager.getFileDescriptor(undefined); + hilog.info(domain, tag, 'usb testGetFileDescriptor005 case getFileDescriptor return: ' + maskCode); + expect(maskCode !== null).assertFalse(); + } catch (err) { + hilog.info(domain, tag, 'usb case testGetFileDescriptor005 catch err code: ' + err); + } + })*/ + + /** + * @tc.number : SUB_USB_HostManager_JS_ErrCode_1600 + * @tc.name : testGetFileDescriptor006 + * @tc.desc : Negative test: Get file descriptor, parameter number exception, necessary parameters not input + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + + // TypeError: No matching call signature for getFileDescriptor(null) + /*it('testGetFileDescriptor006', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor006 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + try { + let maskCode = usbManager.getFileDescriptor(null); + hilog.info(domain, tag, 'usb testGetFileDescriptor006 case getFileDescriptor return: ' + maskCode); + expect(maskCode !== null).assertFalse(); + } catch (err) { + hilog.info(domain, tag, 'usb case testGetFileDescriptor006 catch err code: ' + err); + } + })*/ + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0800 + * @tc.name : testSetPortRoleTypesNormalApp001 + * @tc.desc : setPortRoleTypes Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testSetPortRoleTypesNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let portId: number = 1; + let powerRoleTy: number = 2; + let dataRoleTy: number = 2; + try { + let data = + await usbManager.setPortRoleTypes(portId, usbManager.PowerRoleType.SOURCE, usbManager.DataRoleType.HOST); + hilog.info(domain, tag, 'Test USB setPortRoleTypes nMaskCode: ' + data); + expect(data === null).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'usb testSetPortRoleTypesNormalApp001 catch err code: ' + err); + done() + } + }); + + + it("testUsbSubmitTransfer001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'interrupt testUsbSubmitTransfer001 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]; + let gPipe: usbManager.USBDevicePipe = usbManager.connectDevice(devices); + let tmpInterface: usbManager.USBInterface = devices.configs[0].interfaces[0]; + let type: number = usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT; + let transferParams: usbManager.UsbDataTransferParams = { + devPipe: gPipe, + flags: usbManager.UsbTransferFlags.USB_TRANSFER_FREE_BUFFER, + endpoint: -1, + type: usbManager.UsbEndpointTransferType.TRANSFER_TYPE_INTERRUPT, + timeout: 2000, + length: 10, + callback: () => { + }, + userData: new Uint8Array(10), + buffer: new Uint8Array(10), + isoPacketCount: 0, + }; + usbManager.claimInterface(gPipe, tmpInterface, true); + try { + usbManager.usbSubmitTransfer(transferParams); + expect().assertFail(); + } catch (error) { + hilog.info(domain, tag, 'interrupt testUsbSubmitTransfer001 end'); + hilog.info(domain, tag, 'interrupt error:', error); + let err: BusinessError = error as BusinessError; + // expect(err.code==14400012).assertEqual(true); + usbManager.closePipe(gPipe); + done() + } + })*/ + }) +} \ No newline at end of file diff --git a/frameworks/ets/taihe/usb_manager/test/xts/USBmanger1.test.ets b/frameworks/ets/taihe/usb_manager/test/xts/USBmanger1.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..c2c28d17addfba3ec92f5997e9c84aa25d7a9350 --- /dev/null +++ b/frameworks/ets/taihe/usb_manager/test/xts/USBmanger1.test.ets @@ -0,0 +1,496 @@ +import { describe, it, expect, TestType, Size, Level, beforeAll } from "../../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 abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import Want from '@ohos.app.ability.Want'; +import Utils from './Util.test'; +import usbManager from '@ohos.usbManager'; +import { bundleManager } from '@kit.AbilityKit'; +import { BusinessError } from '@ohos.base'; + +// import { fileIo as fs } from '@kit.CoreFileKit'; + +let gDeviceList: Array>; +let devices: usbManager.USBDevice; +let gPipe: usbManager.USBDevicePipe; +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 type: usbManager.UsbEndpointTransferType; +// let transferParams: usbManager.UsbDataTransferParams; + + +let domain: number = 0x0000; //日志标识,0x0000作为测试框架的业务标识 +let tag: string = 'testTag'; //日志标识字符串,作为tag标识当前runner类下的测试行为 +//let testAbilityContext:common.UIAbilityContext; + +const PARAM_NULLSTRING: string = ""; + +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 abilityTest1() { + + 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`); + } + tmpPipe.busNum = gDeviceList[0].busNum; + tmpPipe.devAddress = gDeviceList[0].devAddress; + } + }) + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0600 + * @tc.name : testGetPortListNormalApp001 + * @tc.desc : getPortList Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + + it('testGetPortListNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + try { + hilog.info(domain, tag, 'USB testGetPortListNormalApp001 test'); + let portList = usbManager.getPortList(); + hilog.info(domain, tag, 'testGetPortListNormalApp001 success %{public}s', + JSON.stringify(portList)); + expect(portList === null).assertTrue(); + } catch (error) { + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ' + 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); // 验证202 + done() + } + }); + + /** + * @tc.number : SUB_USB_HostManager_JS_Func_0700 + * @tc.name : testGetRawDescriptor001 + * @tc.desc : Positive test: Get the original USB descriptor + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetRawDescriptor001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetRawDescriptor001 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetRawDescriptor001'); + let descriptor = usbManager.getRawDescriptor(gPipe); + hilog.info(domain, tag, 'usb case testGetRawDescriptor001 ret: ' + JSON.stringify(descriptor)); + expect(descriptor.length).assertLarger(0); + toClosePipe('testGetRawDescriptor001'); + }) + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0700 + * @tc.name : testGetPortSupportModesNormalApp001 + * @tc.desc : getPortSupportModes Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetPortSupportModesNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let portId: number = 1; + try { + let portMode = usbManager.getPortSupportModes(portId); + hilog.info(domain, tag, 'Test USB getPortSupportModes maskCode: ' + JSON.stringify(portMode)); + expect(portMode === null).assertTrue(); + } catch (error) { + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ' + 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() + } + }); + + /** + * @tc.number : SUB_USB_HostManager_JS_Func_0600 + * @tc.name : testGetFileDescriptor001 + * @tc.desc : Positive test: Get file descriptor + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + // 基于setenforce 0 + it('testGetFileDescriptor001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor001 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor001'); + let fileDescriptor = usbManager.getFileDescriptor(gPipe); + hilog.info(domain, tag, 'usb case testGetFileDescriptor001 ret: ' + fileDescriptor); + expect(fileDescriptor >= 0).assertTrue(); + toClosePipe('testGetFileDescriptor001'); + }) + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0200 + * @tc.name : testGetFunctionsFromStringNormalApp001 + * @tc.desc : getFunctionsFromString Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetFunctionsFromStringNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let strMaskCode = 'hdc'; + try { + let nMaskCode = usbManager.getFunctionsFromString(strMaskCode); + hilog.info(domain, tag, 'Test USB getFunctionsFromString nMaskCode: ' + nMaskCode); + expect(nMaskCode === null).assertTrue(); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testGetFunctionsFromStringNormalApp001 catch err code: ', + err.code, ', message: ', err.message); + expect(err.code).assertEqual(202); + } + done() + }); + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0400 + * @tc.name : testSetDeviceFunctionsNormalApp001 + * @tc.desc : setDeviceFunctions Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testSetDeviceFunctionsNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let funcs: number = 4; + try { + let ret = usbManager.setDeviceFunctions(usbManager.FunctionType.ACM); + if (ret) { + hilog.info(domain, tag, 'setDeviceFunctions success:' + JSON.stringify(ret)); + } else { + hilog.info(domain, tag, 'setDeviceFunctions failed:' + ret); + } + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testSetDeviceFunctionsNormalApp001 catch err code: ', + err.code, ', message: ', err.message); + expect(err.code).assertEqual(202); + } + done() + }); + + it("testGetDeviceFunctionsNormalApp001", TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL1, + async (done: () => void): Promise => { + hilog.info(domain, tag, 'USB testGetDeviceFunctionsNormalApp001 begin'); + if (!isDeviceConnected) { + hilog.info(domain, tag, 'usb not connected'); + } + try { + let ret = usbManager.getDeviceFunctions(); + expect(ret === null).assertTrue(); + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testGetDeviceFunctionsNormalApp001 catch err code: ', + err.code, ', message: ', err.message); + expect(err.code).assertEqual(202); + } + done(); + }) + + it('testGetPortListNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + try { + let portList = usbManager.getPortList(); + hilog.info(domain, tag, 'testGetPortListNormalApp001 success %{public}s', + JSON.stringify(portList)); + expect(portList === null).assertTrue(); + } catch (error) { + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ' + 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() + } + }); + + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0700 + * @tc.name : testGetPortSupportModesNormalApp001 + * @tc.desc : getPortSupportModes Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + it('testGetPortSupportModesNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let portId: number = 1; + try { + let portMode = usbManager.getPortSupportModes(portId); + hilog.info(domain, tag, 'Test USB getPortSupportModes maskCode: ' + JSON.stringify(portMode)); + expect(portMode === null).assertTrue(); + } catch (error) { + hilog.info(domain, tag, 'usb testGetPortListNormalApp001 catch err code: ' + 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('testUsbAddDeviceAccessRightNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + try { + let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION; + await bundleManager.getBundleInfoForSelf(bundleFlags).then((bundleInfo) => { + let tokenId = bundleInfo.appInfo.accessTokenId; + // let tokenIdStr = tokenId.toString(); + let tokenIdStr = String(tokenId); + hilog.info(domain, tag, 'testUsbAddDeviceAccessRightNormalApp001 addDeviceAccessRight begin'); + let deviceList = usbManager.getDevices(); + let rightResult = usbManager.addDeviceAccessRight(tokenIdStr, deviceList[0].name); + hilog.info(domain, tag, 'addDeviceAccessRight failed result: ' + rightResult); + expect(rightResult === null).assertTrue(); + }) + } catch (error) { + const err = error as BusinessError; + hilog.info(domain, tag, 'usb testUsbAddDeviceAccessRightNormalApp001 catch err code: ', + err.code, ', message: ', err.message); + expect(err.code).assertEqual(202); + } + done() + });*/ + + + // 参数255 ,有问题 + /** + * @tc.number : SUB_USB_HostManager_JS_Compatibility_2900 + * @tc.name : testGetFileDescriptor002 + * @tc.desc : Negative test: Get file descriptor, error busNum=255 devAddress=255 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor002', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor002 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor002'); + gPipe.busNum = 255; + gPipe.devAddress = 255; + hilog.info(domain, tag, 'usb case testGetFileDescriptor002 param: ' + JSON.stringify(gPipe)); + let fileDescriptor = usbManager.getFileDescriptor(gPipe); + hilog.info(domain, tag, 'usb case testGetFileDescriptor001 ret: ' + fileDescriptor); + expect(fileDescriptor).assertEqual(-1); + toClosePipe('testGetFileDescriptor002'); + })*/ + + + // 一样参数有问题 255 + /** + * @tc.number : SUB_USB_HostManager_JS_Compatibility_3000 + * @tc.name : testGetFileDescriptor003 + * @tc.desc : Negative test: Get file descriptor,error busNum=255 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor003', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor003 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor003'); + + const tempPipe: usbManager.USBDevicePipe = { + busNum: 255, + devAddress: gPipe?.devAddress + }; + // let tempPipe: usbManager.USBDevicePipe = { + // busNum: 255, devAddress: gPipe?.devAddress + // }; + hilog.info(domain, tag, 'usb case testGetFileDescriptor002 param: ' + JSON.stringify(tempPipe)); + let fileDescriptor = usbManager.getFileDescriptor(tempPipe); + hilog.info(domain, tag, 'usb case testGetFileDescriptor001 ret: ' + fileDescriptor); + expect(fileDescriptor).assertEqual(-1); + toClosePipe('testGetFileDescriptor003'); + })*/ + + // 一样参数有问题 255 + /** + * @tc.number : SUB_USB_HostManager_JS_Compatibility_3100 + * @tc.name : testGetFileDescriptor004 + * @tc.desc : Negative test: Get file descriptor,error devAddress=255 + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor004', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor004 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + getPipe('testGetFileDescriptor004'); + let tempPipe: usbManager.USBDevicePipe = { + busNum: gPipe?.busNum, devAddress: 255 + }; + hilog.info(domain, tag, 'usb case testGetFileDescriptor004 param: ' + JSON.stringify(tempPipe)); + let fileDescriptor = usbManager.getFileDescriptor(tempPipe); + expect(fileDescriptor).assertEqual(-1); + hilog.info(domain, tag, 'usb case testGetFileDescriptor004 ret: ' + fileDescriptor); + toClosePipe('testGetFileDescriptor004'); + })*/ + + //未定义的参数 + /** + * @tc.number : SUB_USB_HostManager_JS_ErrCode_0700 + * @tc.name : testGetFileDescriptor005 + * @tc.desc : Negative test: Get file descriptor, parameter type error "invalid" + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testGetFileDescriptor005', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor005 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + try { + let maskCode = usbManager.getFileDescriptor(undefined); + hilog.info(domain, tag, 'usb testGetFileDescriptor005 case getFileDescriptor return: ' + maskCode); + expect(maskCode !== null).assertFalse(); + } catch (err) { + hilog.info(domain, tag, 'usb case testGetFileDescriptor005 catch err code: ' + err); + } + })*/ + + + // 为null的参数 + /** + * @tc.number : SUB_USB_HostManager_JS_ErrCode_1600 + * @tc.name : testGetFileDescriptor006 + * @tc.desc : Negative test: Get file descriptor, parameter number exception, necessary parameters not input + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + + // TypeError: No matching call signature for getFileDescriptor(null) + /*it('testGetFileDescriptor006', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, () => { + hilog.info(domain, tag, 'usb testGetFileDescriptor006 begin'); + if (!isDeviceConnected) { + expect(isDeviceConnected).assertFalse(); + return + } + + try { + let maskCode = usbManager.getFileDescriptor(null); + hilog.info(domain, tag, 'usb testGetFileDescriptor006 case getFileDescriptor return: ' + maskCode); + expect(maskCode !== null).assertFalse(); + } catch (err) { + hilog.info(domain, tag, 'usb case testGetFileDescriptor006 catch err code: ' + err); + } + })*/ + + + // 需要到黄区测试 + /** + * @tc.number : SUB_USB_Spec_Sec_SysApiAuthen_0800 + * @tc.name : testSetPortRoleTypesNormalApp001 + * @tc.desc : setPortRoleTypes Interface testing + * @tc.size : MediumTest + * @tc.type : Function + * @tc.level : Level 3 + */ + /*it('testSetPortRoleTypesNormalApp001', TestType.FUNCTION | Size.MEDIUMTEST | Level.LEVEL3, + async (done: () => void): Promise => { + let portId: number = 1; + let powerRoleTy: number = 2; + let dataRoleTy: number = 2; + try { + let data = + await usbManager.setPortRoleTypes(portId, usbManager.PowerRoleType.SOURCE, usbManager.DataRoleType.HOST); + hilog.info(domain, tag, 'Test USB setPortRoleTypes nMaskCode: ' + data); + expect(data === null).assertTrue(); + } catch (err) { + hilog.info(domain, tag, 'usb testSetPortRoleTypesNormalApp001 catch err code: ' + err); + done() + } + });*/ + + }) +} \ No newline at end of file diff --git a/utils/native/include/hilog_wrapper.h b/utils/native/include/hilog_wrapper.h index f79c8185391a18f95f6ebd330afb012c0e50fbd3..3a49868a8ddf031000b827ca4cc97f58f931d65f 100644 --- a/utils/native/include/hilog_wrapper.h +++ b/utils/native/include/hilog_wrapper.h @@ -59,6 +59,7 @@ enum UsbMgrSubModule { MODULE_JS_NAPI, MODULE_JAVAKIT, // java kit used, define to avoid repeat used domain MODULE_JNI, + MODULE_JS_ANI, USBMGR_MODULE_BUTT, }; @@ -74,6 +75,7 @@ enum UsbMgrDomainId { COMMON_DOMAIN, //0xD002A06 USB_JS_NAPI, //0xD002A07 USBMGR_JAVAKIT_DOMAIN, + USB_JS_ANI, USB_BUTT, }; @@ -87,6 +89,7 @@ static const UsbLable USB_MGR_LABEL[USBMGR_MODULE_BUTT] = { {USB_JS_NAPI, "UsbMgrJSNAPI"}, {USBMGR_JAVAKIT_DOMAIN, "UsbMgrJavaService"}, {USBMGR_INNERKIT_DOMAIN, "UsbMgrJni"}, + {USB_JS_ANI, "UsbMgrJSANI"}, }; // In order to improve performance, do not check the module range, module should less than USBMGR_MODULE_BUTT.