[英]MQTT.js library best practices
我希望對 JavaScript MQTT.js庫有更多了解的人可以幫助我構建代碼。
我有以下代碼: MqttHandler 類,它使用 MQTT.js 庫連接、發布、訂閱和接收來自 Broker 的消息。 但是現在,如果我有多個要監控的事情,我不明白如何向代理發送操作。
在我的解決方案中,我們正在監控魚類水族館。
我有這兩個主題從傳感器向我發送數據:
aquarium/1/sensors/temperature
aquarium/1/sensors/waterLevel
和這個主題發送動作:
controller/1/actions/addWater
我有多個水族館: 1,2,3...10
處理每個水族館輸入的每個數據的正確方法是什么,以及將addWater操作發送到該特定水族館的正確方法是什么。 如果我只像這樣訂閱這些主題:
aquarium/*/sensors/temperature
aquarium/*/sensors/waterLevel
在我的onReceiveMessage
,我將收到消息中的aquarium id
,現在我想向該特定水族館發送waterAdd操作,如果水族館的水量低於為此水族館定義的閾值。 我怎樣才能以結構合理的方式實現這一點? 或者,如果我不過度復雜化並添加一長串 if 語句以在達到任何水族館的任何水位閾值時激活水動作,是否建議?
這是我的代碼:
const mqtt = require('mqtt');
const InfluxDbHelper = require('./InfluxDbHelper');
/**
* Class to connect to Broker and process MQTT messages
*/
class MqttHandler {
// create a MqttHandler instance for each Plant
// opts: the config used to connect to the Broker
constructor(opts) {
this.opts = opts;
const influxDbOptions = {
host: 'localhost',
database: 'sensors_data',
}
this.influxDbHelper = new InfluxDbHelper(influxDbOptions);
}
connect() {
return new Promise((resolve, reject) => {
// initialize the MQTT client
this.client = mqtt.connect(this.opts);
this.client.on('connect', function () {
resolve('Connected');
});
this.client.on("message", (topic, message) => {
this.onReceiveMessage(topic, message);
});
this.client.on('error', function (error) {
reject(error);
});
});
}
onReceiveMessage(topic, message) {
console.log(`From ${topic} : ${message}`)
const messageReceived = JSON.parse(message);
this.influxDbHelper.write('sensor_data', messageReceived);
}
subscribe(topic, qos = 0) {
return new Promise((resolve, reject) => {
this.client.subscribe(topic, {qos: qos}, function (error) {
if (error) {
reject(error);
}
resolve(`Subscribed to ${topic}`);
});
});
}
publish(topic, message) {
return new Promise((resolve, reject) => {
this.client.publish(topic, message, function (error) {
if (error) {
reject(error);
}
resolve();
});
});
}
}
module.exports = MqttHandler;
我是為我所有的水族館做一個 MqttHandler 還是為每個水族館做一個 MqttHandler ?
我真的不建議在客戶端做這樣的事情或使用 MQTT.js。 您可以使用帶有規則引擎的軟件來快速實現此類功能。
在這里你可以推薦 ekuiper:一個邊緣輕量級的物聯網數據分析軟件。
您可以使用其強大的消息規則引擎來實現您當前的場景問題
首先設置一條源自 MQTT 代理的源消息。
然后設置一個規則,當獲取的值大於某個值時觸發,例如
select * from aquarium where waterValue > 50
最后添加一個動作,動作是sink,你可以添加一個mqtt發布一個主題動作,這樣只要接收到的消息大於你設置的某個閾值,動作就會自動觸發。 無需編寫代碼。
即在您的應用場景中,實現自動補水。
如果非要在MQTT.js中實現,建議將業務邏輯封裝成一個函數。 使用回調函數來做到這一點。
function handleData(message, params cb) {
if (message.value > 50) {
cb(params)
}
}
onReceiveMessage(topic, message) {
console.log(`From ${topic} : ${message}`)
const messageReceived = JSON.parse(message);
this.influxDbHelper.write('sensor_data', messageReceived);
handleData(messageReceived, {topic, retain}, this.client.pushlish)
}
想學習MQTT.js的人可以參考這個教程: https ://www.emqx.com/en/blog/mqtt-js-tutorial
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.