66 lines
1.8 KiB
Java
Raw Normal View History

2019-10-04 16:52:14 +02:00
package com.wasteinformationserver.mqtt;
2019-10-11 16:16:28 +02:00
import com.wasteinformationserver.basicutils.Log;
2019-10-04 16:52:14 +02:00
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
2019-11-15 10:51:50 +01:00
public mqttreceiver(MqttClient mqtt) {
this.client = mqtt;
2019-10-11 15:02:55 +02:00
}
public String getmessage() {
2019-10-04 16:52:14 +02:00
try {
2019-11-15 10:51:50 +01:00
client.setCallback(new MqttCallback() {
2019-10-04 16:52:14 +02:00
@Override
public void connectionLost(Throwable throwable) {
2019-11-15 10:51:50 +01:00
Log.error("connection lost");
2019-10-04 16:52:14 +02:00
}
@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 16:16:28 +02:00
Log.debug("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