Angular使用ngx-serial读取串口消息后发指令报错求助
问题描述
在Angular项目中使用ngx-serial库时,读取串口返回结果后尝试向串口发送数据,出现报错。
相关代码如下:
dataHandler(data: string) { console.log("From serial port -> " + data); this.myResult = data.replace(/\r/g, '');; console.log('myResult: ', this.myResult); this.readMyStream(this.myResult); } readMyStream(data: string) { setTimeout(() => { const words = data.split(' '); if (words[0] === '**' && words[3] === '****') { this.serial.sendData(`*** ** ****\n`); console.log('hhihih'); // Alternatively, display message in template } }, 9000) }
解决建议
- 检查串口连接状态:调用
sendData前先确认串口是否处于打开状态,避免因连接断开导致报错:if (this.serial.isOpen) { this.serial.sendData(`*** ** ****\n`); } else { console.error('串口未打开,无法发送数据'); } - 移除不必要的延迟:9秒的
setTimeout毫无必要,延迟期间串口可能意外断开,直接处理返回数据即可:readMyStream(data: string) { const words = data.split(' '); if (words.length >= 4 && words[0] === '**' && words[3] === '****') { if (this.serial.isOpen) { this.serial.sendData(`*** ** ****\n`); console.log('hhihih'); } } } - 处理数据格式异常:增加数组长度判断,防止因返回数据格式不符合预期导致数组越界报错:
if (words.length >= 4 && words[0] === '**' && words[3] === '****') { // 执行发送逻辑 } - 验证发送数据格式:确认
sendData的参数格式是否符合设备要求,部分串口设备需要\r\n作为换行符,而非单独的\n。
内容的提问来源于stack exchange,提问作者Katerina Maria Gerakianaki
相关产品推荐
相关产品推荐

