<template>
<div id="wrapper">
<div>
<span>串口信息查询</span>
<div
v-for="(item,index) in serialportLists"
:key="index"
>
<table border="1">
<tr>
<th>path</th>
<th>pnpId</th>
<th>friendlyName</th>
<th>locationId</th>
<th>manufacturer</th>
</tr>
<tr>
<td>{{item.path}}</td>
<td>{{item.pnpId}}</td>
<td>{{item.friendlyName}}</td>
<td>{{item.locationId}}</td>
<td>{{item.manufacturer}}</td>
</tr>
</table>
</div>
</div>
<div>
<button @click="openPort">打开串口</button>
<button @click="closePort">关闭串口</button>
<button @click="writeport">写入数据</button>
<button @click="back()">返回首页</button>
</div>
</div>
</template>
<script>
const { SerialPort } = require('serialport')
export default {
data() {
return {
serialportLists: [],
openSerialport: null,
comNum: '',
isOpen: false,
writeData: "88AE0011",
}
},
methods: {
back() {
this.$router.push({ path: '/' })
},
openPort() {
console.log("打开串口")
if (this.comNum === "") {
console.log("串口未找到!")
} else {
console.log("串口找到了!")
}
console.log(this.comNum)
// new一个串口对象
this.openSerialport = new SerialPort({ path: this.comNum, baudRate: 9600, autoOpen: false }, (err) => {
console.log("/`&#@/")
console.log(this.openSerialport)
if (err) {
return console.log(err.message, "代替红色的错误信息");
}
})
//打开串口
this.openSerialport.open(function (error) {
console.log(error)
if (error) {
console.log('打开虚拟串口失败' + error)
} else {
console.log('打开虚拟串口成功')
}
})
//监听数据
this.openSerialport.setEncoding("hex");
this.openSerialport.on("data", data => {
console.log(data)
if (data == '') {
console.log("数据为空")
}
})
},
//写入数据
writeport() {
this.hexData = "";
this.openSerialport.write(this.writeData, "hex", function (err, a) {
if (err) {
console.log(err);
return console.log("Error on write: ", err.message);
} else {
console.log("写入数据成功")
}
});
},
// 关闭串口
closePort() {
this.openSerialport.close((err) => {
console.log(err);
if (!err) {
console.log("串口关闭成功!");
} else {
console.log("串口已经关闭!");
}
});
}
},
mounted() {
SerialPort.list().then(
ports => {
this.serialportLists = ports
this.comNum = ports[3].path
console.log(this.comNum)
console.log(ports)
console.log(this.serialportLists)
}
)
},
}
</script>
<style scoped>
body {
background-color: aliceblue;
}
button {
height: 30px;
width: 150px;
}
#wrapper {
display: block;
}
</style>
注意点
1、在new SerialPort构造方法时,要注意传参里面的path的书写格式({path:'/dev/com4'})或者({path:this.comnum}); (因为网上有大部分资料在这里有误导)