gx
chenyc
2025-12-10 1daaf55ceac01b00be25aecc7efb57cf47a34155
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
const SerialPort = require('serialport');
const { Readline } = require('@serialport/parser-readline'); // 可选:按行解析
 
// 配置你的串口(根据实际情况修改)
const PORT_NAME = 'COM5'; // Windows 示例,Linux/macOS 如 '/dev/ttyUSB0' 或 '/dev/ttyS0'
const BAUD_RATE = 9600;
 
// 要发送的指令(十六进制字符串数组)
const commands = [
  '16 2f 40 31 04 03',
  '16 31 3f 48 44 04 03',
  '16 31 3f 43 44 04 03'
];
 
// 将十六进制字符串转为 Buffer
function hexStringToBuffer(hexStr) {
  const hex = hexStr.replace(/\s+/g, '');
  const bytes = [];
  for (let i = 0; i < hex.length; i += 2) {
    bytes.push(parseInt(hex.substr(i, 2), 16));
  }
  return Buffer.from(bytes);
}
 
// 延迟函数
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
 
async function main() {
  try {
    console.log(`正在打开串口 ${PORT_NAME}...`);
    const port = new SerialPort({
      path: PORT_NAME,
      baudRate: BAUD_RATE,
      autoOpen: false
    });
 
    // 打开串口
    await new Promise((resolve, reject) => {
      port.open(err => {
        if (err) return reject(err);
        console.log('✅ 串口已打开');
        resolve();
      });
    });
 
    // 监听数据回传
    port.on('data', (data) => {
      console.log(`📥 收到回传 (${new Date().toISOString()}):`, data.toString('hex').match(/.{1,2}/g).join(' '));
      // 如果你想看原始字节或 ASCII,也可以打印 data.toString()
    });
 
    // 依次发送命令
    for (let i = 0; i < commands.length; i++) {
      const cmd = commands[i];
      const buffer = hexStringToBuffer(cmd);
      console.log(`📤 发送指令 ${i + 1}: ${cmd}`);
      port.write(buffer);
 
      // 等待 5 秒再发下一条
      await delay(5000);
    }
 
    console.log('✅ 所有指令已发送完毕');
 
    // 可选:5秒后关闭串口
    await delay(5000);
    port.close();
    console.log('🔌 串口已关闭');
 
  } catch (err) {
    console.error('❌ 错误:', err.message);
    process.exit(1);
  }
}
 
// 列出可用串口(调试用)
SerialPort.list().then(ports => {
  console.log('可用串口:');
  ports.forEach(p => console.log('-', p.path, p.manufacturer || ''));
});
 
// 启动主程序
main();