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;

public class ReadO2ValueTask implements Runnable {
	
	private ReadSensorValueService service;

	public ReadO2ValueTask() {
		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_READO2VALUE);
				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 {
					command.setStartAddress(ByteUtil.binToHexString(ByteUtil.intToBins(Integer.parseInt(Configure.getProperty("acubl", client.getAcucode() + ".YQ.START")), 2)) + "00");
					command.setCountWord(Integer.parseInt(Configure.getProperty("acubl", client.getAcucode() + ".YQ.WORDCOUNT")));
					
					// 调用服务过程执行命令发送服务
					service.executeService(client, (ReadMemoryCommand) command);
					Logger.getLogger(this.getClass().getName()).info(command);
				} catch (Exception ex) {
					Logger.getLogger(getClass().getName()).error("发送查询氧气浓度指令异常" + ex);
					continue;
				}
			}
		}
	}

}
