package com.szpg.task;

import java.util.Map;

import org.apache.log4j.Logger;

import com.szpg.plc.message.AppMessageConstants;
import com.szpg.plc.message.command.ReadMemoryCommand;
import com.szpg.plc.protocol.fins.FINSConstants;
import com.szpg.plc.server.ACUClient;
import com.szpg.plc.server.ACUClientUtil;
import com.szpg.plc.util.ByteUtil;
import com.szpg.service.ReadSensorValueService;
import com.szpg.util.Configure;

/**
 * 一期甲烷实时监测值读取任务
 * @author admin
 *
 */
public class ReadCH4ValueTask implements Runnable {

	private ReadSensorValueService service;

	public ReadCH4ValueTask() {
		service = new ReadSensorValueService();
	}

	@Override
	public void run() {
		// 查找所有的client
		Map<String, ACUClient> clients = ACUClientUtil.getInstance().getClients();
		
		for (String key : clients.keySet()) {
			ACUClient client = clients.get(key);
			if (client.getFlag().equals("11")) {
				// 构建命令对象
				ReadMemoryCommand command = ReadMemoryCommand.getInstance(AppMessageConstants.CMD_TYPE_READCH4VALUE);
				String sour = Configure.getProperty("sys", "LOCALHOST.NET") + 
							  Configure.getProperty("sys", "LOCALHOST.NODE") + 
							  Configure.getProperty("sys", "LOCALHOST.UNIT");
				command.setMessageProducerId(sour);
				command.setMessageProducerHost(client.getHost());
				
				String dest = client.getNet() + client.getNode() + client.getUnit();
				command.setDestinationId(dest);
				
				command.setMemoryArea(FINSConstants.MEMORY_DM_AREA);
				
				try {
					// 没有找到对应的配置项，直接返回
					String start = Configure.getProperty("acubl", client.getAcucode() + ".CH.START");
					if (null == start || start.equals("")) {
						continue;
					}
					
					command.setStartAddress(ByteUtil.binToHexString(ByteUtil.intToBins(Integer.parseInt(start), 2)) + "00");
					command.setCountWord(Integer.parseInt(Configure.getProperty("acubl", client.getAcucode() + ".CH.WORDCOUNT")));
					
					// 调用服务过程执行命令发送服务
					service.executeService(client, (ReadMemoryCommand) command);
					Logger.getLogger(this.getClass().getName()).info(command);
				} catch (Exception ex) {
					Logger.getLogger(getClass().getName()).error("发送查询甲烷指令异常" + ex);
					continue;
				}
			}
		}
	}
}
