package com.tmzn.devicelinkykc.frameMsg; import com.tmzn.devicelinkykc.msgEnum.DeviceSendYkc; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; /** * @author xp * @date 2024/3/13 * @explain " 帧数据拼接 " */ public class FrameDataSplicing { /** * * @param seq 序列号 * @param frameType 帧类型 * @param encryptFlag 加密标志 * @param data 消息体 * @param length 长度 * @return */ public static byte[] spliceing(int seq, int frameType, int encryptFlag, byte[] data, int length) { byte[] outBuf = new byte[8 + data.length]; int index = 0; outBuf[index++] = (byte) 0x68; //其实字节 outBuf[index++] = (byte) (length + 4); //字节长度 int seqTemp = seq; outBuf[index++] = (byte) ((seqTemp >> 8) & 0x00FF); outBuf[index++] = (byte) (seqTemp & 0x00FF); outBuf[index++] = (byte) encryptFlag; outBuf[index++] = (byte) frameType; System.arraycopy(data, 0, outBuf, index, length); index += length; int crc = modbusCRC(Arrays.copyOfRange(outBuf, 2, index), index - 2); int crc16 = modbus16CRC(Arrays.copyOfRange(outBuf, 2, index), index - 2); outBuf[index++] = (byte) (crc & 0x00FF); outBuf[index++] = (byte) ((crc >> 8) & 0x00FF); System.out.println("发送消息>>>"+ DeviceSendYkc.getNameByframeType(frameType)+">>>>>>>>>>"+DataConversion.bytesToHexString(outBuf)); return outBuf; } /** * CRC 计算函数 */ private static int modbusCRC(byte[] pData, int len) { int crc = 0xFFFF; for (int i = 0; i < len; i++) { crc = (crc ^ pData[i]) & 0xFF; for (int j = 0; j < 8; j++) { if ((crc & 0x0001) != 0) { crc = ((crc >> 1) ^ 0xA001) & 0xFFFF; } else { crc >>= 1; } } } return crc; } /** * CRC 计算函数 */ private static int modbus16CRC(byte[] pData, int len) { int crc = 0xFFFF; for (int i = 0; i < len; i++) { crc ^= pData[i] & 0xFF; for (int j = 0; j < 8; j++) { if ((crc & 0x0001) != 0) { crc >>= 1; crc ^= 0xA001; } else { crc >>= 1; } } } return crc; } /** * 流水号生成 */ public static byte[] transactionNum(String pilecode,int msgCount){ int index = 0; byte[] transaction = new byte[16]; //1.交易流水,自己生成上报状态 // byte[] pileCodebytes = DataConversion.bcdToBytes(pilecode, 7); // Date date = new Date(); // SimpleDateFormat yy = new SimpleDateFormat("yy-MM-dd-HH-mm-ss"); // String format = yy.format(date); // System.out.println(format); // String[] split = format.split("-"); // byte[] time1 = new byte[6]; // time1[0] = 20; // for (int i = 1; i < split.length; i++) { // time1[i] = Byte.parseByte(split[i - 1]); // } // // System.arraycopy(pileCodebytes, 0, transaction, 0, pileCodebytes.length); // System.arraycopy(time1, 0, transaction, 7, time1.length); // transaction[14] = (byte) ((msgCount >> 8) & 0xFF);//自增 // transaction[15] = (byte) (msgCount & 0xFF); return transaction; } }