[英]How to do Sync in Node-RED?
在我當前的項目中,我們正在嘗試開發一個簡單的應用程序“當我的室溫超過特定極限時通知我”。 該應用程序的流程圖如下:
在這里,溫度傳感器會定期生成溫度數據,並將感測到的數據發送到CalculateAvgTemp
組件。 CalculateAvgTemp
組件等待5個樣本,然后將計算出的值傳遞給DisplayTempController
。 用node.js編寫的CalculateAvgTemp
組件的代碼如下。
var mqtt=require('mqtt');
var client=mqtt.connect('mqtt://test.mosquitto.org:1883');
var NUM_SAMPLE_FOR_AVG=5;
var numSample=0;
var tempCelcius=0;
var currentAvg=0;
client.subscribe('sensorMeasurement');
client.on('message',function(topic,payload){
sensorMeasurement=JSON.parse(payload);
console.log(sensorMeasurement);
if(numSample <= NUM_SAMPLE_FOR_AVG){
numSample = numSample + 1;
if(sensorMeasurement.unitofMeasurement=='F'){
tempCelcius=((sensorMeasurement.tempValue-32)*(5/9));
}
else{
tempCelcius=sensorMeasurement.tempValue;
}
currentAvg=parseFloat(currentAvg)+parseFloat(tempCelcius);
if(numSample==NUM_SAMPLE_FOR_AVG){
//console.log(currentAvg);
currentAvg=currentAvg/NUM_SAMPLE_FOR_AVG;
var avgTemp={"avgTemp":parseFloat(currentAvg),"unitofMeasurement":sensorMeasurement.unitofMeasurement};
client.publish('roomAvgTemp',JSON.stringify(avgTemp));
numSample =0;
currentAvg=0;
}
}
});
我們正在嘗試在Node-RED中實現calculateAvgTemp
組件。 Node-RED提供功能節點 ,允許開發人員編寫自定義功能。 現在,真正的問題從這里開始--- Node-RED自定義函數無法正確實現calculateAvgTemp
功能。 它不會等待5個溫度值,並且會在溫度到達時觸發。 我的問題是-是Node-RED的限制嗎?還是應該在Node-RED中以不同的方式實現calcuateAvgTemp
功能?如果是,那么-我們如何在Node-RED中實現該功能? 用Node-RED編寫的CalculateAvgTemp
的代碼如下:
context.temps = context.temps || [];
sensorMeasurement=JSON.parse(msg.payload);
var tempValue=parseFloat(sensorMeasurement.tempValue);
context.temps.push(tempValue);
if (context.temps.length > 4) {
if (context.temps.length == 6) {
//throw last value away
context.temps.shift();
}
var avg=0;
for (var i=0; i<=context.temps.length; i++) {
avg += context.temps[i];
}
avg = avg/5;
msg.payload = parseFloat(avg);
return msg;
} else {
return null;
}
函數節點不需要傳遞任何東西,如果它不返回(或返回null),則流程將在該點停止。
您還可以使用context
變量將狀態存儲在功能節點中。 這意味着您可以存儲最后傳入的5個值,並且只有在擁有全部5個值才能計算平均值時才返回值。
就像是:
context.temps = context.temps || [];
context.temps.push(msg.payload);
if (context.temps.length > 4) {
if (context.temps.length == 6) {
//throw last value away
context.temps.shift();
}
var avg=0;
for (var i=0; i<context.temps.length; i++) {
avg += context.temps[i];
}
avg = avg/5;
msg.payload = avg;
return msg;
} else {
return null;
}
@hardillb ----非常感謝指針。 以下是解決方案
context.temps = context.temps || [];
data=JSON.parse(msg.payload);
context.temps.push(data.tempValue);
var NO_OF_SAMPLE=5;
if (context.temps.length > 4) {
var avg=0.0;
for (var i=0; i<NO_OF_SAMPLE; i++) {
avg =parseFloat(avg)+parseFloat(context.temps[i]);
}
avg =avg/NO_OF_SAMPLE;
msg.payload = avg;
context.temps=[];
return msg;
} else {
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.