All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.envision.energy.eos.sdk.AlarmProcessProxy Maven / Gradle / Ivy

There is a newer version: 3.0.3
Show newest version
package com.envision.energy.eos.sdk;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.envision.energy.connective.protobuf.generated.Sdk.AlertStrReq;
import com.envision.energy.connective.protobuf.generated.Sdk.SubAllAlarm;
import com.envision.energy.connective.protobuf.generated.Sdk.SubType;
import com.envision.energy.eos.exception.SubscribeException;
import com.envision.energy.sdk.eos.core.Alarm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class AlarmProcessProxy {
	private Logger logger = LoggerFactory.getLogger(AlarmProcessProxy.class);

	private IAlarmHandler alarmHandler = null;
	private Transport transport = null;
	
	
	public void setTransport(Transport transport) {
		this.transport = transport;
	}
	
	//向server发送订阅消息
	public void sendSubMsg() {
		if(transport != null) {
			sendMsg(SubType.sub);
		}
	}
	
	private void sendUnsubMsg() {
		if(transport != null) {
			sendMsg(SubType.unsub);
		}
	}
 	
	private void sendMsg(SubType subType) {
		logger.info("subscribe alarm: " + subType+ ": " + transport.isStarted());
		if(transport.isStarted()) {
			transport.write(SubAllAlarm.newBuilder().setSubType(subType).build());
		}
	}
	
	public void subscribe(IAlarmHandler handler) 
			throws NullPointerException, SubscribeException {
		if(handler == null) {
			throw new NullPointerException("handler null");
		}
		
		alarmHandler = handler;
		
		sendSubMsg();
	}
	
	//向handler分发数据
	public void msgToHandler(AlertStrReq msg) {
		try {
			List alarms = getAlarms(msg);
			for(Alarm alarm : alarms) {
				if(alarmHandler != null) {
					alarmHandler.alarmRead(alarm);
				}
			}
		} catch(Exception e) {
			logger.error("callback error: " + e);
		}
	}
	
	private List getAlarms(AlertStrReq msg) {
		List alarms = new ArrayList();
		JSONArray jArray = new JSONArray(msg.getAlertJsonStr());
		for(int idx = 0; idx < jArray.length(); ++idx) {
			JSONObject jObj = jArray.getJSONObject(idx);
			Alarm alarm = new Alarm();
			alarm.setDeviceId(jObj.getString("deviceId"));
			alarm.setErrorType(Alarm.TYPE.values()[jObj.getInt("errType")]);
			alarm.setMsg(jObj.getString("errMsg"));
			alarm.setTimeStamp(jObj.getLong("timeStamp"));
			alarm.setBoxId(jObj.optString("boxId"));
			
			alarms.add(alarm);
		}
		
		return alarms;
	}
	
	public void unsubscribe() throws SubscribeException {
		try{
			sendUnsubMsg();
			alarmHandler = null;
		} catch(Exception e) {
			logger.error("exception: " + e);
			throw new SubscribeException("unsubscribe failed.");
		}
	}
	
	public void shutdown() {
		transport = null;
		alarmHandler = null;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy