package com.szpg.service;

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

import com.szpg.db.dao.PgAcuCmdDao;
import com.szpg.db.dao.PgAcuDao;
import com.szpg.db.dao.impl.PgAcuCmdDaoImpl;
import com.szpg.db.dao.impl.PgAcuDaoImpl;
import com.szpg.db.data.PgAcu;
import com.szpg.db.data.PgAcuCmd;
import com.szpg.plc.message.command.ReadMemoryCommand;
import com.szpg.plc.protocol.DTProtocolInterface;
import com.szpg.plc.protocol.ProtocolFactory;
import com.szpg.plc.server.ACUClient;
import com.szpg.plc.server.ACUClientUtil;
import com.szpg.util.Configure;

/**
 * 读取环境变量监测值的服务过程
 * 
 * @author admin
 *
 */
public class ReadSensorValueService {
	
	private PgAcuCmdDao cmdDao = new PgAcuCmdDaoImpl();
	private PgAcuDao acuDao = new PgAcuDaoImpl();
	
	public void executeService(ACUClient client, ReadMemoryCommand command) {
		// 解析命令对象为字节数组
		DTProtocolInterface finspi = ProtocolFactory.getDefaultDTProtocol();
		byte[] content = finspi.messageToBytes(command);
		
		// 通过socket接口发送出去
		ACUClientUtil.getInstance().sendACUCommand(client, content);
		
		// 1查找数据库中的ACU对象
		PgAcu acu = acuDao.findACUByHost(client.getHost());
		if (null == acu) {
			return;
		}
		
		// 2生成读取命令对象
		PgAcuCmd cmd = new PgAcuCmd();
		cmd.setCmd_type(command.getCommandType());
		cmd.setDest_acu_code(acu.getAcu_code());
		cmd.setTm(command.getTime().getTime());
		
		// 3将命令保存入数据库
		cmdDao.addCmdRecord(cmd);
		
		// 4定时将数据库中的命令置为超时
		int TIMEOUT = Integer.parseInt(Configure.getProperty("sys", "COMMAND_TIMEOUT", "2"));
		new ScheduledThreadPoolExecutor(1).schedule(new RemoteCommandTimeoutTask(cmd.getId()), TIMEOUT, TimeUnit.MINUTES);
	}
}
