yaowanxin
2 天以前 0a144cc1dd664851638a6a01d030dd6a1585c25a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// 新增:存储全局串口和读取器实例
    let port = null;
    let reader = null;
    let accumulatedData = ""; // 移到全局,便于关闭时重置
 
    async function connect() {
      if ("serial" in navigator) {
        try {
          port = await navigator.serial.requestPort(); // 修改为全局变量
          await port.open({ baudRate: 9600 });
 
          reader = port.readable.getReader(); // 修改为全局变量
          const decoder = new TextDecoder();
          accumulatedData = ""; // 重置累积数据
 
          console.log("串口连接成功,开始接收数据...");
 
          while (true) {
            const { value, done } = await reader.read();
            if (done) break;
 
            const decodedChunk = decoder.decode(value, { stream: true });
            accumulatedData += decodedChunk;
            console.log("接收到数据块:", decodedChunk);
 
            processAccumulatedData(accumulatedData);
          }
        } 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);
          }
 
          accumulatedData = messages[messages.length - 1];
        }
 
        // 其他消息拆分示例保持不变
        /*
  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;
  }
  */
      }
    }
 
    // 新增:关闭连接函数
    async function disconnect() {
      if (!port || !reader) {
        console.log("未建立连接,无需关闭");
        return;
      }
 
      try {
        // 先取消读取器
        await reader.cancel();
        // 再关闭串口
        await port.close();
        console.log("串口连接已关闭");
 
        // 重置全局变量
        port = null;
        reader = null;
        accumulatedData = "";
      } catch (error) {
        console.error("关闭连接失败:", error);
      }
    }
 
    export { connect, disconnect };