cy-plugin-modbus
v1.1.4
Published
modbus 插件
Readme
cy-plugin-modbus
封装浏览器端 modbus 模块
📦 安装
npm install cy-plugin-modbus🦄 使用
import { CySerialPort, Queue } from 'cy-plugin-modbus';
import type {
IReadDateFormat,
IWriteDateFormat,
ICySerialPortSendDataFormat
} from 'cy-plugin-modbus';
//初始化初始化串口对象
const port = new CySerialPort({
// 开启调试
debug: true,
// 连接
onConnect: () => {},
// 失败
onFail: () => {}
});
//初始化队列
const queue = new Queue({
debug: true,
onSuccess: (result, extraData) => {
console.log('每次任务成功都调用', result, extraData);
},
onError: (error, extraData) => {
console.log('每次任务失败都调用', error, extraData);
}
});
// 连接(完整参数示例)
await port.connect({
baudRate: 9600, // 波特率
parity: 'none', // 校验位: 'none' | 'even' | 'odd'
dataBits: 8, // 数据位: 7 或 8
stopBits: 1, // 停止位: 1 或 2
bufferSize: 255, // 读写缓冲区大小 (必须小于 16MB)
flowControl: 'none' // 流量控制: 'none' | 'hardware' | 'software'
});
// 断开连接
await port.disconnect();
// 直接发送消息示例
const readResult = await port.send({
slave: 1, // 设备地址
function_code: EnumModbusOptionType.ReadHoldingRegisters, // 操作类型
starting_address: 0, // 起始地址
quantity_of_x: 10, // 寄存器个数
output_value: [] // 写入数据
});
//队列发送消息
queue.push({
taskParams: data, // data 为 modbus 请求参数格式
task: async (param) => {
return await serialPort.send(param);
// try {
// return await port.send(param);
// } catch (error) {
//这里拦截 send 异常 抛出的错误
// console.log('error', error);
// return Promise.reject(error);
//}
},
retryCount: 1, // 重试次数 retryCount - 1
extraData: { msg: '额外参数' },
onSuccess: (res, extra) => {
console.log('✅ taskOnSuccess', JSON.stringify({ res, extra }, null, 2));
},
onError: (error, extra) => {
console.log('❌ taskOnError', JSON.stringify({ error, extra }, null, 2));
}
});
// =========================================
// 读取示例(参数格式 IReadDateFormat)
// 生成对应操作的数据结构(生成后使用 send 方法发送数据)
// =========================================
// 读线圈
serialPort.readCoilsFormat({});
// 读离散输入
serialPort.readDiscreteInputsFormat({});
// 读保持寄存器
serialPort.readHoldingRegistersFormat({});
// 读输入寄存器
serialPort.readInputRegistersFormat({});
// =======================================
// 写入示例(参数格式 IWriteDateFormat
// 生成对应操作的数据结构(生成后使用 send 方法发送数据)
// =======================================
// 写单个线圈
serialPort.writeSingleCoilFormat({});
// 写单个保持寄存器
serialPort.writeSingleRegisterFormat({});
// 写多个线圈
serialPort.writeMultipleCoilsFormat({});
// 写多个保持寄存器
serialPort.writeMultipleRegistersFormat({});