In: Computer Science
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/#");
Steps To Run Code in the Java IDE.
1. Crete New Project Using File option-> new option -> or by entering ctrl + n(Control Plus new)
2. Don't create simple project. Create Project Of Maven or import already existing Maven Project.(if you have this file in the project)
3. Add dependency of "Paho MQTT" client in the pom.xml.
Since MQTTClient and connections has been used in your existing code hence you will have to add dependency .
just like ...
<dependencies>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>%VERSION_YOU_Are_using%</version>
</dependency>
</dependencies>
Add other dependency depending upon your project and whatever you have used.
4. Right click on the project.
Click Maven Clean
after successful cleaning, Build Maven Project.
And Run starting point of your Project.
or
Using command line, enter following command..
mvn clean install
and Run the starting point of your project.