Skip to content

Instantly share code, notes, and snippets.

@jotathebest
Created February 24, 2019 13:34
Show Gist options
  • Save jotathebest/ed178c9ccf0a208ffdc005864639526d to your computer and use it in GitHub Desktop.
Save jotathebest/ed178c9ccf0a208ffdc005864639526d to your computer and use it in GitHub Desktop.
Ubidots MQTT with Java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package mqttexample;
import java.io.UnsupportedEncodingException;
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.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;
/**
*
* @author jota
*/
public class MqttExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MqttException, UnsupportedEncodingException {
// MQTT Broker Setup
String brokerUrl = "tcp://industrial.api.ubidots.com:1883";
String topic = "/v1.6/devices/my-device";
String token = ""; // Fill here with your token
// Data setup
String deviceLabel = "my-device";
String variableLabel = "my-var";
String testValue = "11";
String payload = "{\"" + variableLabel + "\": " + testValue + "}";
int qos=0;
String tmpDir = System.getProperty("java.io.tmpdir");
MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
// Creates the MQTT client
MqttClient client;
MqttConnectOptions conOpt;
conOpt = new MqttConnectOptions();
conOpt.setCleanSession(true);
conOpt.setUserName(token);
client = new MqttClient(brokerUrl,MqttClient.generateClientId(), dataStore);
if(!client.isConnected()){
System.out.println("Connecting to broker ...");
client.connect(conOpt);
}
// Sends Data
MqttMessage message = new MqttMessage(payload.getBytes("UTF-8"));
message.setQos(qos);
client.publish(topic, message);
client.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment