Procházet zdrojové kódy

修改相机页面为base64.

jiaxiaoqiang před 3 měsíci
rodič
revize
d97737b9c3

+ 5 - 5
build-profile.json5

@@ -21,13 +21,13 @@
       {
         "name": "default",
         "material": {
-          "certpath": "C:/Users/suyat/.ohos/config/openharmony/default_common-station-web_vZFNwrVUnpY3mys1WI1huqdp1qAMQniXhwm2hXzDqzw=.cer",
-          "storePassword": "00000019CEA85C11F67495AD711499FA68E595A610FAFB257D57D5ED14D52A67E505935558E6F62C4C",
+          "certpath": "C:/Users/Administrator/.ohos/config/openharmony/default_ohos-station-web_3PrdxSBaGcCfy9Hg5yBarasQHvqCqV0r5a8yksCRxCU=.cer",
+          "storePassword": "0000001AD2318F0F8B29F4443C8F5D4FF192CE44AE632F559ED4D59B3E82D3E1481B19A2A8B2CCB9347A",
           "keyAlias": "debugKey",
-          "keyPassword": "00000019F9BDB276526512C9334D6E76D2B9B7346047185576241194B982DBB926339764834ABDC473",
-          "profile": "C:/Users/suyat/.ohos/config/openharmony/default_common-station-web_vZFNwrVUnpY3mys1WI1huqdp1qAMQniXhwm2hXzDqzw=.p7b",
+          "keyPassword": "0000001A24B7D29C1F84799AD8148067EFEC319517127B4F21D1F4DAD23D96F6336F01C62810465320D4",
+          "profile": "C:/Users/Administrator/.ohos/config/openharmony/default_ohos-station-web_3PrdxSBaGcCfy9Hg5yBarasQHvqCqV0r5a8yksCRxCU=.p7b",
           "signAlg": "SHA256withECDSA",
-          "storeFile": "C:/Users/suyat/.ohos/config/openharmony/default_common-station-web_vZFNwrVUnpY3mys1WI1huqdp1qAMQniXhwm2hXzDqzw=.p12"
+          "storeFile": "C:/Users/Administrator/.ohos/config/openharmony/default_ohos-station-web_3PrdxSBaGcCfy9Hg5yBarasQHvqCqV0r5a8yksCRxCU=.p12"
         }
       }
     ]

+ 152 - 45
entry/src/main/ets/pages/CameraVersion2.ets

@@ -7,6 +7,7 @@ import commonEvent from "@ohos.commonEvent";
 import CommonEventManager from '@ohos.commonEventManager'
 import uploadInstance from '../utils/UploadUtil';
 import router from '@ohos.router';
+import fileIo from '@ohos.file.fs';
 
 const TAG = "openHarmonyBridge upload"
 @Entry
@@ -19,8 +20,16 @@ struct Index {
    * */
   @State commodityPixelMap: PixelMap | null = null;
   @State isButtonPressed: boolean = false;
-  @State isCapturing: boolean = false; // 新增状态控制拍摄状态
-//
+  @State isCapturing: boolean = false;
+  @State isCloseView: boolean = false;// 新增状态控制拍摄状态
+  @State reminds:string = ''
+
+  remindController: CustomDialogController = new CustomDialogController({
+    builder: RemindDialog({
+      remind: this.reminds,}
+    ),
+  })
+  //
   subscriber: CommonEventManager.CommonEventSubscriber | null = null; // Used to save the created subscriber object for subsequent subscription and unsubscription.
   // Subscriber information.
   subscribeInfo: CommonEventManager.CommonEventSubscribeInfo = { events: ["sonycamera_callback"] };
@@ -43,14 +52,18 @@ struct Index {
   createSubscriber = async () => {
     this.subscriber = await CommonEventManager.createSubscriber(this.subscribeInfo);
     if (this.subscriber) {
-      console.info("[CommonEvent] Subscriber created successfully");
+      console.info(TAG,"创建订阅回调成功");
       CommonEventManager.subscribe(this.subscriber, (err, data) => {
         if (err?.code) {
           console.error("[CommonEvent] SubscribeCallBack err=" + JSON.stringify(err));
         } else {
           console.info("[CommonEvent] SubscribeCallBack data=" + JSON.stringify(data));
           if (data && data.code&&data.code === 2) {
+            console.info(TAG,"开始传输照片");
             this.handleCaptureSuccess()
+          }else if (data && data.code&&data.code === 3) {
+            console.info(TAG,"开始预览" );
+            this.publishStartView();
           }
         }
       });
@@ -59,33 +72,40 @@ struct Index {
 
   handleCaptureSuccess = () => {
     this.savePhoto();
+    // commonEvent.publish("startview", (err) => {
+    //   if (err?.code) {
+    //     console.error("Restart preview error:", JSON.stringify(err));
+    //   } else {
+    //     this.isCapturing = false;
+    //     this.isCloseView =false;
+    //     this.liveShow();// 拍摄完成后恢复预览
+    //     console.log("Restart success")
+    //   }
+    // });
+  };
+  publishStartView=()=>{
     commonEvent.publish("startview", (err) => {
       if (err?.code) {
         console.error("Restart preview error:", JSON.stringify(err));
       } else {
-        this.isCapturing = false; // 拍摄完成后恢复预览
+        this.isCapturing = false;
+        this.isCloseView =false;
+        this.liveShow();// 拍摄完成后恢复预览
         console.log("Restart success")
       }
     });
-  };
+  }
 
   connectCamera = async () => {
     commonEvent.publish("opensession", (err) => {
       if (err?.code) {
         console.info("[CommonEvent] Publish CallBack err=" + JSON.stringify(err))
       } else {
-        commonEvent.publish("startview", (err) => {
-          console.info("[CommonEvent] Publish opensession succeed ")
-          if (err?.code) {
-            console.info("[CommonEvent] Publish CallBack err=" + JSON.stringify(err))
-          } else {
-            console.info("[CommonEvent] Publish startview succeed ")
-          }
-        })
+        console.info("[CommonEvent] Publish opensession succeed ")
       }
     })
   }
-  disconnectCamera = async () => {
+  disconnectCamera = () => {
     commonEvent.publish("stopview", (err) => {
       if (err?.code) {
         console.info("[CommonEvent] Publish CallBack err=" + JSON.stringify(err))
@@ -101,12 +121,28 @@ struct Index {
       }
     })
   }
-  savePhoto=async()=>{
-    const context = getContext() as common.UIAbilityContext;
+  savePhoto=()=>{
+    let imageUri: string = "/data/storage/el2/base/haps/entry/files/image_base64.txt"
     console.log(TAG, "进入了savephoto")
     try {
+      const file = fileIo.openSync(imageUri, fileIo.OpenMode.READ_ONLY);
+      fileIo.closeSync(file.fd); // 关闭文件描述符
+      this.reminds= "照片传输到小黑盒成功"
+      this.remindController.open()
+      delayExecution(()=>{
+        this.remindController.close()
+      }, 1000)
+    } catch (error) {
+      console.error('文件不存在或无法访问:', error);
+      this.reminds= "照片传输到小黑盒失败"
+      this.remindController.open()
+      delayExecution(()=>{
+        this.remindController.close()
+      }, 1000)
+
+    }
+    try {
       // 获取相册访问的 helper 实例
-      const helper = photoAccessHelper.getPhotoAccessHelper(context);
 
       console.log(TAG, "进入了savephoto1")
       // 创建一个新的图片资产,并获取目标 URI
@@ -114,13 +150,14 @@ struct Index {
 
       // console.log(TAG, "进入了savephoto2")
       // 打开源文件和目标文件  这个是写死的 app的名字不能改
-      let imageUri: string = "/data/storage/el2/base/haps/entry/files/shoots.jpg"
+      // let imageUri: string = "/data/storage/el2/base/haps/entry/files/shoots.jpg"
       // 开始上传
       console.log(TAG, "开始上传", imageUri)
-      uploadInstance.startUpload(imageUri, () => {
+      uploadInstance.startUploadBase64(imageUri, () => {
 
         console.log(TAG, "上传完成后的callback")
         this.isUploading = false
+        this.publishStartView();
       })
 
 
@@ -143,6 +180,7 @@ struct Index {
     }
   }
   takePhoto = async () => {
+    this.isCloseView = true;
     this.isCapturing = true;
     commonEvent.publish("stopview", (err) => {
       if (err?.code) {
@@ -161,27 +199,64 @@ struct Index {
       }
     });
   };
+
+  readTimer = 0
+
   liveShow = async () => {
     const context: Context = getContext(this);
     let index = 0;
-    while (true) {
-      if(!this.isCapturing) {
-        const filePath: string = `${context.filesDir}/live${index}.jpg`;
-        console.info("icamera"+filePath)
+    let lastImagePath = '';
+
+     this.readTimer = setInterval( async () => {
+      if (!this.isCloseView) {
         try {
-          const imageSource = image.createImageSource(filePath);
-          if (imageSource) {
-            this.commodityPixelMap = await imageSource.createPixelMap();
+          if(!this.isCapturing) {
+            const filePath: string = `${context.filesDir}/live${index}.jpg`;
+            // 检查文件是否存在
+            try {
+              fs.accessSync(filePath);
+
+              // 只有当文件路径改变时才更新图像
+              if (filePath !== lastImagePath) {
+                const imageSource = image.createImageSource(filePath);
+                if (imageSource) {
+                  try {
+                    // 创建新的PixelMap之后再释放旧的
+                    const newPixelMap = await imageSource.createPixelMap();
+                    if (this.commodityPixelMap) {
+                      this.commodityPixelMap.release();
+                    }
+                    this.commodityPixelMap = newPixelMap;
+                    imageSource.release();
+                    lastImagePath = filePath;
+                    index = (index + 1) % 10;
+                  } catch(error) {
+                    console.error(TAG, "创建PixelMap失败:", error);
+                    // break
+                  }
+                }
+              }
+            } catch (error) {
+              // await sleep(30);
+              // continue;
+            }
+
           }
-          console.info("demo"+"file exists");
+          // 减小循环间隔提高流畅度
+
         } catch (error) {
-          console.info("demo"+"file not exists");
+          console.error(TAG, "预览错误:", error);
+
         }
-        index = (index + 1) % 10;
       }
-      await sleep(50);
+    }, 50)
+
+    // 退出时清理资源
+    if(this.commodityPixelMap) {
+      this.commodityPixelMap.release();
+      this.commodityPixelMap = null;
     }
-  }
+  };
 
   aboutToAppear(): void {
     this.createSubscriber();
@@ -191,10 +266,13 @@ struct Index {
   }
 
   aboutToDisappear(): void {
+    this.isCloseView = true;
     this.disconnectCamera();
     if (this.subscriber) {
       CommonEventManager.unsubscribe(this.subscriber);
     }
+
+    clearInterval(this.readTimer)
   }
 
   build() {
@@ -213,21 +291,30 @@ struct Index {
               .height('100%')
               .objectFit(ImageFit.Contain)
 
-            if (this.isUploading) {
-              Column() {
-                Text('正在上传中...').fontSize(22).margin({ top: 10, bottom: 10 })
-                LoadingProgress()
-                  .color(Color.Blue)
-                  .layoutWeight(1)
-              }
-              .height(140)
-              .width(150)
-              .backgroundColor(Color.White)
-              .borderRadius(10)
-            }
-
           }
+        }
+        if (this.isUploading) {
+          Stack({ alignContent: Alignment.Center }) {
+            // 半透明黑色背景蒙层
+            Column() {
+              Text('正在上传中...')
+                .fontSize(22)
+                .margin({ top: 10, bottom: 10 })
 
+              LoadingProgress()
+                .color(Color.Blue)
+                .width(50)
+                .height(50)
+            }
+            .height(140)
+            .width(150)
+            .backgroundColor(Color.White)
+            .borderRadius(10)
+            .justifyContent(FlexAlign.Center)
+          }
+          .width('100%')
+          .height('100%')
+          .position({ x: 0, y: 0 })
         }
       }
       .width('100%')
@@ -269,6 +356,9 @@ struct Index {
         .height(70)
         .backgroundColor('#1c1c1c')
         .onClick(() => {
+          this.isCloseView = true;
+          sleep(100)
+          this.disconnectCamera()
           router.back()        })
 
       }.width('100%')
@@ -356,5 +446,22 @@ struct Index {
 function sleep(ms: number): Promise<void> {
   return new Promise((resolve) => setTimeout(resolve, ms));
 }
+@CustomDialog
+struct RemindDialog {
+  controller: CustomDialogController
+  @Link remind: string
+  build() {
+    Column() {
+      Text(this.remind)
+        .fontSize(20)
+        .margin({ top: 10, bottom: 10 })
+    }
+  }
+}
 
-
+function delayExecution(callback: Function, delay: number) {
+  let timerId = setInterval(() => {
+    clearInterval(timerId);
+    callback();
+  }, delay);
+}

+ 3 - 3
entry/src/main/ets/pages/Index.ets

@@ -5,10 +5,10 @@ import uploadInstance from "../utils/UploadUtil"
 
 
 const TAG = "openHarmonyBridge" //webview和vue沟通的名称
-// const webUrl = "http://192.168.1.4:11000/"
-// const webUrl = "http://192.168.0.47:3005/"
+// const webUrl = "http://192.168.1.4:11000/"  //创客前端服务
+const webUrl = "http://192.168.0.49:3005/"  //本地跑的项目
 
-const webUrl = "http://10.88.11.201:11000/"
+// const webUrl = "http://10.88.11.201:11000/"  //险峰服务
 
 class BridgeModel {
   constructor() {

+ 3 - 2
entry/src/main/ets/utils/Request.ets

@@ -13,7 +13,8 @@ import RequestParamsModel from './requestParams';
 import uploadInstance from './UploadUtil';
 
 // jxq: 项目基本请求路径 险峰的
-export  const JGRequestBaseUrl = "http://10.88.11.200:8079/"
+// export  const JGRequestBaseUrl = "http://10.88.11.200:8079/" //险峰
+export  const JGRequestBaseUrl = "http://192.168.1.4:8079/" // 创客
 
 const DEBUG = true //
 
@@ -24,7 +25,7 @@ const JGRequest = axios.create(
     headers: {
       'Content-Type': 'application/json;charset=UTF-8',
     },
-    timeout: 60 * 1000,
+    timeout: 20 * 1000,
   }
 )
 

+ 61 - 1
entry/src/main/ets/utils/UploadUtil.ets

@@ -5,6 +5,7 @@ import fs from '@ohos.file.fs';
 import { ProgressDialog } from '../components/ProgressDialog';
 import JGRequest, { JGRequestBaseUrl } from './Request';
 import web_webview from '@ohos.web.webview';
+import { AxiosResponse } from '@ohos/axios';
 
 const TAG = "openHarmonyBridge upload"
 
@@ -25,6 +26,8 @@ interface BridgeParams {
 // 上传文件后,返回一个图片的url,然后再调用其他接口上传url和一些值, 如果有其他接口需要key,在这里添加,然后在下面赋值就行了
 interface APIParamsModel extends BridgeParams {
   filePath?: string, //工序的多媒体采集需要用到的key
+  file?: string,
+  fileName?: string,
 }
 
 interface ResultModel {
@@ -64,10 +67,67 @@ class UploadUtil {
     this.uploadParams = model
   }
 
+  startUploadBase64(uri: string, callBack: () => void) {
+
+
+    try {
+
+      let base64Test =  fs.readTextSync(uri)
+      console.log(TAG, "baes64",base64Test)
+
+      let base64Data: APIParamsModel = {
+        file: base64Test,
+        fileName: 'test.jpg',
+      }
+      JGRequest.request({
+        method:  "post",
+        url: "api/v1/base/uploadBase64",
+        data: base64Data
+      }).then( async (res: AxiosResponse) => {
+        let result: ResultModel = JSON.parse(res.data as string)
+        console.log(TAG, "ddddddd success", JSON.stringify(result?.data ?? ""));
+
+        // 上传完成后调其他接口
+        if (this.uploadParams.apiUrlPath) {
+          let data: APIParamsModel = {
+            filePath: result.data?.fileUrl ?? "",
+            operationMediaId: this.uploadParams?.operationMediaId ?? "",
+            processId: this.uploadParams?.processId ?? "",
+            seqNo: this.uploadParams?.seqNo ?? "",
+          }
+
+          await JGRequest.request({
+            method: this.uploadParams?.method ?? "post",
+            url: this.uploadParams?.apiUrlPath,
+            data: data
+          })
+        }
+
+        // 这个是 给webview发送post messages 通知的
+        if (this.uploadParams.messageKey) {
+          uploadInstance.ports = uploadInstance.controller!.createWebMessagePorts();
+          uploadInstance.controller!.postMessage(JSON.stringify({
+            fullUrl: this.fileUrl + result.data?.fileUrl ?? "",
+            messageKey: this.uploadParams.messageKey ?? ""
+          }), [uploadInstance.ports[0]], '*');
+        }
+
+        callBack()
+      }).catch(() => {
+        callBack()
+      })
+
+
+    }
+    catch (e) {
+      callBack()
+      console.log(TAG, 'mk-logger', 'photoPlugin-str', JSON.stringify(e))
+    }
+  }
+
   startUpload(uri: string, callBack: () => void) {
 
 
-    // console.log(TAG, "token", this.token === this.uploadParams)
     //   开始上传
     try {
       // 2.2 根据uri同步打开文件

+ 21 - 5
entry/src/main/resources/rawfile/camera_install.bat

@@ -1,17 +1,33 @@
 @echo ================================================
-@echo     COPY AND INSTALL
+@echo     COPY, INSTALL AND START SERVICE
 @echo ================================================
 @echo START %date:~0,10% %time:~0,8%
 
 @echo ------------
-
+@hdc shell mount -o remount,rw /
 @hdc shell mount -o remount,rw /vendor
-@hdc shell "cd /vendor/bin && ./sonycamera_lib" 
+@rem 终止主进程和所有子进程
+@hdc shell "killall -9 sonycamera_exe || true"
 
+@hdc file send sonycamera_exe /vendor/bin
+@hdc shell chmod a+x /vendor/bin/sonycamera_exe
 
 @echo ------------
+@echo Starting sonycamera_exe service...
 
-@echo END %date:~0,10% %time:~0,8%
-pause
+@rem 终止主进程和所有子进程
+@hdc shell "killall -9 sonycamera_exe || true"
+
+@rem 在后台启动新进程
+@hdc shell "/vendor/bin/sonycamera_exe"
+
+@rem 等待几秒确保进程启动
+@timeout /t 2 /nobreak > nul
 
+@rem 验证进程是否成功启动
+@hdc shell "ps | grep sonycamera_exe"
 
+@echo ------------
+
+@echo END %date:~0,10% %time:~0,8%
+pause