package com.szpg.service;

import org.apache.log4j.Logger;

import com.szpg.db.dao.PgAcuDao;
import com.szpg.db.dao.PgAcuCmdDao;
import com.szpg.db.dao.impl.PgAcuDaoImpl;
import com.szpg.db.dao.impl.PgAcuCmdDaoImpl;
import com.szpg.db.data.PgAcu;
import com.szpg.db.data.PgAcuCmd;
import com.szpg.plc.message.CommandResponse;
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;

/**
 * 读取控制器状态的服务过程
 * 
 * @author admin
 *
 */
public class ReadControllerStatusService {
	
	private final Logger logger = Logger.getLogger(this.getClass().getName());
	
	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(command.getMessageProducerHost());
		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);
	}
	
}
