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.
67 lines
2.8 KiB
67 lines
2.8 KiB
package com.mh.common.utils; |
|
|
|
import io.netty.buffer.ByteBuf; |
|
import io.netty.buffer.Unpooled; |
|
import io.netty.channel.ChannelHandlerContext; |
|
import lombok.extern.slf4j.Slf4j; |
|
|
|
/** |
|
* @author LJF |
|
* @version 1.0 |
|
* @project EEMCS |
|
* @description Modbus协议工具类 |
|
* @date 2025-06-06 14:40:24 |
|
*/ |
|
@Slf4j |
|
public class ModbusUtils { |
|
|
|
public static String createReadOrder(String mtCode, String funCode, String registerAddr, String registerNum) { |
|
// 开始创建指令 |
|
// 拼接指令 |
|
String sendOrderStr = ExchangeStringUtil.addZeroForNum(mtCode, 2) |
|
+ ExchangeStringUtil.addZeroForNum(funCode, 2) |
|
+ ExchangeStringUtil.addZeroForNum(registerAddr, 4) |
|
+ ExchangeStringUtil.addZeroForNum(registerNum, 4); |
|
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(sendOrderStr); |
|
int checkNum = CRC16.CRC16_MODBUS(strOrder); |
|
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum)); |
|
checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2); |
|
sendOrderStr = sendOrderStr + checkWord; |
|
return sendOrderStr; |
|
} |
|
|
|
public static String createControlCode(String mtCode, Integer type, String registerAddr, String param) { |
|
String orderStr; |
|
mtCode = ExchangeStringUtil.addZeroForNum(mtCode, 2); |
|
registerAddr = ExchangeStringUtil.addZeroForNum(registerAddr, 4); |
|
param = ExchangeStringUtil.addZeroForNum(ExchangeStringUtil.decToHex(param), 4); |
|
orderStr = mtCode + "06" + registerAddr + param; |
|
byte[] strOrder = ExchangeStringUtil.hexStrToBinaryStr(orderStr); |
|
int checkNum = CRC16.CRC16_MODBUS(strOrder); |
|
String checkWord = ExchangeStringUtil.decToHex(String.valueOf(checkNum)); |
|
checkWord = checkWord.substring(2, 4) + checkWord.substring(0, 2); |
|
// 发送的指令 |
|
log.info("发送指令:{}", orderStr+checkWord); |
|
return orderStr + checkWord; |
|
} |
|
|
|
public static ByteBuf getByteBuf(ChannelHandlerContext ctx, String sendStr) { |
|
// byte类型的数据 |
|
// String sendStr = "5803004900021914"; // 冷量计 |
|
// 申请一个数据结构存储信息 |
|
ByteBuf buffer = ctx.alloc().buffer(); |
|
// 将信息放入数据结构中 |
|
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制 |
|
return buffer; |
|
} |
|
|
|
public static ByteBuf createByteBuf(String sendStr) { |
|
// byte类型的数据 |
|
// String sendStr = "5803004900021914"; // 冷量计 |
|
// 申请一个数据结构存储信息 |
|
ByteBuf buffer = Unpooled.buffer(); |
|
// 将信息放入数据结构中 |
|
buffer.writeBytes(ExchangeStringUtil.hexStrToBinaryStr(sendStr));//对接需要16进制 |
|
return buffer; |
|
} |
|
}
|
|
|