package com.yfd.platform.component.iec104.server.handler;

import com.yfd.platform.component.iec104.common.Iec104Constant;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannel;
import com.yfd.platform.component.iec104.server.master.BootNettyClientChannelCache;
import com.ydl.iec.util.ByteUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
* @ClassName: Check104Handler
* @Description: 检查104报文
* @author YDL
* @date 2020年5月13日
 */
public class Check104Handler extends ChannelInboundHandlerAdapter {
	private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);
	private static final int MAX_BUFFER_SIZE = 1024; // 缓存区大小

	/**
	 * 拦截系统消息
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf result = (ByteBuf) msg;
		// 检查ByteBuf中的数据长度是否超过最大缓冲区大小
		if (result.readableBytes() > MAX_BUFFER_SIZE) {
			LOGGER.error("接收的数据长度是否超过最大缓冲区大小!");
			return;
		}

		byte[] bytes = new byte[result.readableBytes()];
		result.readBytes(bytes);
		BootNettyClientChannel Channel= BootNettyClientChannelCache.get(ctx.channel().id().asShortText());
		String slave_ip= Channel.getCode();
		LOGGER.info( String.format("接收到从站[%s]发送的报文: %s", slave_ip,ByteUtil.byteArrayToHexString(bytes) ));
		if (bytes.length < Iec104Constant.APCI_LENGTH || bytes[0] != Iec104Constant.HEAD_DATA) {
			LOGGER.error("报文无效");
			ReferenceCountUtil.release(result);
		} else {
			result.writeBytes(bytes);
			ctx.fireChannelRead(msg);
		}
	}
}
