Browse Source

修改usb访问

cjb 2 weeks ago
parent
commit
3ed77c3768

+ 15 - 38
entry/src/main/ets/common/util/PreviewManager.ets

@@ -1,5 +1,5 @@
 import image from '@ohos.multimedia.image';
-import fs from "@ohos.file.fs"
+const TAG = "sony_camera info"
 export class PreviewManager {
   // 上下文对象
   private context: Context;
@@ -9,37 +9,17 @@ export class PreviewManager {
   private nextBuffer: PixelMap | null = null;
   // 处理状态标志,防止重复处理
   private isProcessing: boolean = false;
-  // 上一帧处理完成的时间戳
-  private lastFrameTime: number = 0;
-  // 目标帧率(帧/秒)
-  private targetFPS: number = 20;
-  // 帧间隔时间(毫秒),根据目标帧率计算
-  private frameInterval: number = 1000 / this.targetFPS;
   // 缓冲区交换锁,防止并发交换
   private bufferLock: boolean = false;
-  // private errorCount: number = 0; // 错误计数器
-  // private readonly MAX_ERROR_COUNT = 5; // 最大连续错误次数
 
   constructor(context: Context) {
     this.context = context;
   }
-  //设置目标帧率
-  setTargetFPS(fps: number): void {
-    this.targetFPS = fps;
-    this.frameInterval = 1000 / fps;
-  }
   //处理指定索引的帧
   async processFrame(index: number): Promise<boolean> {
-    if (this.isProcessing) return false;
-
-    // 检查错误次数
-    // if (this.errorCount >= this.MAX_ERROR_COUNT) {
-    //   console.error("达到最大错误次数,暂停处理");
-    //   return false;
-    // }
-
-    const now = Date.now();
-    if (now - this.lastFrameTime < this.frameInterval) {
+    if (this.isProcessing)
+    {
+      console.info(TAG,"isprocessing")
       return false;
     }
 
@@ -47,17 +27,17 @@ export class PreviewManager {
     try {
       const filePath = `${this.context.filesDir}/live${index}.jpg`;
 
-      // 1. 文件检查
-      try {
-        await fs.access(filePath); // 仅检查文件是否存在
-      } catch (error) {
-        console.warn("文件访问失败:", error);
-        return false;
-      }
+      // // 1. 文件检查
+      // try {
+      //   await fs.access(filePath); // 仅检查文件是否存在
+      // } catch (error) {
+      //   console.warn("文件访问失败:", error);
+      //   return false;
+      // }
       // 2. 创建图像源
       const imageSource = image.createImageSource(filePath);
       if (!imageSource) {
-        console.warn("创建ImageSource失败");
+        console.warn(TAG,"创建ImageSource失败");
         return false;
       }
       try {
@@ -68,21 +48,18 @@ export class PreviewManager {
           desiredPixelFormat: 3 // RGB_565节省内存
         });
         if (!pixelMap) {
-          console.warn("创建PixelMap失败");
+          console.warn(TAG,"创建PixelMap失败");
           return false;
         }
         // 5. 安全交换缓冲区
         this.nextBuffer = pixelMap;
         this.swapBuffers();
-        this.lastFrameTime = now;
-        //this.errorCount = 0; // 重置错误计数
         return true;
       } finally {
         imageSource.release();
       }
     } catch (error) {
-      //this.errorCount++;
-     // console.warn(`处理预览帧失败(${this.errorCount}/${this.MAX_ERROR_COUNT}):`, error);
+      console.error(TAG,`处理预览帧失败`, error);
       return false;
     } finally {
       this.isProcessing = false;
@@ -104,7 +81,7 @@ export class PreviewManager {
     }
   }
   //获取当前活跃缓冲区
-  getActiveBuffer(): PixelMap | null {
+  async getActiveBuffer(): Promise<PixelMap | null> {
     return this.activeBuffer;
   }
   //检查是否准备好显示

+ 79 - 106
entry/src/main/ets/common/util/UsbDevice.ets

@@ -17,140 +17,113 @@ export const USBDeviceIds: Array<UsbDeviceInfo> = [
 
 // USB设备信息接口
 interface UsbDeviceInfo {
-  DeviceName: string
-  VendorId: number
-  ProductId: number
+  DeviceName: string;
+  VendorId: number;
+  ProductId: number;
 }
 
-// USB设备管理类(单例)
-export class USBDeviceManager {
-  private static instance: USBDeviceManager | null = null;
+export
+class USBDeviceManager {
   private connectedDevices: Array<usbManager.USBDevice> = [];
-  private checkIntervalId: number | null = null;
-  private refreshLock: Promise<void> = Promise.resolve();
-  private deviceCheckLock: Promise<void> = Promise.resolve();
-
-  private constructor() {
-    this.init();
-  }
-
-  // 异步初始化
-  private async init(): Promise<void> {
-    await this.refreshDeviceList();
-    this.startAutoCheck();
-  }
-
-  // 获取单例实例(异步)
-  public static async getInstance(): Promise<USBDeviceManager> {
-    if (!USBDeviceManager.instance) {
-      USBDeviceManager.instance = new USBDeviceManager();
-      await USBDeviceManager.instance.init();
-    }
-    return USBDeviceManager.instance;
-  }
-
-  // 开始自动检测(异步)
-  private startAutoCheck(): void {
-    this.stopAutoCheck();
-
-    this.checkIntervalId = setInterval(async () => {
+  private pollTimer: number | null = null;
+  private isPollingPaused: boolean = false;
+
+  // 启动轮询(带暂停控制)
+  public startPolling(interval: number, callback: (devices: usbManager.USBDevice[]) => void): void {
+    this.stopPolling(); // 先停止已有轮询
+    this.pollTimer = setInterval(async () => {
+      if (this.isPollingPaused) return; // 暂停时跳过检测
       try {
-        await this.refreshDeviceList();
-        await this.checkDevices();
+        this.connectedDevices = await this.refreshDeviceList();
+        callback(this.connectedDevices);
       } catch (error) {
-        console.error('[AsyncUSB] 自动检测失败:', (error as BusinessError).message);
+        console.error('轮询失败:', (error as BusinessError).message);
       }
-    }, 2000);
+    }, interval)  as number; // 鸿蒙中setInterval返回类型需转换
   }
 
-  // 停止自动检测
-  public stopAutoCheck(): void {
-    if (this.checkIntervalId !== null) {
-      clearInterval(this.checkIntervalId);
-      this.checkIntervalId = null;
-    }
+  // 暂停轮询
+  public pausePolling(): void {
+    this.isPollingPaused = true;
   }
 
-  // 异步检查设备连接状态
-  private async checkDevices(): Promise<void> {
-    return this.deviceCheckLock = this.deviceCheckLock.then(async () => {
-      const hasDevices = await this.hasConnectedDevices();
-      if (hasDevices) {
-        // 替换解构赋值为单独变量声明
-        const connectedResults = await Promise.all([
-          this.isDeviceConnectedByName('Sony_Camera'),
-          this.isDeviceConnectedByName('Scanning_Gun')
-        ]);
-        const isCameraConnected = connectedResults[0];
-        const isScannerConnected = connectedResults[1];
-        AppStorage.setOrCreate<boolean>('CameraStatus', isCameraConnected);
-        AppStorage.setOrCreate<boolean>('ScanningGunStatus', isScannerConnected);
-      } else {
-        console.log('USB状态检测', '没有USB设备连接');
-      }
-    });
+  // 恢复轮询
+  public resumePolling(): void {
+    this.isPollingPaused = false;
   }
 
-  // 异步刷新设备列表
-  public async refreshDeviceList(): Promise<void> {
-    return this.refreshLock = this.refreshLock.then(async () => {
-      try {
-        this.connectedDevices = await new Promise((resolve, reject) => {
-          try {
-            const devices = usbManager.getDevices();
-            resolve(devices);
-          } catch (error) {
-            reject(error);
-          }
-        });
-        console.log('[AsyncUSB] 当前连接的设备:', this.connectedDevices);
-      } catch (error) {
-        console.error('[AsyncUSB] 获取USB设备失败:', (error as BusinessError).message);
-        this.connectedDevices = [];
-      }
-    });
+  // 停止轮询(释放资源)
+  public stopPolling(): void {
+    if (this.pollTimer !== null) {
+      clearInterval(this.pollTimer);
+      this.pollTimer = null;
+    }
+    this.isPollingPaused = false;
+  }
+
+  /* 手动刷新设备列表(需主动调用)
+  * @returns 返回刷新后的设备列表
+  */
+  public async refreshDeviceList(): Promise<Array<usbManager.USBDevice>> {
+    try {
+      this.connectedDevices = usbManager.getDevices();
+      console.log('[USB] 当前连接的设备:', this.connectedDevices);
+      return this.connectedDevices;
+    } catch (error) {
+      console.error('[USB] 获取USB设备失败:', (error as BusinessError).message);
+      this.connectedDevices = [];
+      return [];
+    }
   }
 
-  // 异步检查是否有USB设备连接
-  public async hasConnectedDevices(): Promise<boolean> {
-    await this.refreshLock;
+  /* 检查是否有USB设备连接
+  * @param forceRefresh 是否强制刷新设备列表
+  */
+  public async hasConnectedDevices(forceRefresh: boolean = false): Promise<boolean> {
+    if (forceRefresh || this.connectedDevices.length === 0) {
+      await this.refreshDeviceList();
+    }
     return this.connectedDevices.length > 0;
   }
 
-  // 异步检查特定USB设备是否连接
-  public async isDeviceConnectedById(vendorId: number, productId: number): Promise<boolean> {
-    await this.refreshLock;
+  /* 检查特定设备是否连接
+  * @param vendorId 厂商ID
+  * @param productId 产品ID
+  * @param forceRefresh 是否强制刷新
+  */
+  public async isDeviceConnectedById(
+    vendorId: number,
+    productId: number,
+    forceRefresh: boolean = false
+  ): Promise<boolean> {
+    if (forceRefresh) {
+      await this.refreshDeviceList();
+    }
     return this.connectedDevices.some(device =>
     device.vendorId === vendorId && device.productId === productId
     );
   }
 
-  // 异步检查USB设备是否连接
-  public async isDeviceConnectedByInfo(usbDevice: UsbDeviceInfo): Promise<boolean> {
-    return this.isDeviceConnectedById(usbDevice.VendorId, usbDevice.ProductId);
-  }
-
-  // 异步检查预定义的设备是否连接
-  public async isDeviceConnectedByName(deviceName: string): Promise<boolean> {
-    await this.refreshLock;
+  /* 检查预定义的设备是否连接
+  * @param deviceName 设备名称(需在USBDeviceIds中定义)
+  * @param forceRefresh 是否强制刷新
+  */
+  public async isDeviceConnectedByName(
+    deviceName: string,
+    forceRefresh: boolean = false
+  ): Promise<boolean> {
     const deviceInfo = USBDeviceIds.find(item => item.DeviceName === deviceName);
-
     if (!deviceInfo) {
-      console.warn(`[AsyncUSB] 设备 ${deviceName} 不在预定义列表中`);
+      console.warn(`[USB] 设备 ${deviceName} 不在预定义列表中`);
       return false;
     }
-    return this.isDeviceConnectedById(deviceInfo.VendorId, deviceInfo.ProductId);
+    return this.isDeviceConnectedById(deviceInfo.VendorId, deviceInfo.ProductId, forceRefresh);
   }
 
-  // 异步获取所有已连接的USB设备
-  public async getAllDevices(): Promise<Array<usbManager.USBDevice>> {
-    await this.refreshLock;
+  /*
+  * 获取当前缓存的设备列表(不主动刷新)
+  */
+  public getCachedDevices(): Array<usbManager.USBDevice> {
     return [...this.connectedDevices];
   }
-
-  // 销毁实例
-  public destroy(): void {
-    this.stopAutoCheck();
-    USBDeviceManager.instance = null;
-  }
 }

+ 49 - 47
entry/src/main/ets/pages/CameraView.ets

@@ -13,7 +13,7 @@ import { PreviewManager } from '../common/util/PreviewManager';
 const TAG = "sony_camera info"
 @Entry
 @Component
-struct RgvControl {
+struct CameraControl {
   @StorageLink('CameraStatus') cameraStatus: boolean = false;
   commonDialogController: CustomDialogController | null = null;
   build() {
@@ -174,8 +174,9 @@ export struct CameraDialog {
   // 控制帧率
   @State readTimer:number = 0
   // 预览操作
-  private previewManager: PreviewManager | null =null ;
+  private previewManager: PreviewManager | null = null;
   @State photoPixelMaps: photoInfo[] = []; // 存储所有照片的 PixelMap
+
   // 加载照片并生成 PixelMap
   loadPhotos = async () => {
     const context = getContext(this);
@@ -425,6 +426,7 @@ export struct CameraDialog {
         console.info(TAG,"Publish openSession err=" + JSON.stringify(err))
       } else {
         console.info(TAG,"Publish openSession succeed ")
+        this.queryFlashMode();
       }
     })
   }
@@ -432,19 +434,20 @@ export struct CameraDialog {
   queryFlashMode = async () => {
     CommonEventManager.publish("queryflashmode", (err) => {
       if (err?.code) {
-        console.info(TAG,"Publish openSession err=" + JSON.stringify(err))
+        console.info(TAG,"Publish queryflashmode err=" + JSON.stringify(err))
       } else {
-        console.info(TAG,"Publish openSession succeed ")
+        console.info(TAG,"Publish queryflashmode succeed ")
       }
     })
   }
 
   //开始预览
-  startView=()=>{
+  startView=async()=>{
     CommonEventManager.publish("startview", (err) => {
       if (err?.code) {
         console.error(TAG, JSON.stringify(err));
       } else {
+        console.info(TAG, 'publish startview succeed');
         this.isStopView =false;
         this.liveShow();
       }
@@ -458,6 +461,11 @@ export struct CameraDialog {
         console.error(TAG, JSON.stringify(err));
       } else {
         this.isStopView =true;
+        console.info(TAG, 'publish stopview succeed');
+        if (this.readTimer) {
+          clearInterval(this.readTimer);
+          this.readTimer = 0 ;
+        }
       }
     });
   }
@@ -494,58 +502,54 @@ export struct CameraDialog {
     });
   }
 
-  //开始预览 50ms一张图片(20帧)
   liveShow = async () => {
-    if (this.previewManager) {
-      this.previewManager.release();
-    }
-    if (this.readTimer) {
-      clearInterval(this.readTimer);
-    }
-    this.previewManager = new PreviewManager(getContext(this));
     let index = 0;
     let retryCount = 0;
-    const MAX_RETRIES = 5; // 最大重试次数
-    this.readTimer = setInterval(async () => {
+    const MAX_RETRIES = 10; // 最大重试次数
+
+    const previewLoop = async () => {
       if (!this.isStopView && !this.isCapturing) {
         try {
           const success = await this.previewManager!.processFrame(index);
           if (success) {
-            this.commodityPixelMap = this.previewManager!.getActiveBuffer();
-            retryCount=0;
+            this.commodityPixelMap = await this.previewManager!.getActiveBuffer();
+            retryCount = 0;
+          } else {
+            retryCount++;
+            console.warn(TAG, "processFrame失败");
           }
         } catch (error) {
-          retryCount++
+          retryCount++;
           console.warn(TAG, "预览更新失败:", error);
         }
       }
-      if(retryCount===MAX_RETRIES)
-      {
-        clearInterval(this.readTimer);
-        this.previewManager?.release();
-        this.stopView()
-        await sleep(50)
-        this.startView()
-        console.info(TAG, "预览更新:");
+
+      if (retryCount === MAX_RETRIES) {
+          clearInterval(this.readTimer)
+          this.readTimer = 0;
+          console.info(TAG,"GG")
+          return;
+          //this.reconnectCamera();
+      }
+      if (this.readTimer !== 0) { // 检查是否应该继续循环
+        this.readTimer = setTimeout(previewLoop, 50);
       }
-    }, 50);
-  };
+    };
 
+    this.readTimer = setTimeout(previewLoop, 50);
+  };
 
   //断开相机(停止预览->关闭连接)
-  disconnectCamera = () => {
-    CommonEventManager.publish("stopview", (err) => {
+  disconnectCamera = async () => {
+    if(!this.isStopView)
+    {
+     await this.stopView()
+    }
+    CommonEventManager.publish("closesession", (err) => {
       if (err?.code) {
-        console.info(TAG,"Publish stopview err=" + JSON.stringify(err))
+        console.info(TAG,"Publish closesession err=" + JSON.stringify(err))
       } else {
-        console.info(TAG,"Publish stopview succeed ")
-        CommonEventManager.publish("closesession", (err) => {
-          if (err?.code) {
-            console.info(TAG,"Publish closesession err=" + JSON.stringify(err))
-          } else {
-            console.info(TAG,"Publish closesession succeed ")
-          }
-        })
+        console.info(TAG,"Publish closesession succeed ")
       }
     })
   }
@@ -625,29 +629,27 @@ export struct CameraDialog {
 
   }
   async aboutToAppear() {
+    this.previewManager = new PreviewManager(getContext(this));
     this.loadPhotos();
     await this.createSubscriber();
+    await sleep(50)
     await this.connectCamera();
-    await this.queryFlashMode();
   }
 
   aboutToDisappear(): void {
-    this.isStopView = true;
     this.disconnectCamera()
+    if (this.previewManager) {
+      this.previewManager.release();
+      this.previewManager = null
+    }
     if (this.subscriber) {
       CommonEventManager.unsubscribe(this.subscriber);
     }
     this.releaseAllPixelMaps()
-    if (this.readTimer) {
-      clearInterval(this.readTimer);
-    }
     if (this.commodityPixelMap) {
       this.commodityPixelMap.release();
       this.commodityPixelMap = null;
     }
-    if (this.previewManager) {
-      this.previewManager.release();
-    }
   }
   build() {
     Row() {

+ 0 - 6
entry/src/main/ets/pages/ProcessIndex.ets

@@ -33,7 +33,6 @@ import { SelfInspectView } from '../view/process/SelfInspectView';
 import { MultiMediaCollect } from '../view/process/MultiMediaCollect';
 import { BarcodeAssociationDialog } from '../view/BarcodeAssociationDialog';
 import WorkOrderSeq from '../viewmodel/WorkOrderSeq';
-import { USBDeviceManager } from '../common/util/UsbDevice';
 import { InAndOutBoundDialog } from '../view/InAndOutBoundDialog';
 import { LittleMaterialRequestDialog } from '../view/LittleMaterialRequestDialog';
 import { PictureDrawingDialog } from '../view/PictureDrawingDialog';
@@ -336,10 +335,6 @@ struct ProcessIndex {
     }
   }
 
-  connectUsbDevice=async()=>{
-    return await USBDeviceManager.getInstance();
-  }
-
   onPageShow() {
     const params = router.getParams() as Params; // 获取传递过来的参数对象
     if (params && params.auxiliaryOperationFlag) {
@@ -370,7 +365,6 @@ struct ProcessIndex {
     }
     // 创建mqtt连接和usb设备连接
     this.connectMQTT()
-    this.connectUsbDevice()
 
     // 判断是否选中工单,未选择则选则工单
     if (!this.selectWorkOder || !this.selectWorkOder.workOrderCode) {

+ 28 - 5
entry/src/main/ets/view/AuxiliaryOperationView.ets

@@ -16,6 +16,8 @@ import CommonConstants from '../common/constants/CommonConstants'
 import router from '@ohos.router'
 import CardReader from '../viewmodel/device/CardReader'
 import TempHumiditySensor from '../viewmodel/device/TempHumiditySensor'
+import { USBDeviceManager } from '../common/util/UsbDevice'
+
 
 // 辅助操作弹窗
 @Component
@@ -53,9 +55,10 @@ export struct AuxiliaryOperationView {
   // 温湿度传感器
   @StorageProp('TempHumiditySensor') tempHumiditySensor: TempHumiditySensor = {}
   // 相机是否在线
-  @StorageProp('CameraStatus') cameraStatus: boolean = false
+  @State cameraStatus: boolean = false
   // 扫码枪是否在线
-  @StorageProp('ScanningGunStatus') scanningGunStatus: boolean = false
+  @State scanningGunStatus: boolean = false
+  private  usbManager = new USBDeviceManager();
 
   // 打开零星叫料弹窗
   openLittleMaterialRequestDialog?: () => void = () => {}
@@ -87,15 +90,35 @@ export struct AuxiliaryOperationView {
     }
   }
 
+  connectUsbDevice = async () => {
+    this.usbManager = new USBDeviceManager();
+    this.usbManager.startPolling(1000, async () => {
+      const cameraPromise = this.usbManager.isDeviceConnectedByName('Sony_Camera');
+      const scannerPromise = this.usbManager.isDeviceConnectedByName('Scanning_Gun');
+      this.cameraStatus = await cameraPromise;
+      this.scanningGunStatus = await scannerPromise;
+      AppStorage.setOrCreate<boolean>('CameraStatus', this.cameraStatus);
+    });
+  }
+
+  disConnectUsbDevice=async()=>{
+    this.usbManager.stopPolling();
+  }
+
   async aboutToAppear() {
     if (this.workOrderCode) {
       this.seqList = await ProcessRequest.post('/api/v1/plan/seq/list', {
         workOrderCode: this.workOrderCode
       } as RequestParamModel)
     }
+    this.connectUsbDevice()
     this.getBarcodeStatistics()
   }
 
+   async aboutToDisappear() {
+     this.disConnectUsbDevice()
+   }
+
   build() {
     Stack() {
       Image($r('app.media.process_drawer'))
@@ -667,9 +690,9 @@ export struct AuxiliaryOperationView {
                 .backgroundColor($r('app.color.20FFFFFF'))
                 .borderRadius($r('app.float.virtualSize_16'))
                 .onClick(()=>{
-                 router.pushUrl({
-                   url: 'pages/CameraView',
-                 })
+                  router.pushUrl({
+                    url: 'pages/CameraView',
+                  })
                 })
                 // 电烙铁
                 Column() {

+ 38 - 47
entry/src/main/ets/view/process/MultiMediaCollect.ets

@@ -203,6 +203,7 @@ export struct MultiMediaCollect {
         console.info(TAG,"Publish openSession err=" + JSON.stringify(err))
       } else {
         console.info(TAG,"Publish openSession succeed ")
+        this.queryFlashMode();
       }
     })
   }
@@ -237,6 +238,14 @@ export struct MultiMediaCollect {
         console.error(TAG, JSON.stringify(err));
       } else {
         this.isStopView =true;
+        console.info(TAG, 'publish stopview succeed');
+        if (this.previewManager) {
+          this.previewManager.release();
+        }
+        if (this.readTimer) {
+          clearInterval(this.readTimer);
+          this.readTimer = 0 ;
+        }
       }
     });
   }
@@ -272,57 +281,52 @@ export struct MultiMediaCollect {
     });
   }
 
-  //开始预览 50ms一张图片(20帧)
   liveShow = async () => {
-    if (this.previewManager) {
-      this.previewManager.release();
-    }
-    if (this.readTimer) {
-      clearInterval(this.readTimer);
-    }
-    this.previewManager = new PreviewManager(getContext(this));
     let index = 0;
     let retryCount = 0;
-    const MAX_RETRIES = 5; // 最大重试次数
-    this.readTimer = setInterval(async () => {
+    const MAX_RETRIES = 10; // 最大重试次数
+
+    const previewLoop = async () => {
       if (!this.isStopView && !this.isCapturing) {
         try {
           const success = await this.previewManager!.processFrame(index);
           if (success) {
-            this.commodityPixelMap = this.previewManager!.getActiveBuffer();
-            retryCount=0;
+            this.commodityPixelMap = await this.previewManager!.getActiveBuffer();
+            retryCount = 0;
+          } else {
+            retryCount++;
           }
         } catch (error) {
-          retryCount++
+          retryCount++;
           console.warn(TAG, "预览更新失败:", error);
         }
       }
-      if(retryCount===MAX_RETRIES)
-      {
-        clearInterval(this.readTimer);
-        this.previewManager?.release();
-        this.stopView()
-        await sleep(50)
-        this.startView()
-        console.info(TAG, "预览更新:");
+      if (retryCount === MAX_RETRIES) {
+        clearInterval(this.readTimer)
+        this.readTimer = 0;
+        console.info(TAG,"GG")
+        return;
+        //this.reconnectCamera();
+      }
+      if (this.readTimer !== 0) { // 检查是否应该继续循环
+        this.readTimer = setTimeout(previewLoop, 50);
       }
-    }, 50);
+    };
+
+    this.readTimer = setTimeout(previewLoop, 50);
   };
 
   //断开相机(停止预览->关闭连接)
-  disconnectCamera = () => {
-    CommonEventManager.publish("stopview", (err) => {
+  disconnectCamera = async () => {
+    if(!this.isStopView)
+    {
+      await this.stopView()
+    }
+    CommonEventManager.publish("closesession", (err) => {
       if (err?.code) {
-        console.info(TAG,"Publish stopview err=" + JSON.stringify(err))
+        console.info(TAG,"Publish closesession err=" + JSON.stringify(err))
       } else {
-        console.info(TAG,"Publish stopview succeed ")
-        CommonEventManager.publish("closesession", (err) => {
-          if (err?.code) {
-            console.info(TAG,"Publish closesession err=" + JSON.stringify(err))
-          } else {
-            console.info(TAG,"Publish closesession succeed ")
-          }
-        })
+        console.info(TAG,"Publish closesession succeed ")
       }
     })
   }
@@ -414,8 +418,8 @@ export struct MultiMediaCollect {
   async aboutToAppear() {
     this.loadPhotos();
     await this.createSubscriber();
+    await sleep(50)
     await this.connectCamera();
-    await this.queryFlashMode();
     uploadInstance.uploadParams = {
       token: "your_token_here", // 替换为实际 token
       operationMediaId: this.selectOperationId, // 默认值
@@ -430,22 +434,14 @@ export struct MultiMediaCollect {
   }
 
   aboutToDisappear(): void {
-    this.isStopView = true;
-    sleep(100)
     this.disconnectCamera()
     if (this.subscriber) {
       CommonEventManager.unsubscribe(this.subscriber);
     }
-    if (this.readTimer) {
-      clearInterval(this.readTimer);
-    }
     if (this.commodityPixelMap) {
       this.commodityPixelMap.release();
       this.commodityPixelMap = null;
     }
-    if (this.previewManager) {
-      this.previewManager.release();
-    }
   }
   build() {
     Row() {
@@ -830,8 +826,3 @@ function sleep(ms: number): Promise<void> {
   return new Promise((resolve) => setTimeout(resolve, ms));
 }
 
-
-interface CameraParam {
-  flash_mode: string;
-  moduleName?: string;
-}