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();
|