繁体   English   中英

Node.js与Java之间的mqtt通信

[英]mqtt communication between node.js and java

目标是使用mqtt协议发送数据。 Java项目(tempSensor)使用mqtt协议和node.js生成温度值,后者使用mqtt预订温度值。 node.js和java项目都使用相同的密钥进行发布/订阅。 我可以使用Java项目发布数据,也可以在node.js中订阅数据。 但是数据不是可读格式。 怎么做 ? 因此该数据为可读格式。 TempStruct的结构如下:

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

使用mqtt发布数据的代码如下:

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

使用mqtt接收数据的代码如下所示:(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); 
 });

错误快照如下所示: 来自Node.js控制台的错误

MQTT消息有效负载只是字节数组,因此您需要了解消息在发送和接收端如何进行编码。 在这种情况下,由于发布的代码只是传递Java对象,因此不清楚发送的是什么。

图片中的错误消息表示该对象的Java序列化版本正在作为消息有效负载发送。 尽管其中将包含您需要的信息,但是使用JavaScript对其进行重组将非常困难。

假设TempStruct对象看起来像这样:

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

然后,您应该添加以下方法:

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

然后,按如下所示编辑Java发布代码:

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

然后像这样更改您的JavaScript:

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

编辑:

在Java代码中添加了getBytes(“ utf-8”)以确保我们只是将字符串字节放入消息中。

EDIT2:对不起,将Paho Web客户端与npm mqtt模块混合在一起,JavaScript应该是:

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

最后我能够解决问题。在接收端,我们需要将字节转换为可读字符串,然后使用JSON解析器解析可读文件。 解决方案如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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