package com.mes.util.ytnetty; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class YtUtil { public static final Logger log = LoggerFactory.getLogger(YtUtil.class); // 获取功能码 public static String getCode(String msg){ return msg.substring(0,4); } /** * 计算16进制字符串的BCC校验码 * @param hexData 16进制字符串 * @return BCC校验码 */ public static byte calculateBCC(String hexData) { byte bcc = 0; // 初始化BCC校验码为0 for (int i = 0; i < hexData.length(); i += 2) { // 每次处理两个字符(1个字节) String byteStr = hexData.substring(i, i + 2); // 获取当前16进制字节 int byteValue = Integer.parseInt(byteStr, 16); // 将16进制字符串转换为整数 bcc ^= byteValue; // 执行异或操作 } return bcc; // 返回计算后的BCC校验码 } public static String formatCommon(String msg){ String start = "02"; String end = "03"; String content = start+msg+end; String bcc = String.format("%02x",calculateBCC(content)); return content + bcc; } // 启动指令 public static String getStartCommon(){ return formatCommon("5354"); } // 停止/复位指令 public static String getStopCommon(){ return formatCommon("5254"); } // 锁机指令 public static String getLockCommon(){ return formatCommon("4C4D31"); } // 解锁指令 public static String getUnLockCommon(){ return formatCommon("4C4D30"); } // 选频指令 public static String getSelectProgramCommon(String programNo){ String no = String.format("%03d", Integer.parseInt(programNo)); return formatCommon("4348"+asciiToHex(no)); } // 读取当前通道 public static String getCurProgramCommon(){ return formatCommon("5250"); } // 读取实时 public static String getCurDataCommon(){ return formatCommon("5253"); } // 设备状态 public static String getStateCommon(){ return formatCommon("5453"); } // 传输结果 public static String getResultCommon(){ return formatCommon("4353"); } public static String asciiToHex(String input){ StringBuilder hexValues = new StringBuilder(); for (char c : input.toCharArray()) { int asciiValue = (int) c; // 获取ASCII值 String hexValue = Integer.toHexString(asciiValue); // 转换为16进制字符串 if (hexValues.length() > 0) { // 如果不是第一个字符,添加空格分隔 hexValues.append(""); } hexValues.append(hexValue); // 添加到StringBuilder中 } return hexValues.toString(); } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } /** * 将字符串消息转为ByteBuf * 16进制字符串转二进制 * @param hex 字符串消息 */ public static ByteBuf getSendByteBuf(String hex) { byte[] bytes = new byte[hex.length() / 2]; for (int i = 0; i < hex.length(); i += 2) { int value = Integer.parseInt(hex.substring(i, i + 2), 16); bytes[i/2] = (byte)(value & 0xFF); } return Unpooled.wrappedBuffer(bytes); } }