From cb2a01ee7dea28a2661720060b03c41dc372acb5 Mon Sep 17 00:00:00 2001
From: yaowanxin <3588231647@qq.com>
Date: 星期五, 01 八月 2025 11:53:16 +0800
Subject: [PATCH] 完善串口处理数据,数据选择

---
 src/views/system/user/index.vue                  |    2 
 src/utils/connect.js                             |   99 ++++++++++++++++++------
 src/views/business/inspectionTask/inspection.vue |  134 ++++++++++++++++++++++++---------
 3 files changed, 173 insertions(+), 62 deletions(-)

diff --git a/src/utils/connect.js b/src/utils/connect.js
index 39edfd6..251a15e 100644
--- a/src/utils/connect.js
+++ b/src/utils/connect.js
@@ -1,10 +1,30 @@
+import request from '@/utils/request';
 // 鏂板锛氬瓨鍌ㄥ叏灞�涓插彛鍜岃鍙栧櫒瀹炰緥
     let port = null;
     let reader = null;
     let accumulatedData = ""; // 绉诲埌鍏ㄥ眬锛屼究浜庡叧闂椂閲嶇疆
+    let weightList = []; // 鐢ㄤ簬瀛樺偍閲嶉噺鍊肩殑鍒楄〃
+
+    async function sendWeightsToBackend(weights) {
+      try {
+        // 浣跨敤 await 绛夊緟 request 鍑芥暟杩斿洖缁撴灉
+        const response = await request({
+          url: "/weight/handleWeights",
+          method: "POST",
+          data: weights, // 閫氬父 request 鍑芥暟浣跨敤 data 瀛楁浼犻�掓暟鎹�
+        });
+        // 鏍规嵁 request 鍑芥暟鐨勫疄鐜板垽鏂搷搴旀槸鍚︽垚鍔�
+        if (response.code !== 200) { // 鍋囪 response 鏈� code 瀛楁锛�200 琛ㄧず鎴愬姛
+          throw new Error(`Backend response error: ${response.message}`);
+        }
+        return response.data; // 鍋囪鍝嶅簲鏁版嵁鍦� data 瀛楁涓�
+      } catch (error) {
+        console.error('鍙戦�侀噸閲忔暟鎹埌鍚庣澶辫触:', error);
+        throw error;
+      }
+    }
 
     async function connect() {
-      if ("serial" in navigator) {
         try {
           port = await navigator.serial.requestPort(); // 淇敼涓哄叏灞�鍙橀噺
           await port.open({ baudRate: 9600 });
@@ -28,16 +48,36 @@
         } catch (error) {
           console.error("涓插彛閿欒:", error);
         }
-      }
-
+    }
       function processAccumulatedData(data) {
+
         if (data.includes("\n")) {
           const messages = data.split("\n");
 
           for (let i = 0; i < messages.length - 1; i++) {
             const completeMessage = messages[i];
             console.log("瀹屾暣娑堟伅:", completeMessage);
-            handleMessage(completeMessage);
+            // 鎻愬彇鏁板��
+            const weightValue = extractWeightValue(completeMessage);
+            if (!isNaN(weightValue)) {
+              console.log("鎻愬彇鐨勯噸閲忓��:", weightValue); 
+              // 灏嗘湁鏁堥噸閲忓�兼坊鍔犲埌鍒楄〃
+              weightList.push(weightValue);
+
+              // 褰撳垪琛ㄩ暱搴﹁揪鍒� 6 鏃讹紝鍙戦�佹暟鎹埌鍚庣骞舵竻绌哄垪琛�
+              if (weightList.length === 6) { 
+                sendWeightsToBackend({
+                  weights: weightList
+                })
+                .then(() => {
+                  console.log('鏁版嵁鍙戦�佹垚鍔�');
+                  weightList = [];
+                })
+                .catch(() => {
+                  console.log('鍙戦�佸け璐ワ紝淇濈暀鏁版嵁寰呴噸璇�');
+                });
+              }
+            }
           }
 
           accumulatedData = messages[messages.length - 1];
@@ -45,29 +85,38 @@
 
         // 鍏朵粬娑堟伅鎷嗗垎绀轰緥淇濇寔涓嶅彉
         /*
-  while (accumulatedData.length >= 32) {
-    const message = accumulatedData.substring(0, 32);
-    accumulatedData = accumulatedData.substring(32);
-    handleMessage(message);
-  }
-  */
+        while (accumulatedData.length >= 32) {
+          const message = accumulatedData.substring(0, 32);
+          accumulatedData = accumulatedData.substring(32);
+          handleMessage(message);
+        }
+        */
 
         /*
-  let startIndex = 0;
-  while (true) {
-    const start = accumulatedData.indexOf(0xAA, startIndex);
-    if (start === -1) break;
-    
-    const end = accumulatedData.indexOf(0x55, start + 1);
-    if (end === -1) break;
-    
-    const message = accumulatedData.substring(start, end + 1);
-    accumulatedData = accumulatedData.substring(end + 1);
-    handleMessage(message);
-    startIndex = start;
-  }
-  */
+        let startIndex = 0;
+        while (true) {
+          const start = accumulatedData.indexOf(0xAA, startIndex);
+          if (start === -1) break;
+          
+          const end = accumulatedData.indexOf(0x55, start + 1);
+          if (end === -1) break;
+          
+          const message = accumulatedData.substring(start, end + 1);
+          accumulatedData = accumulatedData.substring(end + 1);
+          handleMessage(message);
+          startIndex = start;
+        }
+        */
       }
+    }
+    // 鏂板鎻愬彇閲嶉噺鏁板�肩殑鏂规硶
+    function extractWeightValue(message) {
+      // 鍖归厤鏁板�奸儴鍒嗭紝鍙鐞嗘璐熷彿
+      const match = message.match(/-?\d+\.?\d*/); 
+      if (match) {
+        return parseFloat(match[0]);
+      }
+      return NaN;
     }
 
     // 鏂板锛氬叧闂繛鎺ュ嚱鏁�
@@ -93,4 +142,4 @@
       }
     }
 
-    export { connect, disconnect };
\ No newline at end of file
+    export { connect, disconnect,weightList };
\ No newline at end of file
diff --git a/src/views/business/inspectionTask/inspection.vue b/src/views/business/inspectionTask/inspection.vue
index 01ef6f2..d32723c 100644
--- a/src/views/business/inspectionTask/inspection.vue
+++ b/src/views/business/inspectionTask/inspection.vue
@@ -447,7 +447,7 @@
                 <el-checkbox-group v-if="!item.child[0].isShowSelect" v-model="item.child[0].getDataIndex1"
                   :max="item.child[0].maxNum">
                   <el-checkbox v-for="(n, j) in item.child[0].arr" :key="index + '-' + j + 'aaaaaa'" :label="j + '^' + n"
-                  @change="handleGroupSelect(item.child[0], j)" >{{ n }}</el-checkbox>
+                  @change="handleGroupSelect(item.child[0], j, item.child[0].arr.length)" >{{ n }}</el-checkbox>
                 </el-checkbox-group>
               </div>
             </td>
@@ -478,7 +478,7 @@
                 </el-select>
                 <el-checkbox-group v-if="!m.isShowSelect" v-model="m.getDataIndex1" :max="m.maxNum">
                   <el-checkbox v-for="(n, j) in m.arr" :key="index + '-' + j + 'dddddddd'" :label="j + '^' + n"
-                  @change="handleGroupSelect(m, j)" >{{ n }}</el-checkbox>
+                  @change="handleGroupSelect(m, j, m.arr.length)" >{{ n }}</el-checkbox>
                 </el-checkbox-group>
               </div>
             </td>
@@ -526,6 +526,7 @@
       :purchaseDialog="purchaseDialog" @resetPurchaseDialog="resetPurchaseDialog"></purchase-verification>
     <!--鏌ョ湅宸ユ椂寮规-->
     <viewManHourDia ref="viewManHourDia" @submit="openAddVerifyDia"></viewManHourDia>
+    <button @click="sss">杩炴帴涓插彛</button>
   </div>
 </template>
 
@@ -536,7 +537,7 @@
 import AddUnPass from "../unpass/components/addUnPass.vue";
 import InspectionWord from "./components/InspectionWord.vue";
 import PurchaseVerification from "../unpass/components/PurchaseVerification.vue";
-import { connect,disconnect } from "@/utils/connect.js";
+
 
 import {
   doInsOrder,
@@ -561,6 +562,7 @@
 import DataWorker from '@/workers/DataWorker.worker.js';
 import html2canvas from "html2canvas";
 import { mapGetters } from "vuex";
+import { connect,disconnect,weightList } from "@/utils/connect.js";
 import viewManHourDia from "@/views/business/inspectionTask/components/viewManHourDia.vue";
 export default {
   name: 'Inspection',
@@ -599,6 +601,7 @@
         state: null,
       },
       isSerialConnected: false, // 鏂板鐘舵�佸彉閲忥紝涓插彛杩炴帴鐘舵��
+      serialPort: null, // 瀛樺偍涓插彛瀵硅薄
       id: null,
       changeType: null,
       insOrder: {},
@@ -901,9 +904,16 @@
   beforeDestroy() {
     // 鍦ㄧ粍浠堕攢姣佸墠纭繚鍋滄 Worker锛岄伩鍏嶅唴瀛樻硠婕�
     this.stopWorker();
-    disconnect()
+    disconnect();
+    // 璋冪敤鍓嶅厛鍒ゆ柇鏂规硶鏄惁瀛樺湪锛岄伩鍏嶆姤閿�
+    if (this.closeSerialPort) {
+      this.closeSerialPort();// 缁勪欢閿�姣佸墠鍏抽棴涓插彛
+    }
   },
   methods: {
+    sss() {
+      console.log(this.$store.state.weightList) // 
+    },
     // 鏂囦欢绠$悊--寮�濮�
     getList() {
       this.tableLoading = true;
@@ -939,14 +949,19 @@
       }).catch(() => { });
     },
     // 鏂囦欢绠$悊--缁撴潫
-  // 澶勭悊鏁寸粍鍕鹃�夐�昏緫鐨勬柟娉�
-    handleGroupSelect(childItem, clickedIndex) {
+    // 澶勭悊鏁寸粍鍕鹃�夐�昏緫鐨勬柟娉�
+    handleGroupSelect(childItem, clickedIndex, groupSize = 5) {
+      if(groupSize == 6){
+        groupSize = 6;
+      }else{
+        groupSize = 5;
+      }
       // 璁$畻鎵�鍦ㄧ粍鐨勮捣濮嬬储寮�
-      const groupStartIndex = Math.floor(clickedIndex / 5) * 5;
+      const groupStartIndex = Math.floor(clickedIndex / groupSize) * groupSize;
       // 娓呯┖褰撳墠宸查��
       childItem.getDataIndex1 = [];
-      // 閬嶅巻褰撳墠缁勭殑 5 涓厓绱狅紝娣诲姞鍒伴�変腑鍒楄〃
-      for (let i = groupStartIndex; i < groupStartIndex + 5 && i < childItem.arr.length; i++) {
+      // 閬嶅巻褰撳墠缁勭殑 groupSize 涓厓绱狅紝娣诲姞鍒伴�変腑鍒楄〃
+      for (let i = groupStartIndex; i < groupStartIndex + groupSize && i < childItem.arr.length; i++) {
         childItem.getDataIndex1.push(i + '^' + childItem.arr[i]);
       }
     },
@@ -1133,36 +1148,82 @@
     },
 
     // 鏁版嵁閲囬泦
-    getDataAcquisitionDevice() {
-      if (this.isSerialConnected) {
-        connect();
-      }
-      // return
-      let itemIds = [];
-      this.currentSample.insProduct.forEach((item) => {
-        if (item.inspectionItemType === "1") {
-          itemIds.push(item.id);
+
+  getDataAcquisitionDevice() {
+      (async () => {
+        try {
+          // 妫�鏌ユ槸鍚︽敮鎸� Web Serial API
+          if ('serial' in navigator) {
+            // 璇锋眰鍙敤涓插彛
+            const ports = await navigator.serial.getPorts();
+            if (ports.length > 0) {
+              await connect();
+            } else {
+              console.log('娌℃湁鍙敤鐨勪覆鍙�');
+            }
+          } else {
+            console.log('褰撳墠娴忚鍣ㄤ笉鏀寔 Web Serial API');
+          }
+        } catch (error) {
+          console.error('妫�娴嬩覆鍙f椂鍑洪敊:', error);
         }
-      });
-      const params = {
-        entrustCode: this.insOrder.entrustCode,
-        sampleCode: this.currentSample.sampleCode,
-        id: this.currentSample.id,
-        itemIds: itemIds,
-      };
-      this.dataAcquisitionLoading = true;
-      dataCollection(params).then((res) => {
-        this.dataAcquisitionLoading = false;
-        if (res.code != 200) {
-          return;
-        }
-        this.dataAcquisitionInfoNew = this.HaveJson(res.data);
-        // 瀵规暟閲囧洖鏉ョ殑鍊艰繘琛屽鐞�
-        this.handleDataAcquisition(res.data);
-      }).catch(err => {
-        this.dataAcquisitionLoading = false;
+      })().then(() => {
+        let itemIds = [];
+        this.currentSample.insProduct.forEach((item) => {
+          if (item.inspectionItemType === "1") {
+            itemIds.push(item.id);
+          }
+        });
+        const params = {
+          entrustCode: this.insOrder.entrustCode,
+          sampleCode: this.currentSample.sampleCode,
+          id: this.currentSample.id,
+          itemIds: itemIds,
+        };
+        this.dataAcquisitionLoading = true;
+        dataCollection(params).then((res) => {
+          this.dataAcquisitionLoading = false;
+          if (res.code != 200) {
+            return;
+          }
+          this.dataAcquisitionInfoNew = this.HaveJson(res.data);
+          // 瀵规暟閲囧洖鏉ョ殑鍊艰繘琛屽鐞�
+          this.handleDataAcquisition(res.data);
+        }).catch(err => {
+          this.dataAcquisitionLoading = false;
+        });
       });
     },
+    // getDataAcquisitionDevice() {
+    //   if (this.isSerialConnected) {
+    //     connect();
+    //   }
+    //   // return
+    //   let itemIds = [];
+    //   this.currentSample.insProduct.forEach((item) => {
+    //     if (item.inspectionItemType === "1") {
+    //       itemIds.push(item.id);
+    //     }
+    //   });
+    //   const params = {
+    //     entrustCode: this.insOrder.entrustCode,
+    //     sampleCode: this.currentSample.sampleCode,
+    //     id: this.currentSample.id,
+    //     itemIds: itemIds,
+    //   };
+    //   this.dataAcquisitionLoading = true;
+    //   dataCollection(params).then((res) => {
+    //     this.dataAcquisitionLoading = false;
+    //     if (res.code != 200) {
+    //       return;
+    //     }
+    //     this.dataAcquisitionInfoNew = this.HaveJson(res.data);
+    //     // 瀵规暟閲囧洖鏉ョ殑鍊艰繘琛屽鐞�
+    //     this.handleDataAcquisition(res.data);
+    //   }).catch(err => {
+    //     this.dataAcquisitionLoading = false;
+    //   });
+    // },
     // 鍋囪瀛樺湪涓�涓柟娉曠敤浜庢洿鏂颁覆鍙h繛鎺ョ姸鎬�
     // updateSerialConnectionStatus(status) {
     //   this.isSerialConnected = status;
@@ -1177,6 +1238,7 @@
       return newObj;
     },
     handleDataAcquisition(data, noDialog) {
+      console.log(data);
       // 鏄惁鍙互缂栬緫鏁伴噰鏁版嵁
       if (this.dataAcquisitionEidtAble) {
         this.getDataType = 1;
diff --git a/src/views/system/user/index.vue b/src/views/system/user/index.vue
index 0fb4722..5124927 100644
--- a/src/views/system/user/index.vue
+++ b/src/views/system/user/index.vue
@@ -63,7 +63,7 @@
                 <template slot-scope="scope">
                   <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:user:edit']">淇敼</el-button>
-                  <!--                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">鍒犻櫎</el-button>-->
+                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">鍒犻櫎</el-button>
                   <!--                  <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['system:user:resetPwd', 'system:user:edit']">-->
                   <!--                    <el-button size="mini" type="text" icon="el-icon-d-arrow-right">鏇村</el-button>-->
                   <!--                    <el-dropdown-menu slot="dropdown">-->

--
Gitblit v1.9.3