1. Engineering
  2. Computer Science
  3. how to run the following code in ecclipse ide mqtt...

Question: how to run the following code in ecclipse ide mqtt...

Question details

How to run the following code in ecclipse IDE?

MQTT PUBLISH - SUBSCRIBE MODEL CODE IN JAVA

(slide 29)public class Publisher
{
public static final String BROKER_URL = "tcp://broker.mqttdashboard.com:1883";
private MqttClient client;

public Publisher()
{

String clientId = Utils.getMacAddress() + "-pub";
try
{
client = new MqttClient(BROKER_URL, clientId);
}
catch (MqttException e)
{
e.printStackTrace();
System.exit(1);
}
}
}
//connecting client (slide 30)

MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(false);
options.setWill(client.getTopic("home/LWT"), //helps detecting failures of other clients
"I'm gone".getBytes(), 2, true);

client.connect(options);

//the busniness logic (slide 31)
public static final String TOPIC_TEMPERATURE = "home/temperature";

//...
while (true)
{
publishBrightness();
Thread.sleep(500);
publishTemperature();
Thread.sleep(500);
}
//...

private void publishTemperature() throws MqttException {
final MqttTopic temperatureTopic = client.getTopic(TOPIC_TEMPERATURE);

final int temperatureNumber = Utils.createRandomNumberBetween(20, 30);
final String temperature = temperatureNumber + "°C";

temperatureTopic.publish(new MqttMessage(temperature.getBytes()));
}

//publishBrightness() will be implemented the same way publishTemperature() is


//implementing the subscribing client

public class SubscribeCallback implements MqttCallback(slide 32)
{

@Override
public void connectionLost(Throwable cause) {}

@Override
public void messageArrived(MqttTopic topic, MqttMessage message)
{
System.out.println("Message arrived. Topic: " + topic.getName() + " Message: " + message.toString());

if ("home/LWT".equals(topic.getName()))
{
System.err.println("Sensor gone!");
}
}

@Override
public void deliveryComplete(MqttDeliveryToken token) {}

}

\\make it known to the MqttClient before connecting (slide 34)

mqttClient.setCallback(new SubscribeCallback());
mqttClient.connect();
mqttClient.subscribe("home/#");

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution