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