0

Goal is to send data using mqtt protocol. Java project (tempSensor) produce tempvalue using mqtt protocol and node.js which subscribe tempvalue using mqtt. Both node.js and java project use same key for publish/subscribe. I am able to publish data using java project and also subscribe data in node.js. But data is not in readable format. How to do it ? So that data is in readable format. Structure for TempStruct is as below:

public class TempStruct implements Serializable {
private static final long serialVersionUID = 1L;

private double tempValue;

public double gettempValue() {
    return tempValue;
}

private String unitOfMeasurement;

public String getunitOfMeasurement() {
    return unitOfMeasurement;
}

public TempStruct(double tempValue, String unitOfMeasurement) {

    this.tempValue = tempValue;
    this.unitOfMeasurement = unitOfMeasurement;
}

public String toJSON() {
      String json = String.format("{'tempValue': %f, 'unitOfMeasurement': '%s'}", tempValue, unitOfMeasurement);
      return json;
    }
   }

Code which published data using mqtt is as below:

Logger.log(myDeviceInfo.getName(), "TemperatureSensor",
                "Publishing tempMeasurement");
        System.out.println("JSON Value...."+newValue.toJSON());
        try {
            this.myPubSubMiddleware.publish("tempMeasurement",
                    newValue.toJSON().getBytes("utf-8"), myDeviceInfo);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

Code which received data using mqtt is shown below:(Node.js)

var mqtt=require('mqtt');
var client=mqtt.connect('mqtt://test.mosquitto.org:1883');
var data;
client.subscribe('tempMeasurement');
client.on('message',function(topic,payload){
//arg=JSON.stringify(arg);
console.log("In Message......");
var tempStruct = JSON.parse(payload);
console.log("tempValue: "+tempStruct.tempValue); 
 });

Snapshot for error is shown below: Error from Node.js console

7
  • You have to convert the data into something different. JSON might be a good choice Commented Oct 30, 2015 at 5:57
  • @Nitek- Will try and get back to you. Thank You Commented Oct 30, 2015 at 5:58
  • @Nitek-Could you please check post and answer me?? Thank You Commented Oct 30, 2015 at 6:07
  • @Nitek-- Yes it doesn't work. Commented Oct 30, 2015 at 6:24
  • That's not an error description Commented Oct 30, 2015 at 6:25

2 Answers 2

3

MQTT message payloads are just byte arrays so you need to be aware of how a message is encoded at both the sending and receiving end. In this case it is not clear exactly what you are sending as the code you have posted is just passing a Java Object.

The error message in the picture implies that the a Java serialized version of the object is being sent as the message payload. While this will contain the information you need reassembling it in JavaScript will be incredibly difficult.

Assuming the TempStruct object looks something like this:

public class TempStruct {

  int value = 0;
  String units = "C";

  public void setValue(int val) {
    value = val;
  }

  public int getValue() {
    return value;
  }

  public void setUnits(String unit) {
    units = unit;
  }

  public String getUnits() {
    return units;
  }
}

Then you should add the following method:

public String toJSON() {
  String json = String.format("{'value': %d, 'units': '%s'}", value, units);
  return json;
}

Then edit your Java publishing code as follows:

...
 this.myPubSubMiddleware.publish("tempMeasurement", newValue.toJSON().getBytes("utf-8"),
            myDeviceInfo);
...

And change your JavaScript like this:

...
client.on('message',function(topic,payload){
  console.log("In messgage....");
  var tempStruct = JSON.parse(payload.payloadString)
  console.log("tempValue: "+tempStruct.value);        
});
...

EDIT:

Added getBytes("utf-8") to the Java code to ensure we are just putting the string bytes in the message.

EDIT2: Sorry, mixed up the paho web client with the npm mqtt module, the JavaScript should be:

...
client.on('message',function(topic,payload){
  console.log("In messgage....");
  var tempStruct = JSON.parse(payload.toString())
  console.log("tempValue: "+tempStruct.value);        
});
...
Sign up to request clarification or add additional context in comments.

4 Comments

@hardillb- Still it doesnot works...Segment of Error is shown below: undefined:1 �� ^ SyntaxError: Unexpected token �
I've stuck and edit in that I think should now work, but without seeing what you've changed I can't really guess
@hardillb- Could you please give me ans ?. Look at edited section in question. I have added all the required information. Could you please identify problem ?
@hardillb- Thank You for reply but still it is not working. I will try and possibly try to come with solution.
-3

Finally i am able to solve the problem.On the receiving side, we need to convert byte in to readable string and than parse readable using JSON parser. Solution is shown below:

var mqtt=require('mqtt');
var client=mqtt.connect('mqtt://test.mosquitto.org:1883');  
client.subscribe('tempMeasurement');
client.on('message',function(topic,payload){
if(topic.toString()=="tempMeasurement"){
console.log("Message received");
var data =payload.toString('utf8',7);
var temp=JSON.parse(data);
console.log(temp.tempValue,temp.unitOfMeasurement);
//console.log(data);
}  
});

2 Comments

That's no different from the answer I gave several weeks ago
@hardillb- You are right but here its a implementation. Thank You.

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.