扫设备二维码配网

更新时间:2025-12-16 06:33:03下载pdf

该功能仅适用于设备已配备配网二维码,且已连接互联网的设备。

扫设备二维码配网API使用示例

API说明参考设备配网

获取设备UUID扫描设备二维码,从二维码中获取设备UUID。

扫码

build() {
    Column() {
      Row() {
        Button("点击扫码")
          .backgroundColor('#0D9FFB')
          .fontSize(20)
          .fontColor('#FFFFFF')
          .fontWeight(FontWeight.Normal)
          .align(Alignment.Center)
          .type(ButtonType.Capsule)
          .width('90%')
          .height(40)
          .margin({ top: 50, bottom: 5 })
          .enabled(this.scanBtnEnable)
          .onClick(() => {
            this.scanBtnEnable = false;
            // 定义扫码参数options
            let options: scanBarcode.ScanOptions = {
              scanTypes: [scanCore.ScanType.ALL],
              enableMultiMode: true,
              enableAlbum: true
            };
            try {
              scanBarcode.startScanForResult(getContext(this), options).then((result: scanBarcode.ScanResult) => {
                // 解析码值结果
                hilog.info(0x0001, '[Scan CPSample]', `Succeeded in getting ScanResult by promise with options, result is ${JSON.stringify(result)}`);
                this.parseQRCode(result['originalValue'] as string);

              }).catch((error: BusinessError) => {
                this.scanBtnEnable = true;
                hilog.error(0x0001, '[Scan CPSample]',
                  `Failed to get ScanResult by promise with options. Code:${error.code}, message: ${error.message}`);
              });
            } catch (error) {
              this.scanBtnEnable = true;
              hilog.error(0x0001, '[Scan CPSample]',
                `Failed to start the scanning service. Code:${error.code}, message: ${error.message}`);
            }
          })
      }

    }
    .width('100%')
  }

解析扫描结果

  parseQRCode(code: string) {
    TSmartActivatorRequester.parseQRCode(code).then(res => {
      console.log('parseQRCode ', JSON.stringify(code));
      // {"actionData":{"uuid":"dc18219067cf0516"},"actionName":"device_net_conn_multi_ver"}
      if (res['actionName'] === 'device_net_conn_multi_ver') {
        this.uuid = (res['actionData'] as Record<string, string>)['uuid'];
      }
    }).catch((error: Error) => {
      console.log('parseQRCode error');
    })
  }

配网实现配网监听器中的方法

activatorListener: ITSmartActivatorListener = {
    onActiveSetpAndError: (step: TSmartActivatorStep, error?: Error, device?: TSmartDeviceModel) => {
      // 实现相关逻辑
    },

    onActiveSuccess: (deviceModel: TSmartDeviceModel) => {
      // 处理配网成功的逻辑,例如更新UI,跳转到下一个页面
    },
};

创建配网实例

    const builder = TSmartActivator.buildMQTTDirectlyActivatorBuilder(homeId, this.uuid!, 120000,this.activatorListener);
    this.activator = TSmartActivator.createActivator(builder);

调用开始配网

this.activator.startActive()

调用停止配网

this.activator.stopActive()