package com.persagy.socket;

import java.util.concurrent.TimeUnit;

import com.persagy.cameractl.conf.AllStaticConfig;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @version 1.0.0
 * @company persagy 
 * @author zhangqiankun
 * @date 2021年10月12日 上午10:20:11
 */
@Slf4j
public class IotClientHandler extends SimpleChannelInboundHandler<String> {

	/**
     * 向服务端发送数据
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	log.info("Connected to: {}", ctx.channel().remoteAddress());
    }

    /**
     * 接收数据
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("客户端接收到的服务端信息:" + msg);
    }
	
    /**
     * channel 通道 Inactive 不活跃的
     *
     * 当客户端主动断开服务端的链接后，这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端与服务端通道关闭：" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    	log.info("channelUnregistered and reconnecting to: {}:{} ", AllStaticConfig.toupIp, AllStaticConfig.toupPort);
        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                IotSocketClient.reConnect();
            }
        }, 5, TimeUnit.SECONDS);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    	log.warn("通道异常退出", cause);
        ctx.close();
    }
    
}