Skip to content

Instantly share code, notes, and snippets.

@alcarazolabs
Forked from msvitok77/MQTTConsumer.java
Created April 26, 2022 15:52
Show Gist options
  • Save alcarazolabs/3afb155b54a71740d72d80033547fe28 to your computer and use it in GitHub Desktop.
Save alcarazolabs/3afb155b54a71740d72d80033547fe28 to your computer and use it in GitHub Desktop.
MQTT Sender/Consumer
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class MQTTConsumer {
public static void main(String[] args) {
String topic = "sah/+/#";
String broker = "tcp://90.183.120.37:1883";
String clientId = "JavaSample1";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
sampleClient.connect(connOpts);
sampleClient.subscribe(topic);
sampleClient.setCallback(new MqttCallback() {
public void connectionLost(Throwable throwable) {
throwable.printStackTrace();
}
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
System.out.println("Topic : " + topic + " Message : " + mqttMessage);
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("Delivery complete : " + iMqttDeliveryToken);
}
});
new CountDownLatch(1).await(100, TimeUnit.SECONDS);
sampleClient.disconnect();
} catch (MqttException | InterruptedException e) {
e.printStackTrace();
}
}
}
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import java.nio.charset.Charset;
public class MQTTSender {
public static void main(String[] args) {
String topic = "sah/to/HGW-3D00534148475555FBKL00100000587/api/Devices/Device/ZWAVE_13/off";
String broker = "tcp://90.183.120.37:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
sampleClient.connect(connOpts);
Charset utf8 = Charset.forName("UTF-8");
MqttMessage message = new MqttMessage( "{\"From\":\"me\", \"CallId\":321, \"Arguments\":{} }".getBytes(utf8));
message.setQos(0);
sampleClient.publish(topic, message);
sampleClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment