package vs;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * client for the Smart Home application: logs sensor observations
 *
 * @author Sandro Leuchter
 *
 */
public class LoggingSubscriber {

	/**
	 * main routine and starting point of program. subscribe to topic
	 * <tt>Conf.TOPICSTART/#</tt> i.e. all messages in the Smart Home Application
	 *
	 * @param args not used
	 * @throws MqttException Paho library exceptions that have something to do with
	 *                       MQTT
	 * 
	 */
	public static void main(String[] args) throws MqttException {
		MqttClient client;
		client = new MqttClient(Conf.BROKER, MqttClient.generateClientId());
		client.setCallback(new MqttCallback() {

			@Override
			public void connectionLost(Throwable arg0) {
			}

			@Override
			public void deliveryComplete(IMqttDeliveryToken arg0) {
			}

			@Override
			public void messageArrived(String topic, MqttMessage m) throws Exception {
				System.out.println(topic + ": " + m.toString());
			}
		});
		client.connect();
		client.subscribe(Conf.TOPICSTART + "/#");
		try {
			while (true) {
				Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			System.err.println(e.getMessage());
		} finally {
			try {
				client.disconnect();
			} catch (MqttException e) {
				// unrecoverable
			}
		}
	}
}
