2019-10-04 16:52:14 +02:00
|
|
|
package com.wasteinformationserver.mqtt;
|
|
|
|
|
|
|
|
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
|
|
|
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
|
|
|
import org.eclipse.paho.client.mqttv3.MqttClient;
|
|
|
|
import org.eclipse.paho.client.mqttv3.MqttException;
|
|
|
|
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
|
|
|
|
|
|
|
import java.awt.event.ActionEvent;
|
|
|
|
import java.awt.event.ActionListener;
|
|
|
|
import java.util.ArrayList;
|
|
|
|
|
|
|
|
public class mqttreceiver {
|
|
|
|
|
2019-10-11 15:02:55 +02:00
|
|
|
private MqttClient client;
|
|
|
|
public ArrayList<ActionListener> mylisteners = new ArrayList<>();
|
|
|
|
public String message;
|
2019-10-04 16:52:14 +02:00
|
|
|
|
|
|
|
public mqttreceiver() {
|
|
|
|
|
2019-10-11 15:02:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public String getmessage() {
|
|
|
|
|
|
|
|
String temp;
|
|
|
|
|
2019-10-04 16:52:14 +02:00
|
|
|
try {
|
|
|
|
client = new MqttClient("tcp://192.168.65.15:1883", "JavaSample");
|
|
|
|
client.connect();
|
|
|
|
|
|
|
|
client.setCallback(new MqttCallback() {
|
|
|
|
@Override
|
|
|
|
public void connectionLost(Throwable throwable) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
|
2019-10-11 15:02:55 +02:00
|
|
|
message =new String(mqttMessage.getPayload());
|
|
|
|
notifylisteners(message);
|
|
|
|
|
2019-10-04 16:52:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
|
|
|
|
|
|
|
|
}
|
|
|
|
});
|
2019-10-11 10:48:04 +02:00
|
|
|
client.subscribe("TopicIn");
|
2019-10-11 15:02:55 +02:00
|
|
|
System.out.println("subscribed topic");
|
2019-10-04 16:52:14 +02:00
|
|
|
} catch (MqttException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
2019-10-11 15:02:55 +02:00
|
|
|
return message;
|
2019-10-04 16:52:14 +02:00
|
|
|
}
|
|
|
|
|
2019-10-11 15:02:55 +02:00
|
|
|
|
2019-10-11 09:03:14 +02:00
|
|
|
private void notifylisteners(String message) {
|
|
|
|
for (ActionListener ac : mylisteners) {
|
2019-10-11 15:02:55 +02:00
|
|
|
ac.actionPerformed(new ActionEvent(this, 0, message));
|
2019-10-04 16:52:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-10-11 09:03:14 +02:00
|
|
|
public void addMessageReceivedListener(ActionListener l) {
|
2019-10-04 16:52:14 +02:00
|
|
|
mylisteners.add(l);
|
|
|
|
}
|
2019-10-11 10:48:04 +02:00
|
|
|
|
2019-10-04 16:52:14 +02:00
|
|
|
}
|
2019-10-11 15:02:55 +02:00
|
|
|
|