#
whycq
2024-08-15 e54492fb532366faac8aa5d46ad8905ea3ff38d5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.example.agvcontroller.protocol;
 
import io.netty.buffer.ByteBuf;
 
/**
 * 校验工具类
 * Created by vincent on 2019-04-03
 */
public class ValidUtil {
 
    public static final Integer MAX_DEFAULT = 65531;
 
    /**
     * 校验消息中数值是否在对应允许的范围内
     * @param item  被校验数据值
     * @param min   允许的最小值
     * @param max   允许的最大值
     */
    public static boolean rangeValid(int item, int min, int max) {
        return !(item < min || item > max);
    }
 
    /**
     * 异或校验包完整
     *      从命令单元(第三个字节)开始,一次与后一个字节异或,直至倒数第二个字节。
     *      将异或的结果与报文中最后一个字节比较。
     *      -相等:报文完整
     *      -不相等:报文不完整
     */
    public static boolean validPac(AgvPackage pac) {
        ByteBuf buf = pac.getSourceBuff();
        return getValdByteInMsg(pac) == calculateValidByteFromBuff(buf);
    }
 
    /**
     * 从当前数据包计算校验码
     */
    public static int calculateValidByteFromBuff(ByteBuf buf) {
        buf.resetReaderIndex();
        byte[] bytes = new byte[buf.readableBytes() - PackagePart.VALIDE_CODE.getLen()];
        buf.readBytes(bytes);
        int currValidByte = CRCUtils.crc16(bytes);
        // 重置读指针
        buf.resetReaderIndex();
        return currValidByte;
    }
 
    /**
     * 获取当前数据包中的校验码(最后一位字节)
     */
    public static int getValdByteInMsg(AgvPackage pac) {
        return pac.getValidCode();
    }
 
}