所以我有一个代码可以创建一个udp数据包发送到网关设备。数据包的标头是根据以下规范创建的:
以下是创建它的Java代码:
private static final int CRC_SIZE = 2;
private static final int HEADER_SIZE = 9;
private static final int GW_ADR_POS = 0;
private static final int GW_ADR_VALUE = 0x22;
private static final int CMD_POS = 1;
private static final int CMD_WRITE_VALUE = 0x03;
private static final int SUBCMD_POS = 2;
private static final int SUBCMD_WRITE_VALUE = 0;
private static final int DLEN_H_POS = 7;
private static final int DLEN_L_POS = 8;
public static short[] transformRequestData(short[] data) {
checkRequest(data);
short[] transformedData = new short[HEADER_SIZE + data.length + CRC_SIZE];
transformedData[GW_ADR_POS] = GW_ADR_VALUE;
transformedData[CMD_POS] = CMD_WRITE_VALUE;
transformedData[SUBCMD_POS] = SUBCMD_WRITE_VALUE;
System.arraycopy(data, 0, transformedData, HEADER_SIZE, data.length);
transformedData[DLEN_H_POS] = (short)((data.length & 0xFF00) >> 8);
transformedData[DLEN_L_POS] = (short)(data.length & 0xFF);
int crc = calculateCRC_microrisc(transformedData, 0, HEADER_SIZE + data.length);
transformedData[HEADER_SIZE + data.length] = (short)((crc & 0xFF00) >> 8);
transformedData[HEADER_SIZE + data.length+1] = (short)(crc & 0xFF);
return transformedData;
}
所以基本上发生的事情是函数transformRequestData采用HEX字符串数据并为HEADER信息加前缀并为CRC加后缀。
我的问题是如何在此代码中设置PACID_H和PACID_L。当我读取UDP输出时,RES RES PACID_H PACID_L都是0x00。为了让我的网关正确读取数据包,PACID_H和PACID_L应该设置不是0x00的值。 我相信它与以下代码有关:
System.arraycopy(data, 0, transformedData, HEADER_SIZE, data.length);
transformedData[DLEN_H_POS] = (short)((data.length & 0xFF00) >> 8);
在某些位移位上,RES RES PACID_H PACID_L全部为零,然后继续添加其余数据。 我试图理解按位移位操作正在做什么,但我没有掌握它。 如何更改此代码以便使用随机HEX值设置PACID_H和PACID_L? (虽然保留RES原样)?