基于Java实现使用Socket进行通讯的Modbus协议框架
01.讲在前面
因为个人项目需要,所以就开发了这么一个框架,只有后续还会不会更新就是看心情,废话讲完就来讲讲使用到的一些技术,首先编程语言方面选择的是Java 然后和底层设备通讯使用的是Socket这是Java自带的,然后使用的协议是Modbus RTU,虽然使用的是Modbus RTU但是通讯走的是TCP(有转换模块)
02.介绍框架
由于没有上传到maven所有还是需要lib的方式来进行导包,导包后又两种使用方式
01.只生成报文,不进行发送
02.生成报文的同时进行发送报文
这两种最大的区别就是一个需要设置socket连接对象,一个不需要。
项目地址:
https://github.com/codeXYW/MSocket
https://github.com/codeXYW/MSocket/releases/
03.代码演示
仅报文生成
01.读单个线圈
public static void readCoils() throws IOException, ModbusException {
String s = ReadCoilsRegisters.readCoils(1, 0, 1);
System.out.println(s);
}
02.读离散输入寄存器
public static void readDiscreteInput() throws IOException, ModbusException {
String s = ReadDiscreteInputRegisters.readDiscreteInput(1, 0, 2);
System.out.println(s);
}
03.读取输入型寄存器
public static void readInput() throws ModbusException, IOException {
String s = ReadInputRegisters.readInput(1, 0, 3, DataType.FLOAT);
System.out.println(s);
}
04.读取保持型寄存器
public static void readHolding() throws ModbusException, IOException {
String s = ReadHoldingRegisters.readHolding(1,0,3,DataType.FLOAT);
System.out.println(s);
}
05.写单个线圈
public static void writeCoil() throws IOException, ModbusException {
String s = WriteCoilRegisters.writeCoil(1, 0, true);
System.out.println(s);
}
06.写单个寄存器
public static void writeRegister() throws IOException, ModbusException {
String s = WriteRegister.writeRegister(1, 0, 2, DataType.INTEGER);
System.out.println(s);
}
07.写多个线圈
public static void writeCoils() throws Exception {
String s = WriteCoilsRegisters.writeCoils(1, 1, new boolean[]{true, true, true, true, true, true, true, true, true});
System.out.println(s);
}
08.写多寄存器
public static void writeRegistersFloat() throws IOException, ModbusException {
String s = WriteRegisters.writeRegisters(1, 0, new float[]{1, 12, 5}, DataType.FLOAT);
System.out.println(s);
}
public static void writeRegistersInt() throws IOException, ModbusException {
String s = WriteRegisters.writeRegisters(1, 0, new int[]{1, 12, 5}, DataType.INTEGER);
System.out.println(s);
}
生成报文并发送(解析)
框架文档有
https://github.com/codeXYW/MSocket