harmony 鸿蒙@ohos.usb (USB)

2022-12-13 浏览 (676)

@ohos.usb (USB)

The usb module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control.

NOTE

The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.

The APIs provided by this module are no longer maintained since API version 9. You are advised to use @ohos.usbManager.

Modules to Import

import usb from "@ohos.usb";

usb.getDevices

getDevices(): Array<Readonly<USBDevice>>

Obtains the USB device list.

System capability: SystemCapability.USB.USBManager

Return value

TypeDescription
Array<Readonly<USBDevice>>USB device list.

Example

let devicesList = usb.getDevices();
console.log(`devicesList = ${devicesList}`);
// devicesList is a list of USB devices.
// A simple example of devicesList is provided as follows:
[
  {
    name: "1-1",
    serial: "",
    manufacturerName: "",
    productName: "",
    version: "",
    vendorId: 7531,
    productId: 2,
    clazz: 9,
    subClass: 0,
    protocol: 1,
    devAddress: 1,
    busNum: 1,
    configs: [
      {
        id: 1,
        attributes: 224,
        isRemoteWakeup: true,
        isSelfPowered: true,
        maxPower: 0,
        name: "1-1",
        interfaces: [
          {
            id: 0,
            protocol: 0,
            clazz: 9,
            subClass: 0,
            alternateSetting: 0,
            name: "1-1",
            endpoints: [
              {
                address: 129,
                attributes: 3,
                interval: 12,
                maxPacketSize: 4,
                direction: 128,
                number: 1,
                type: 3,
                interfaceId: 0,
              },
            ],
          },
        ],
      },
    ],
  },
]

usb.connectDevice

connectDevice(device: USBDevice): Readonly<USBDevicePipe>

Connects to a USB device.

Before you do this, call usb.getDevices to obtain the USB device list, and then call usb.requestRight to request the device access permission.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
deviceUSBDeviceYesUSB device information.

Return value

TypeDescription
Readonly<USBDevicePipe>USB device pipe for data transfer.

Example

let devicepipe= usb.connectDevice(device);
console.log(`devicepipe = ${devicepipe}`);

usb.hasRight

hasRight(deviceName: string): boolean

Checks whether the application has the permission to access the device.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
deviceNamestringYesDevice name.

Return value

TypeDescription
booleanReturns true if the application has the permission to access the device; returns false otherwise.

Example

let devicesName= "1-1";
let bool = usb.hasRight(devicesName);
console.log(bool);

usb.requestRight

requestRight(deviceName: string): Promise<boolean>

Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. System applications are granted the device access permission by default, and you do not need to apply for the permission separately.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
deviceNamestringYesDevice name.

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true indicates that the temporary device access permissions are granted; and the value false indicates the opposite.

Example

let devicesName= "1-1";
usb.requestRight(devicesName).then((ret) => {
  console.log(`requestRight = ${ret}`);
});

usb.claimInterface

claimInterface(pipe: USBDevicePipe, iface: USBInterface, force ?: boolean): number

Claims a USB interface.

Before you do this, call usb.getDevices to obtain the USB device list and USB interfaces, call usb.requestRight to request the device access permission, and call usb.connectDevice to obtain devicepipe as an input parameter.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesDevice pipe, which is used to determine the bus number and device address.
ifaceUSBInterfaceYesUSB interface, which is used to determine the index of the interface to claim.
forcebooleanNoWhether to forcibly claim the USB interface. The default value is false, indicating not to forcibly claim the USB interface.

Return value

TypeDescription
numberReturns 0 if the USB interface is successfully claimed; returns an error code otherwise.

Example

let ret = usb.claimInterface(devicepipe, interfaces);
console.log(`claimInterface = ${ret}`);

usb.releaseInterface

releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number

Releases a USB interface.

Before you do this, ensure that you have claimed the interface by calling usb.claimInterface.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesDevice pipe, which is used to determine the bus number and device address.
ifaceUSBInterfaceYesUSB interface, which is used to determine the index of the interface to release.

Return value

TypeDescription
numberReturns 0 if the USB interface is successfully released; returns an error code otherwise.

Example

let ret = usb.releaseInterface(devicepipe, interfaces);
console.log(`releaseInterface = ${ret}`);

usb.setConfiguration

setConfiguration(pipe: USBDevicePipe, config: USBConfig): number

Sets the device configuration.

Before you do this, call usb.getDevices to obtain the USB device list and device configuration, call usb.requestRight to request the device access permission, and call usb.connectDevice to obtain devicepipe as an input parameter.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesDevice pipe, which is used to determine the bus number and device address.
configUSBConfigYesUSB configuration to set.

Return value

TypeDescription
numberReturns 0 if the USB configuration is successfully set; returns an error code otherwise.

Example

let ret = usb.setConfiguration(devicepipe, config);
console.log(`setConfiguration = ${ret}`);

usb.setInterface

setInterface(pipe: USBDevicePipe, iface: USBInterface): number

Sets a USB interface.

Before you do this, call usb.getDevices to obtain the USB device list and interfaces, call usb.requestRight to request the device access permission, call usb.connectDevice to obtain devicepipe as an input parameter, and call usb.claimInterface to claim the USB interface.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesDevice pipe, which is used to determine the bus number and device address.
ifaceUSBInterfaceYesUSB interface to set.

Return value

TypeDescription
numberReturns 0 if the USB interface is successfully set; returns an error code otherwise.

Example

let ret = usb.setInterface(devicepipe, interfaces);
console.log(`setInterface = ${ret}`);

usb.getRawDescriptor

getRawDescriptor(pipe: USBDevicePipe): Uint8Array

Obtains the raw USB descriptor.

Before you do this, call usb.getDevices to obtain the USB device list, call usb.requestRight to request the device access permission, and call usb.connectDevice to obtain devicepipe as an input parameter.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesDevice pipe, which is used to determine the bus number and device address.

Return value

TypeDescription
Uint8ArrayReturns the raw USB descriptor if the operation is successful; returns undefined otherwise.

Example

let ret = usb.getRawDescriptor(devicepipe);

usb.getFileDescriptor

getFileDescriptor(pipe: USBDevicePipe): number

Obtains the file descriptor.

Before you do this, call usb.getDevices to obtain the USB device list, call usb.requestRight to request the device access permission, and call usb.connectDevice to obtain devicepipe as an input parameter.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesDevice pipe, which is used to determine the bus number and device address.

Return value

TypeDescription
numberReturns the file descriptor of the USB device if the operation is successful; returns -1 otherwise.

Example

let ret = usb.getFileDescriptor(devicepipe);

usb.controlTransfer

controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout ?: number): Promise<number>

Performs control transfer.

Before you do this, call usb.getDevices to obtain the USB device list, call usb.requestRight to request the device access permission, and call usb.connectDevice to obtain devicepipe as an input parameter.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesUSB device pipe, which is used to determine the USB device.
controlparamUSBControlParamsYesControl transfer parameters.
timeoutnumberNoTimeout duration in ms. This parameter is optional. The default value is 0, indicating no timeout.

Return value

TypeDescription
Promise<number>Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or -1 if an exception has occurred.

Example

let param = {
  request: 0,
  reqType: 0,
  target:0,
  value: 0,
  index: 0,
  data: null
};
usb.controlTransfer(devicepipe, param).then((ret) => {
 console.log(`controlTransfer = ${ret}`);
})

usb.bulkTransfer

bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout ?: number): Promise<number>

Performs bulk transfer.

Before you do this, call usb.getDevices to obtain the USB device list and endpoints, call usb.requestRight to request the device access permission, call usb.connectDevice to obtain devicepipe as an input parameter, and call usb.claimInterface to claim the USB interface.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesUSB device pipe, which is used to determine the USB device.
endpointUSBEndpointYesUSB endpoint, which is used to determine the USB port for data transfer.
bufferUint8ArrayYesBuffer for writing or reading data.
timeoutnumberNoTimeout duration in ms. This parameter is optional. The default value is 0, indicating no timeout.

Return value

TypeDescription
Promise<number>Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or -1 if an exception has occurred.

Example

// Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission.
// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device.
// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer.
usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => {
 console.log(`bulkTransfer = ${ret}`);
});

usb.closePipe

closePipe(pipe: USBDevicePipe): number

Closes a USB device pipe.

Before you do this, call usb.getDevices to obtain the USB device list, call usb.requestRight to request the device access permission, and call usb.connectDevice to obtain devicepipe as an input parameter.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
pipeUSBDevicePipeYesUSB device pipe.

Return value

TypeDescription
numberReturns 0 if the USB device pipe is closed successfully; returns an error code otherwise.

Example

let ret = usb.closePipe(devicepipe);
console.log(`closePipe = ${ret}`);

usb.usbFunctionsFromString9+

usbFunctionsFromString(funcs: string): number

Converts the USB function list in the string format to a numeric mask in Device mode.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
funcsstringYesFunction list in string format.

Return value

TypeDescription
numberFunction list in numeric mask format.

Example

let funcs = "acm";
let ret = usb.usbFunctionsFromString(funcs);

usb.usbFunctionsToString9+

usbFunctionsToString(funcs: FunctionType): string

Converts the USB function list in the numeric mask format to a string in Device mode.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
funcsFunctionTypeYesUSB function list in numeric mask format.

Return value

TypeDescription
stringFunction list in string format.

Example

let funcs = usb.FunctionType.ACM|usb.FunctionType.ECM;
let ret = usb.usbFunctionsToString(funcs);

usb.setCurrentFunctions9+

setCurrentFunctions(funcs: FunctionType): Promise<boolean>

Sets the current USB function list in Device mode.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
funcsFunctionTypeYesUSB function list in numeric mask format.

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

let funcs = usb.FunctionType.HDC;
usb.setCurrentFunctions(funcs).then(() => {
    console.info('usb setCurrentFunctions successfully.');
}).catch(err => {
    console.error('usb setCurrentFunctions failed: ' + err.code + ' message: ' + err.message);
});

usb.getCurrentFunctions9+

getCurrentFunctions(): FunctionType

Obtains the numeric mask combination for the USB function list in Device mode.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Return value

TypeDescription
FunctionTypeNumeric mask combination for the USB function list.

Example

let ret = usb.getCurrentFunctions();

usb.getPorts9+

getPorts(): Array<USBPort>

Obtains the list of all physical USB ports.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Return value

TypeDescription
Array<USBPort>List of physical USB ports.

Example

let ret = usb.getPorts();

usb.getSupportedModes9+

getSupportedModes(portId: number): PortModeType

Obtains the mask combination for the supported mode list of a given USB port.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
portIdnumberYesPort number.

Return value

TypeDescription
PortModeTypeMask combination for the supported mode list.

Example

let ret = usb.getSupportedModes(0);

usb.setPortRoles9+

setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise<boolean>

Sets the role types supported by a specified port, which can be powerRole (for charging) and dataRole (for data transfer).

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

Parameters

NameTypeMandatoryDescription
portIdnumberYesPort number.
powerRolePowerRoleTypeYesRole for charging.
dataRoleDataRoleTypeYesRole for data transfer.

Return value

TypeDescription
Promise<boolean>Promise used to return the result. The value true indicates that the operation is successful, and the value false indicates the opposite.

Example

let portId = 1;
usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => {
    console.info('usb setPortRoles successfully.');
}).catch(err => {
    console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message);
});

USBEndpoint

Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through USBInterface.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
addressnumberYesEndpoint address.
attributesnumberYesEndpoint attributes.
intervalnumberYesEndpoint interval.
maxPacketSizenumberYesMaximum size of data packets on the endpoint.
directionUSBRequestDirectionYesEndpoint direction.
numbernumberYesEndpoint number.
typenumberYesEndpoint type.
interfaceIdnumberYesUnique ID of the interface to which the endpoint belongs.

USBInterface

Represents a USB interface. One USBConfig can contain multiple USBInterface instances, each providing a specific function.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
idnumberYesUnique ID of the USB interface.
protocolnumberYesInterface protocol.
clazznumberYesDevice type.
subClassnumberYesDevice subclass.
alternateSettingnumberYesSettings for alternating between descriptors of the same USB interface.
namestringYesInterface name.
endpointsArray<USBEndpoint>YesEndpoints that belong to the USB interface.

USBConfig

Represents the USB configuration. One USBDevice can contain multiple USBConfig instances.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
idnumberYesUnique ID of the USB configuration.
attributesnumberYesConfiguration attributes.
maxPowernumberYesMaximum power consumption, in mA.
namestringYesConfiguration name, which can be left empty.
isRemoteWakeupbooleanYesSupport for remote wakeup.
isSelfPoweredbooleanYesSupport for independent power supplies.
interfacesArray <USBInterface>YesSupported interface attributes.

USBDevice

Represents the USB device information.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
busNumnumberYesBus address.
devAddressnumberYesDevice address.
serialstringYesSequence number.
namestringYesDevice name.
manufacturerNamestringYesDevice manufacturer.
productNamestringYesProduct name.
versionstringYesVersion.
vendorIdnumberYesVendor ID.
productIdnumberYesProduct ID.
clazznumberYesDevice class.
subClassnumberYesDevice subclass.
protocolnumberYesDevice protocol code.
configsArray<USBConfig>YesDevice configuration descriptor information.

USBDevicePipe

Represents a USB device pipe, which is used to determine a USB device.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
busNumnumberYesBus address.
devAddressnumberYesDevice address.

USBControlParams

Represents control transfer parameters.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
requestnumberYesRequest type.
targetUSBRequestTargetTypeYesRequest target type.
reqTypeUSBControlRequestTypeYesControl request type.
valuenumberYesRequest parameter value.
indexnumberYesIndex of the request parameter value.
dataUint8ArrayYesBuffer for writing or reading data.

USBPort9+

Represents a USB port.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
idnumberYesUnique identifier of a USB port.
supportedModesPortModeTypeYesNumeric mask combination for the supported mode list.
statusUSBPortStatusYesUSB port role.

USBPortStatus9+

Enumerates USB port roles.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

NameTypeMandatoryDescription
currentModenumberYesCurrent USB mode.
currentPowerRolenumberYesCurrent power role.
currentDataRolenumberYesCurrent data role.

USBRequestTargetType

Enumerates request target types.

System capability: SystemCapability.USB.USBManager

NameValueDescription
USB_REQUEST_TARGET_DEVICE0Device.
USB_REQUEST_TARGET_INTERFACE1Interface.
USB_REQUEST_TARGET_ENDPOINT2Endpoint.
USB_REQUEST_TARGET_OTHER3Other.

USBControlRequestType

Enumerates control request types.

System capability: SystemCapability.USB.USBManager

NameValueDescription
USB_REQUEST_TYPE_STANDARD0Standard.
USB_REQUEST_TYPE_CLASS1Class.
USB_REQUEST_TYPE_VENDOR2Vendor.

USBRequestDirection

Enumerates request directions.

System capability: SystemCapability.USB.USBManager

NameValueDescription
USB_REQUEST_DIR_TO_DEVICE0Request for writing data from the host to the device.
USB_REQUEST_DIR_FROM_DEVICE0x80Request for reading data from the device to the host.

FunctionType9+

Enumerates USB device function types.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

NameValueDescription
NONE0No function.
ACM1ACM function.
ECM2ECM function.
HDC4HDC function.
MTP8Not supported currently.
PTP16Not supported currently.
RNDIS32Not supported currently.
MIDI64Not supported currently.
AUDIO_SOURCE128Not supported currently.
NCM256Not supported currently.

PortModeType9+

Enumerates USB port mode types.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

NameValueDescription
NONE0None.
UFP1Upstream facing port, which functions as the sink of power supply.
DFP2Downstream facing port, which functions as the source of power supply.
DRP3Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.
NUM_MODES4Not supported currently.

PowerRoleType9+

Enumerates power role types.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

NameValueDescription
NONE0None.
SOURCE1External power supply.
SINK2Internal power supply.

DataRoleType9+

Enumerates data role types.

System API: This is a system API.

System capability: SystemCapability.USB.USBManager

NameValueDescription
NONE0None.
HOST1USB host.
DEVICE2USB device.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/9669282a93be4f16984ef93b2ddb4efa