serialport串口通信
npm包serialport
/*
* @Descripttion:
* @Author: yizheng.yuan
* @Date: 2020-03-02 09:38:54
* @LastEditors: yizheng.yuan
* @LastEditTime: 2020-04-10 18:18:40
*/
// console.log('SerialPort:',SerialPort)
// if(SerialPort){
// SerialPort.close();
// }
var portName = 'COM2'; //定义串口名
var SerialPort = require('serialport');
// list()弃用回调形式了,已经采用promise返回了,所以这里要用promise接收数据
let rel = SerialPort.list();
let com,vid,pid;
// [ { path: 'COM5',
// manufacturer: 'Prolific',
// serialNumber: '5&79ce5a3&0&2',
// pnpId: 'USB\\VID_067B&PID_2303\\5&79CE5A3&0&2',
// locationId: 'Port_#0002.Hub_#0001',
// vendorId: '067B',
// productId: '2303' } ]
rel.then(
data=>{
console.log('成功,串口列表为data22:',data);
// for(let i=0;i<data.length;i++){
// if(data[i].vendorId=='067B'){
// com = data[i].path;
// vid = data[i].vendorId;
// pid = data[i].productId;
// }
// }
com = data[1].path;
vid = data[1].vendorId;
pid = data[1].productId;
console.log('###-get-:com,vid,pid:',com,vid,pid);
connectPort(com)
},
error=>{console.log('失败err:',error)}
)
function connectPort(com){
let spt = new SerialPort( //设置串口属性
com, {
baudRate: 115200, //波特率
dataBits: 8, //数据位
parity: 'none', //奇偶校验
stopBits: 1, //停止位
flowControl: false ,
autoOpen:false //不自动打开1
}, false);
spt.open(function(error){
if(error){
console.log("打开端口"+portName+"错误:"+error);
}else{
console.log("打开端口成功1,正在监听数据中");
spt.on('data',function(data){
console.log('1返回的11----接收串口数据data:',data.toString());
})
}
});
console.log('--尝试往串口发数据1--');
function callbackFun(){
console.log('write--success2')
}
function writeAndDrain (data,callback) {
console.log('write:',data)
spt.write(data, function () {
spt.drain(callback);
});
}
setInterval(()=>{
let data="abc\r\n"
let data1='{"msg":"method", "method":"system.get_channel", "params":[{"args": [], "kwargs": {}}], "id":"xxxxx", "devID":"xxxx" }\r\n';
writeAndDrain(data1,callbackFun)
},3000)
}
// var SerialPort = require('serialport');
// SerialPort.list(function (err, ports) {
// ports.forEach(function(port) {
// console.log(port.comName);
// console.log(port.pnpId);
// console.log(port.manufacturer);
// });
// });