nix
nix

Reputation: 165

How to read data from MQTT in Eclipse Paho?

I am trying to read sensor data using MQTT, using Eclipse Paho. I am successfully connected, but I want to read data. my code so far:

  public static void main(String[] args) {
    MqttClient client;
    MqttMessage msg;
    MemoryPersistence persistence;
    MqttConnectOptions conn;
    IMqttMessageListener listen;

    String broker = "tcp://url:1883";
    String str = "password";
    char[] accessKey = str.toCharArray();
    String appEUI = "userID";


    try {
        persistence = new MemoryPersistence();
        client = new MqttClient(broker, appEUI, persistence);
        conn = new MqttConnectOptions();
        conn.setCleanSession(true);
        conn.setPassword(accessKey);
        conn.setUserName(appEUI);
        client.connect(conn);
        //client.connect();

        if(client.isConnected()) {
            System.out.println("Connected..");
        }else {
            System.out.println("Unable to connect");
            System.exit(0);
        }

        msg = new MqttMessage();
        byte[] data = msg.getPayload();
        System.out.println(d);



    }catch(Exception x) {
        x.printStackTrace();
    }

}

But i am unable to read data. Can someone please guide?

Upvotes: 0

Views: 2718

Answers (1)

hardillb
hardillb

Reputation: 59731

You don't read data from a MQTT broker, instead you subscribe to a topic and get sent the data when ever a new message is published to that topic.

So you need to implement an instance of the MqttCallback interface and set it on the connection:

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) {
    }
});

Then you need to tell the broker which topics you are interested in:

client.subscribe("topic/foo")

Upvotes: 2

Related Questions