001package var.mom.mqtt.smarthome;
002
003import org.eclipse.paho.client.mqttv3.MqttClient;
004import org.eclipse.paho.client.mqttv3.MqttException;
005import org.eclipse.paho.client.mqttv3.MqttMessage;
006
007/**
008 * client for the Smart Home application: sensor simulator
009 *
010 * @author Sandro Leuchter
011 *
012 */
013class Sensor {
014        /**
015         * topic to which this sensor publishes its observations
016         */
017        static String topic;
018        /**
019         * floor where sensor is located
020         */
021        static String floor;
022        /**
023         * room where sensor is located
024         */
025        static String room;
026        /**
027         * type of sensor
028         */
029        static String sensorType;
030        /**
031         * unique name of client
032         */
033        static String clientId = MqttClient.generateClientId();
034
035        /**
036         * main routine and starting point of program
037         *
038         * @param args[0] floor where sensor is located
039         * @param args[1] room where sensor is located
040         * @param args[2] type of sensor
041         * @param args[3] initial observation of sensor
042         * @throws MqttException Paho library exceptions that have something to do with
043         *                       MQTT
044         * 
045         */
046        public static void main(String[] args) throws MqttException {
047                floor = args[0];
048                room = args[1];
049                sensorType = args[2];
050                topic = Conf.TOPICSTART + "/" + floor + "/" + room + "/" + sensorType;
051                double lastObservation = Double.valueOf(args[3]);
052                MqttClient client;
053                client = new MqttClient(Conf.BROKER, clientId);
054                client.connect();
055                MqttMessage message = new MqttMessage();
056                try {
057                        while (true) {
058                                if (Math.random() > 0.5) { // randomly +/- 0.1
059                                        lastObservation += 0.1;
060                                } else {
061                                        lastObservation -= 0.1;
062                                }
063                                message.setPayload(String.valueOf(lastObservation).getBytes());
064                                client.publish(topic, message);
065                                Thread.sleep((int) (Math.random() * 1000)); // < 1 s waiting
066                        }
067                } catch (InterruptedException e) {
068                        System.err.println(e.getMessage());
069                } finally {
070                        try {
071                                client.disconnect();
072                        } catch (MqttException e) {
073                                // unrecoverable
074                        }
075                }
076        }
077}