update 电单车协议

This commit is contained in:
Guoqs
2024-08-06 13:58:14 +08:00
parent e3dd0a7944
commit b87efcda57

View File

@@ -41,6 +41,7 @@ public class ChargingPileMessage {
// 从字节数组解析消息
public static ChargingPileMessage parseMessage(byte[] messageBytes) {
boolean b = validateChecksum(messageBytes);
ChargingPileMessage message = new ChargingPileMessage();
// log.info("parseMessage:{}", BytesUtil.binary(messageBytes, 16));
// 读取包头
@@ -86,4 +87,31 @@ public class ChargingPileMessage {
log.info("报文:{}, parseMessage:{}", BytesUtil.binary(messageBytes, 16), message.toString());
return message;
}
/**
* 校验方法
* 整个数据包中的每个字节不包括校验字段本身将它们的数值累加起来。然后取累加和的低2字节16位作为校验字段的值
*/
public static boolean validateChecksum(byte[] bytes) {
if (bytes.length < 2) {
return false; // 校验字段长度不足时返回 false
}
// 计算累加和
int sum = 0;
for (int i = 0; i < bytes.length - 2; i++) {
sum += (bytes[i] & 0xFF); // 将每个字节视为无符号值进行累加
}
// 取累加和的低 2 字节16 位)
int calculatedChecksum = sum & 0xFFFF;
// 读取校验字段的值
byte[] checksumBytes = {bytes[bytes.length - 2], bytes[bytes.length - 1]};
int receivedChecksum = BytesUtil.bytesToIntLittle(checksumBytes);
// 比较计算的校验值和接收到的校验值
log.info("计算的校验值:{}, 接收到的校验值:{}", calculatedChecksum, receivedChecksum);
return calculatedChecksum == receivedChecksum;
}
}