package com.szpg.plc;

import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.szpg.db.dao.PgAcuDao;
import com.szpg.db.dao.impl.PgAcuDaoImpl;
import com.szpg.db.data.PgAcu;
import com.szpg.plc.server.ACUClient;
import com.szpg.plc.server.ACUClientUtil;
import com.szpg.task.ACUSocketCheckTask;

public class PGDSCServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4422075957571639803L;
	
	@Override
	public void init() throws ServletException {
		// 1获取数据库中所有ACU
		PgAcuDao acuDao = new PgAcuDaoImpl();
		List<PgAcu> acuList = acuDao.findAllACU();
		
		// 2遍历ACU列表，获取其IP地址与端口号
		for (PgAcu acu : acuList) {
			ACUClient client = new ACUClient(acu.getAcu_host(), Integer.parseInt(acu.getAcu_port()));
			
			client.setNet(acu.getAcu_net());
			client.setNode(acu.getAcu_node());
			client.setUnit(acu.getAcu_unit());
			
			// 3将ACU的信息加入到map中
			ACUClientUtil.getInstance().addClient(client);
			
			// 4新建线程启动client
			new ScheduledThreadPoolExecutor(1).scheduleAtFixedRate(new ACUSocketCheckTask(client), 0, 30, TimeUnit.SECONDS);
		}
	}
}
