目录

How Do I Implement the Retry Mechanism for Barcode Scanning by Custom UI?

Problem

After init is successfully called and start is called to start camera streams, the internal error 1000500001 is reported.

Solution

You can implement the retry mechanism for starting camera streams.

In the mechanism, you will stop and then release camera streams by calling stop and release respectively, and then restart camera streams by calling init and start.

Sample code (for reference only):

import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { customScan, scanBarcode, scanCore } from '@kit.ScanKit';

const MAX_RETRY_SCAN_TIMES: number = 3; // Maximum number of barcode scanning retries. Change the value to suit application needs.
const DELAY_RETRY_SCAN_TIME: number = 100; // Retry delay. Change the value to suit application needs.

export class ScanService {
  private retryScanTimes: number = 0; // Number of retry times.

  // Callback for the customScan.start API; invoke this function to determine whether to retry based on the error information.
  private retryOnCondition(error: BusinessError, options: scanBarcode.ScanOptions,
    viewControl: customScan.ViewControl): boolean {
    if (error) {
      hilog.error(0x0001, '[Scan Sample]',
        `An error is returned during customScanCallback. Code: ${error.code}, message: ${error.message}`);
      // Restart the camera stream if an internal error 1000500001 occurs and the number of retries has not exceeded the maximum retry count.
      if (this.retryScanTimes < MAX_RETRY_SCAN_TIMES && error.code === scanCore.ScanErrorCode.INTERNAL_ERROR) {
        this.retryScanTimes++;
        let timeId = setTimeout(async () => {
          hilog.info(0x0001, '[Scan Sample]',
            `Retry preview stream by customScanCallback. Times: ${this.retryScanTimes}.`);
          await this.stopPreviewStream();
          this.startPreviewStream(options, viewControl);
          hilog.info(0x0001, '[Scan Sample]', 'Retry preview stream end.');
          clearTimeout(timeId);
        }, DELAY_RETRY_SCAN_TIME);
        return true; // Retry.
      }
    }
    return false; // No retry.
  }

  // Stop and release camera preview streams.
  public async stopPreviewStream(): Promise<void> {
    hilog.info(0x0001, '[Scan Sample]', 'Stop Preview Stream start.');
    await this.stopCustomScan();
    this.resetRetryScanTimes();
    await this.releaseCustomScan();
    hilog.info(0x0001, '[Scan Sample]', 'Stop Preview Stream end.');
  }

  // Initialize and start barcode scanning by custom UI.
  public startPreviewStream(options: scanBarcode.ScanOptions, viewControl: customScan.ViewControl) {
    hilog.info(0x0001, '[Scan Sample]', 'Start Preview Stream.');
    this.initCustomScan(options);
    this.startCustomScan(options, viewControl);
    hilog.info(0x0001, '[Scan Sample]', 'Start Preview Stream end.');
  }

  // Initialize barcode scanning by custom UI.
  private initCustomScan(options: scanBarcode.ScanOptions) {
    try {
      hilog.info(0x0001, '[Scan Sample]', 'Init customScan start.');
      customScan.init(options);
      hilog.info(0x0001, '[Scan Sample]', 'Init customScan end.');
    } catch (error) {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to init customScan. Code: ${error.code}, message: ${error.message}.`);
    }
  }

  // Start barcode scanning by custom UI.
  private startCustomScan(options: scanBarcode.ScanOptions, viewControl: customScan.ViewControl): void {
    try {
      hilog.info(0x0001, '[Scan Sample]',
        `Start customScan start. width: ${viewControl.width}, height: ${viewControl.height}`);
      customScan.start(viewControl, (err: BusinessError, data: Array<scanBarcode.ScanResult>) => {
        if (this.retryOnCondition(err, options, viewControl)) {
          return;
        }
        hilog.info(0x0001, '[Scan Sample]',
          `Succeeded in getting ScanResult by callback, result length: ${data.length}`);
        // Obtain the scanning result from data and process the service.
        // ...
      });
      hilog.info(0x0001, '[Scan Sample]', 'Start customScan end.');
    } catch (error) {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to start customScan. Code: ${error.code}, message: ${error.message}.`);
    }
  }

  // Stop camera streams.
  private async stopCustomScan(): Promise<void> {
    try {
      hilog.info(0x0001, '[Scan Sample]', 'Stop customScan start.');
      await customScan.stop();
      hilog.info(0x0001, '[Scan Sample]', 'Stop customScan end.');
    } catch (error) {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to stop customScan. Code: ${error.code}, message: ${error.message}.`);
    }
  }

  // Release the camera preview stream.
  private async releaseCustomScan(): Promise<void> {
    try {
      hilog.info(0x0001, '[Scan Sample]', 'Release customScan start.');
      await customScan.release();
      hilog.info(0x0001, '[Scan Sample]', 'Release customScan end.');
    } catch (error) {
      hilog.error(0x0001, '[Scan Sample]',
        `Failed to release customScan. Code: ${error.code}, message: ${error.message}.`);
    }
  }

  // Reset the number of retry times.
  resetRetryScanTimes(): void {
    hilog.info(0x0001, '[Scan Sample]', 'Reset retry scan times.');
    this.retryScanTimes = 0;
  }
}