yaowanxin
11 小时以前 cb2a01ee7dea28a2661720060b03c41dc372acb5
完善串口处理数据,数据选择
已修改3个文件
235 ■■■■ 文件已修改
src/utils/connect.js 99 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/views/business/inspectionTask/inspection.vue 134 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/views/system/user/index.vue 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
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 };
    export { connect, disconnect,weightList };
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('检测串口时出错:', 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;
    //   });
    // },
    // 假设存在一个方法用于更新串口连接状态
    // updateSerialConnectionStatus(status) {
    //   this.isSerialConnected = status;
@@ -1177,6 +1238,7 @@
      return newObj;
    },
    handleDataAcquisition(data, noDialog) {
      console.log(data);
      // 是否可以编辑数采数据
      if (this.dataAcquisitionEidtAble) {
        this.getDataType = 1;
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">-->