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


import com.yfd.platform.component.iec104.config.Iec104Config;
import com.yfd.platform.component.iec104.server.Iec104Master;
import com.yfd.platform.component.iec104.server.handler.DataHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
 *
 * @ClassName:  Iec104TcpClientMaster
 * @Description: 104 TCP 客户端 主机
 * @author: YDL
 * @date:   2020年5月19日 上午10:44:35
 */
public class Iec104TcpClientMaster implements Iec104Master {
	private static final Logger LOGGER = LoggerFactory.getLogger(ChannelInboundHandlerAdapter.class);

	private int port;
	private String host;
	private DataHandler dataHandler;
	private Iec104Config iec104Config;
	private  EventLoopGroup group;

	public Iec104TcpClientMaster(String host, int port) {
		this.port = port;
		this.host = host;
		this.group = EventLoopGroupManager.createEventLoopGroup(host);
	}

	@Override
	public void run() throws Exception {
		try {
			Bootstrap bs = new Bootstrap();
			bs.group(group)
					.channel(NioSocketChannel.class)
					.option(ChannelOption.SO_KEEPALIVE, true)
					.handler(new Iec104ClientInitializer().setDataHandler(dataHandler).setIec104Config(iec104Config));
			Channel channel = bs.connect(host, port).sync().channel();
			channel.closeFuture().sync();
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			LOGGER.error("Exception caught", e);
		}

	}

	@Override
	public Iec104Master setDataHandler(DataHandler dataHandler) {
		this.dataHandler = dataHandler;
		return this;
	}

	@Override
	public Iec104Master setConfig(Iec104Config iec104Config) {
		this.iec104Config = iec104Config;
		return this;
	}

}
