簡體   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