package com.cisdi.data.AMETEKSurfaceVision.gateway;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;

/**
 * 表检仪协议帧解码
 *
 * @author tzz
 */
public class SurfaceVisionFrameDecoder extends ByteToMessageDecoder {
    /** 结束符除|第一位，$的16进制 */
    private byte end = 0x24;
    /** 结束符除|第二位，\r的16进制 */
    private byte end1 = 0x0D;
    /** 结束符除|第三位，\n的16进制 */
    private byte end2 = 0x0A;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf bufferIn, List<Object> out) throws Exception {
        if (bufferIn.readableBytes() < 1){
            return;
        }
        final int beginIndex = bufferIn.readerIndex();

        int length = 0;
        for (int i = 0; i + 2 < bufferIn.readableBytes(); i += 1) {
            byte curByte = bufferIn.getByte(beginIndex + i);

            //判断是否为结束符，若为结束符读取从beginIndex开始的所有数据
            if (curByte == end){
                if (end1 == bufferIn.getByte(beginIndex + i + 1) &&
                end2 == bufferIn.getByte(beginIndex + i + 2)){
                    length = i + 3;
                    byte[] bytes = new byte[i+3];
                    bufferIn.readBytes(bytes);

                    ByteBuf copiedBuff = Unpooled.copiedBuffer(bytes);
                    out.add(copiedBuff);
                    break;
                }
            }

            if (i + 3 == bufferIn.readableBytes()){
                return;
            }
        }
        //若未结束，重置读索引
        bufferIn.readerIndex(beginIndex + length);

        //解决可能得粘包和拆包问题
        decode(ctx, bufferIn, out);
        return;
    }

}
