Question

In: Computer Science

How to run the following code in ecclipse IDE? MQTT PUBLISH - SUBSCRIBE MODEL CODE IN...

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/#");

Solutions

Expert Solution

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.


Related Solutions

Run the following code and explain what the code does Run this code at least twice...
Run the following code and explain what the code does Run this code at least twice and take screenshots Explain what the code does What is the running result supposed to be What caused this issue? #include <thread> #include <iostream> using namespace std; const unsigned int NTHREADS = 20; const int ITERS = 10000000; int counter; void increment() {        for (int i = 0; i < ITERS; i++)                      counter++;               } void decrement() {        for (int i...
Run the following code and answer the following questions: (a) How do accuracy change with changing...
Run the following code and answer the following questions: (a) How do accuracy change with changing the tree maximum depth? [Your answer] (b) What are the ways to reduce overfitting in a decision tree? [Your answer] from sklearn import datasets import numpy as np from sklearn.model_selection import train_test_split from sklearn.tree import plot_tree iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=1, stratify=y) tree = DecisionTreeClassifier(criterion='entropy', max_depth=10, random_state=1) tree.fit(X_train,...
Compile and run the following code then answer the following questions: a.) Run this command from...
Compile and run the following code then answer the following questions: a.) Run this command from the shell prompt: ./a.out ls -F Explain, in your own words, why you see the screen output you do and how that output relates to both the content of the program AND the nature of the shell command used to invoke it. Be sure to comment on the pointer arithmetic done inside the line: execvp(*(argv+1), argv+1); b.) Run this command from the shell prompt:...
How long is the short run? The specific factor model is a short-run model because two...
How long is the short run? The specific factor model is a short-run model because two of the actors were specific to the two goods which would be true in the short run. In contrast, the Heckscher - Ohlin model is a long-run model because both factors of production are mobile which would be true in the long run. But we never discussed how long is the short run? (We only said that the short run is the period of...
Write code using the Arduino IDE that compiles with no errors. 2-bit adder: The code must...
Write code using the Arduino IDE that compiles with no errors. 2-bit adder: The code must read two digital input signals and turn on two LEDS as needed to show the sum of the inputs. e.g. 0 + 1 = 01.
I am using NetBeans IDE Java to code and I am seeking comment to the code...
I am using NetBeans IDE Java to code and I am seeking comment to the code as well (for better understanding). Magic squares. An n x n matrix that is filled with the numbers 1, 2, 3, …, n2 is a magic square if the sum of the elements in each row, in each column, and in the two diagonals is the same value. Write a program that reads in 16 values from the keyboard, displays them in a 4...
discuss the implications of EMH. If investors subscribe to the EMH market model, could they beat...
discuss the implications of EMH. If investors subscribe to the EMH market model, could they beat the market? Consider this more than 95% of mutual funds managers are unable to beat the market, why?
The following code will generate a Decision Tree. You need to run the code and explain...
The following code will generate a Decision Tree. You need to run the code and explain the tree. After you get the Tree. You need to explain how does it draw like that. install.packages("rpart.plot") # install package rpart.plot ########################################## # section 7.1.1 Overview of a Decision Tree ########################################## library("rpart") library("rpart.plot") # Read the data setwd("c:/data/") banktrain <- read.table("bank-sample-test.csv",header=TRUE,sep=",") ## drop a few columns to simplify the tree drops<-c("age", "balance", "day", "campaign", "pdays", "previous", "month") banktrain <- banktrain [,!(names(banktrain) %in% drops)]...
Do you think global businesses would be willing to subscribe to a global code of conduct?...
Do you think global businesses would be willing to subscribe to a global code of conduct? Explain your answer. Would it be easier to just follow the business practices and customs of the country in which you’re doing business? Why or why not? Are there more stakeholders for an international or global company than a domestic one? Explain your answer. How would the Foreign Corrupt Practices Act (FCPA) that we reviewed in Chapter 6 come into play here? Which offers...
JAVA Copy the attached code into your IDE or an online compiler and test an additional...
JAVA Copy the attached code into your IDE or an online compiler and test an additional type with the generic class. Submit your code and execution display. JAVA The test cases for Integer and String is given in the code. Please add test cases for Character, Boolean and Double type etc. // A Simple Java program to show working of user defined // Generic classes    // We use < > to specify Parameter type class Test<T> {     //...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT