I have a microcontroller with a thermostat sending its data over Raspberry Pi to my computer using MQTT protocol. Kura is installed and working on the Raspberry.
I'm having no problems with receiving the data on Putty, but now I need to receive it on Eclipse so I can develop a program.
I managed to publish on the topic via eclipse using Paho with the following code, (which is an adaptation of this other topic Subscribe and Read MQTT Message Using PAHO):
package publish;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class PublishSemInterface {
MqttClient client;
public PublishSemInterface() {}
public static void main(String[] args) {
new PublishSemInterface().doDemo();
}
public void doDemo() {
try {
client = new MqttClient("tcp://192.168.0.39:1883", "user");
client.connect();
MqttMessage message = new MqttMessage();
message.setPayload("Published message".getBytes());
client.publish("sensor/temp/out", message);
client.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
But the subscribe is being a pain. I tried using the answer of the topic I mentioned above, implementing MqttCallback interface:
public class PublishSemInterface implements MqttCallback
Adding setCallback after connecting to the client and the required interface methods (I only need messageArrived):
client.setCallback(this);
@Override
public void connectionLost(Throwable cause) {}
@Override
public void messageArrived(String topic, MqttMessage message)
throws Exception {
System.out.println(message);
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {}
But it didn't work. I also tried using the answer from the following topic: How to read data from MQTT in Eclipse Paho?
public static void main(String[] args) {
MqttClient client;
MqttConnectOptions conn;
try {
client = new MqttClient("tcp://192.168.0.39:1883", "user");
client.connect();
client.setCallback(new MqttCallback() {
public void connectionLost(Throwable cause) {}
public void messageArrived(String topic,
MqttMessage message)
throws Exception {
System.out.println(message.toString());
}
public void deliveryComplete(IMqttDeliveryToken token) {}
});
client.subscribe("sensor/temp/in");
} catch (MqttException e) {
e.printStackTrace();
}
}
Except that it didn't work either. In both cases, when I run the code, the console is active, but when the microcontroller send the data (which appears on Putty), instead of printing it, the program is terminated. It looks as if the messageArrived methods are not being called.
Can anyone help me with the subscription and printing on Eclipse's console?