简体   繁体   中英

mqtt communication between node.js and java

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: 来自Node.js控制台的错误

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM