You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
3.1 KiB

8 months ago
'use strict';
const Service = require('egg').Service;
const _ = require("lodash");
class DealSerialportService extends Service {
//打开串口
async openSerialport(SerialPortItem, port) {
if (SerialPortItem.isOpen) {
await this.closeSerialport(SerialPortItem, port)
}
let returnData = {
haserror: true,
msg: `${port}串口打开出错`,
};
await SerialPortItem.open(function (error) {
if (error) {
returnData.haserror = true
returnData.msg = `${port}端口打开出错:${error}`
} else {
returnData.haserror = false
returnData.msg = `${port}端口打开成功`
}
return returnData
});
return returnData
}
//关闭串口
async closeSerialport(SerialPortItem, port) {
if (SerialPortItem.isOpen) {
await SerialPortItem.close()
}
let returnData = {
haserror: false,
msg: `${port}串口关闭成功`,
};
return returnData
}
//向串口发送指令
async writeSerialport(SerialPortItem, params) {
let { ctx } = this
//每次发送数据停留50ms
await ctx.service.utils.sleep(50);
let returnData = {
haserror: false,
msg: `${params.ripCom}的指令(${JSON.stringify(params.sendRipId)})发送成功`,
};
if (SerialPortItem.isOpen) {
await this.writeData(SerialPortItem, params)
} else {
await this.openSerialport(SerialPortItem, params.ripCom)
await this.writeData(SerialPortItem, params)
}
return returnData
}
//写数据后读取
async writeData(SerialPortItem, params) {
let { ctx } = this
let dealData1 = ""
let dealData2 = ""
if (typeof (params.sendRipId) === "string") {
dealData1 = await ctx.service.utils.MODBUS_CRC(params.sendRipId, true, "hex");
} else if (typeof (params.sendRipId) === "object") {
dealData1 = await ctx.service.utils.MODBUS_CRC(params.sendRipId[0], true, "hex");
// dealData2 = await ctx.service.utils.MODBUS_CRC(params.sendRipId[1], true, "hex");
}
await SerialPortItem.write(Buffer.from(dealData1)); // 发送字符串
await ctx.service.utils.sleep(50);
let readResult1 = await SerialPortItem.read(); // 发送字符串
if (dealData1 && readResult1) {
if (dealData1.toString("hex").substring(0, 4) === readResult1.toString("hex").substring(0, 4) && dealData1.toString("hex") !== readResult1.toString("hex")) {
await ctx.service.home.sendData(params, readResult1, params.isDirct);
}
}
if (dealData2) {
await ctx.service.utils.sleep(50);
await SerialPortItem.write(Buffer.from(dealData2)); // 发送字符串
await ctx.service.utils.sleep(50);
let readResult2 = await SerialPortItem.read(); // 发送字符串
if (dealData2 && readResult2) {
if (dealData2.toString("hex").substring(0, 4) === readResult2.toString("hex").substring(0, 4) && dealData2.toString("hex") !== readResult2.toString("hex")) {
await ctx.service.home.sendData(params, readResult2, params.isDirct);
}
}
}
}
}
module.exports = DealSerialportService;