package vs;

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: sensor simulator
 *
 * @author Sandro Leuchter
 *
 */
public class Sensor {
	/**
	 * topic to which this sensor publishes its observations
	 */
	static String topic;
	/**
	 * floor where sensor is located
	 */
	static String floor;
	/**
	 * room where sensor is located
	 */
	static String room;
	/**
	 * type of sensor
	 */
	static String sensorType;
	/**
	 * unique name of client
	 */
	static String clientId = MqttClient.generateClientId();

	/**
	 * main routine and starting point of program
	 *
	 * @param args[0] floor where sensor is located
	 * @param args[1] room where sensor is located
	 * @param args[2] type of sensor
	 * @param args[3] initial observation of sensor
	 * @throws MqttException Paho library exceptions that have something to do with
	 *                       MQTT
	 * 
	 */
	public static void main(String[] args) throws MqttException {
		floor = args[0];
		room = args[1];
		sensorType = args[2];
		topic = Conf.TOPICSTART + "/" + floor + "/" + room + "/" + sensorType;
		double lastObservation = Double.valueOf(args[3]);
		MqttClient client;
		client = new MqttClient(Conf.BROKER, clientId);
		client.connect();
		MqttMessage message = new MqttMessage();
		try {
			while (true) {
				if (Math.random() > 0.5) { // randomly +/- 0.1
					lastObservation += 0.1;
				} else {
					lastObservation -= 0.1;
				}
				message.setPayload(String.valueOf(lastObservation).getBytes());
				client.publish(topic, message);
				Thread.sleep((int) (Math.random() * 1000)); // < 1 s waiting
			}
		} catch (InterruptedException e) {
			System.err.println(e.getMessage());
		} finally {
			try {
				client.disconnect();
			} catch (MqttException e) {
				// unrecoverable
			}
		}
	}
}
