Question
How to run the following code in ecclipse IDE? MQTT PUBLISH - SUBSCRIBE MODEL CODE IN JAVA (slide 29)public class Publisher { public static final
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/#");
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started