目录

UI-based Driver Development

When to Use

UI-based basic drivers are applicable to a wide variety of composite devices. When developing these drivers, you may set the corresponding unique driver capabilities through the UI, or display the information retrieved from the devices on the UI. Examples of such devices include mice with side buttons, handwriting tablets, and ID card readers.

Environment Setup

Before you get started, make necessary preparations by following instructions in Environment Preparation.

Available APIs

The following table describes the basic peripheral management capabilities. For more details, see @ohos.driver.deviceManager (Peripheral Management).

Table 1 APIs for basic peripheral management

Name Description
queryDevices(busType?: number): Array<Readonly<Device>> Queries the extended peripheral list.
bindDriverWithDeviceId(deviceId: number, onDisconnect: AsyncCallback<number>): Promise<RemoteDeviceDriver> Binds a device in Promise form. Supported since API version 19.
unbindDriverWithDeviceId(deviceId: number): Promise<number> Unbinds a device in Promise form. Supported since API version 19.

How to Develop

You can use the APIs to query and bind peripheral devices so as to use the customized driver capabilities of the peripherals.

The following sample code is a demo that illustrates how to develop both the client and server and implement IPC.

  1. Create a project following instructions in Creating a Project.

    • To develop a driver client, select the Empty Ability template.
    • To develop the driver server, select the Native C++ template.
    • To develop both the driver client and server, select the Native C++ template.
  2. Import the related kit, and declare the product ID, vendor ID, and code of the USB device to be bound.

    All the following sample code is written in the entry/src/main/ets/pages/Index.ets file.

    import { hilog } from '@kit.PerformanceAnalysisKit';
    import { deviceManager } from '@kit.DriverDevelopmentKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    import { rpc } from '@kit.IPCKit';
    
    const REQUEST_CODE: number = 99; // Custom communication code, which is for reference only.
    const productId: number = 4258; // Declare the product ID of the connected USB device.
    const vendorId: number = 4817; // Declare the vendor ID of the connected USB device.
    const DOMAIN = 0x0000;
  3. Define the message variable and remote object variable for communication with the driver.

    The following APIs are defined in struct Index{}.

    @State message: string = 'Hello';
    private remote: rpc.IRemoteObject | null = null;
  4. Define the queryDevices API, and use it to obtain the device ID of the peripheral.

    private async queryTargetDeviceId(): Promise<number> {
      try {
        const devices: deviceManager.Device[] = deviceManager.queryDevices(deviceManager.BusType.USB);
        const index = devices.findIndex((item: deviceManager.Device) => {
          let usbDevice = item as deviceManager.USBDevice;
          // If the product ID and vendor ID of the peripheral are unknown, you can view the information about the connected USB device in the log.
          hilog.info(DOMAIN, 'testTag', `usbDevice.productId = ${usbDevice.productId}, usbDevice.vendorId = ${usbDevice.vendorId}`);
          return usbDevice.productId === productId && usbDevice.vendorId === vendorId;
        });
        if (index < 0) {
          hilog.error(DOMAIN, 'testTag', 'can not find device');
          return -1;
        }
        hilog.info(DOMAIN, 'testTag', `queryTargetDeviceId index = ${index}, deviceId = ${devices[index].deviceId}`);
        return devices[index].deviceId;
      } catch (error) {
        hilog.error(DOMAIN, 'testTag', `queryDevice failed, err: ${JSON.stringify(error)}`);
      }
      return -1;
    }
  5. Define the interface for obtaining the corresponding driver remote object, and obtain the remote object through bindDriverWithDeviceId.

    private async getDriverRemote(deviceId: number): Promise<rpc.IRemoteObject | null> {
      try {
        let remoteDeviceDriver: deviceManager.RemoteDeviceDriver = await deviceManager.bindDriverWithDeviceId(deviceId,
          (err: BusinessError, id: number) => {
            hilog.error(DOMAIN, 'testTag', `device[${id}] id disconnect, err: ${JSON.stringify(err)}`);
          });
        return remoteDeviceDriver.remote;
      } catch (error) {
        hilog.error(DOMAIN, 'testTag', `bindDriverWithDeviceId failed, err: ${JSON.stringify(error)}`);
      }
      return null;
    }
  6. Define the sendMessageRequest API, and use it to perform IPC with the remote object.

    private async communicateWithRemote(): Promise<void> {
      const deviceId: number = await this.queryTargetDeviceId();
      hilog.info(DOMAIN, 'testTag', `queryTargetDeviceId, deviceId=${deviceId}`);
      if (deviceId < 0) {
        hilog.error(DOMAIN, 'testTag', 'can not find target device');
        return;
      }
      this.remote = await this.getDriverRemote(deviceId);
      if (this.remote === null) {
        hilog.error(DOMAIN, 'testTag', `getDriverRemote failed`);
        return;
      }
    
      let option = new rpc.MessageOption();
      let data = new rpc.MessageSequence();
      let reply = new rpc.MessageSequence();
    
      // Send "Hello" to the driver.
      hilog.info(DOMAIN, 'testTag', `communicateWithRemote, message=${this.message}`);
      data.writeString(this.message);
    
      try {
        await this.remote.sendMessageRequest(REQUEST_CODE, data, reply, option);
        // Obtain the "Hello world" information returned by the driver.
        this.message = reply.readString();
        hilog.info(DOMAIN, 'testTag', `sendMessageRequest, message: ${this.message}`);
      } catch (error) {
        hilog.error(DOMAIN, 'testTag', `sendMessageRequest failed, err: ${JSON.stringify(error)}`);
      }
    }
  7. Render the UI. For details about UI development, see UI Development.

    build() {
      Row() {
        Column() {
          Text(this.message)
            .fontSize($r('app.float.page_text_font_size'))
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              // Click "Hello" to communicate with the remote object. The message "Hello World" is displayed.
              this.communicateWithRemote();
            })
        }
        .width('100%')
      }
      .height('100%')
    }
  8. Develop peripheral drivers by following instructions in UI-free Driver Development.

Application Signing

Configure the permission before enabling automatic signing.

You need to configure a signature file for your application to run on a device. Besides, to develop a peripheral driver client, you need to declare the ohos.permission.ACCESS_EXTENSIONAL_DEVICE_DRIVER and ohos.permission.ACCESS_DDK_DRIVERS permissions for the peripheral.

After the permission is configured, you can sign the app by referring to Signing Your App/Service Automatically.