import { ElMessage } from 'element-plus'
|
const { SerialPort } = require('serialport')
|
const { DelimiterParser } = require('@serialport/parser-delimiter')
|
import {sockteStore} from '@/stores/sockteInfo'
|
|
|
let serialport={}
|
// 解析器分隔符
|
const buf=Buffer.from('A555','hex')
|
const hexString = 'A55501FB0D0A';
|
const hexBuffer = Buffer.from(hexString, 'hex');
|
|
const initPort=(path:String,baudRate:Number)=>{
|
console.log('初始化打开测温端口')
|
serialport = new SerialPort({ path, baudRate }, (err: any) => {
|
if (err) {
|
console.log(err)
|
ElMessage({
|
message: '端口打开失败!',
|
type: 'error',
|
})
|
console.log(err)
|
}else{
|
ElMessage({
|
message: '端口打开成功',
|
type: 'success',
|
})
|
setInterval(()=>{
|
serialport.write(hexBuffer,(err: any)=>{
|
if(err){
|
console.log('发送失败')
|
}
|
})
|
},3000)
|
}
|
})
|
serialport.on("close",(err: any)=>{
|
console.log('端口异常端口链接断开')
|
console.log(err)
|
})
|
// 解析分割数据流
|
const parser = serialport.pipe(new DelimiterParser({
|
delimiter:buf
|
}))
|
parser.on('data', (value: string | any[])=>{
|
if(value.length>=5){
|
const hex4e=value[0]
|
const hex0e=value[1]
|
const wendu=(hex4e+hex0e*256)/100
|
if(wendu>20){
|
sockteStore().setWendu(wendu)
|
console.log('解析到的温度'+wendu)
|
// ElMessage({
|
// message: '收到温度:'+wendu,
|
// type: 'success',
|
// })
|
}else{
|
console.log('读取温度异常'+wendu)
|
}
|
|
}
|
})
|
}
|
const sundGetKey=()=>{
|
const hexString = 'A55501FB';
|
const hexBuffer = Buffer.from(hexString, 'hex');
|
if(serialport){
|
console.log('串口没有初始化')
|
return false
|
}
|
serialport.write(hexBuffer,(err: any)=>{
|
if(err){
|
console.log('发送失败')
|
}
|
ElMessage({
|
message: '发送KEY成功',
|
type: 'success',
|
})
|
})
|
}
|
|
|
|
export {
|
initPort,
|
sundGetKey
|
}
|