001package var.mom.mqtt.smarthome;
002
003import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
004import org.eclipse.paho.client.mqttv3.MqttCallback;
005import org.eclipse.paho.client.mqttv3.MqttClient;
006import org.eclipse.paho.client.mqttv3.MqttException;
007import org.eclipse.paho.client.mqttv3.MqttMessage;
008
009/**
010 * client for the Smart Home application: logs sensor observations
011 *
012 * @author Sandro Leuchter
013 *
014 */
015class LoggingSubscriber {
016
017        /**
018         * main routine and starting point of program. subscribe to topic
019         * <tt>Conf.TOPICSTART/#</tt> i.e. all messages in the Smart Home Application
020         *
021         * @param args not used
022         * @throws MqttException Paho library exceptions that have something to do with
023         *                       MQTT
024         * 
025         */
026        public static void main(String[] args) throws MqttException {
027                MqttClient client;
028                client = new MqttClient(Conf.BROKER, MqttClient.generateClientId());
029                client.setCallback(new MqttCallback() {
030
031                        @Override
032                        public void connectionLost(Throwable arg0) {
033                        }
034
035                        @Override
036                        public void deliveryComplete(IMqttDeliveryToken arg0) {
037                        }
038
039                        @Override
040                        public void messageArrived(String topic, MqttMessage m) throws Exception {
041                                System.out.println(topic + ": " + m.toString());
042                        }
043                });
044                client.connect();
045                client.subscribe(Conf.TOPICSTART + "/#");
046                try {
047                        while (true) {
048                                Thread.sleep(1000);
049                        }
050                } catch (InterruptedException e) {
051                        System.err.println(e.getMessage());
052                } finally {
053                        try {
054                                client.disconnect();
055                        } catch (MqttException e) {
056                                // unrecoverable
057                        }
058                }
059        }
060}