package com.zy.acs.gateway.utils; 
 | 
  
 | 
import com.zy.acs.gateway.constant.PackagePart; 
 | 
import com.zy.acs.gateway.domain.AgvPackage; 
 | 
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(); 
 | 
    } 
 | 
  
 | 
} 
 |