2

I am using following java code to unwrap the data. But i don't know how could i write same for Node.js ? Java code is shown below:

public void receiveEvent(String forTopic, MqttMessage event)
        throws MqttException {
    Object obj = null;
    java.io.ByteArrayInputStream bstream = new   java.io.ByteArrayInputStream(
            event.getPayload());
    try {
        java.io.ObjectInputStream st = new java.io.ObjectInputStream(
                bstream);
        obj = st.readObject();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    DataWrapper dt = (DataWrapper) obj;
 s.notifyReceived(forTopic, dt.getObject(), dt.getDevice());

Code for data wrapper is shown below:

public class DataWrapper implements Serializable {
private static final long serialVersionUID = 1L;
Device device;
Object object;
public void setDevice(Device deviceInfo) {
    this.device = deviceInfo;
}
public void setObject(Object object) {
    this.object = object;
}
public Device getDevice() {
    return device;
}
public Object getObject() {
    return object;
}

}

1 Answer 1

3

You might want to look into MQTT.js. It's available on NPM here: https://www.npmjs.com/package/mqtt

For a full example, we'll need to know a bit more about your setup and what you're trying to do... but here's the example copied over from MQTT,js

var mqtt    = require('mqtt');
var client  = mqtt.connect('mqtt://test.mosquitto.org');

client.on('connect', function () {
  client.subscribe('presence');
  client.publish('presence', 'Hello mqtt');
});

client.on('message', function (topic, message) {
  // message is Buffer 
  console.log(message.toString());
  client.end();
});

It's probably pretty close to what you want to start with.

Sign up to request clarification or add additional context in comments.

3 Comments

@Julian- I know but i am new to node.js that's why asking such question. Already i did with java code.
We're going to need a bit more than that example code to really help you.. The only thing that your code is doing is converting the payload of your received event through 3 different kinds of stream before calling "notifyReceived" on a mysterious object "s".
@Julian- Could you please refer my following post? stackoverflow.com/questions/33429380/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.