You can save variables in Node-red Flow/Storage Data using Arduino based boards like ESP8266 , ESP32, and so on.
Concept:
Send message to node/variable to store
publish to TOPIC + /$get to get stored data
Example:
To Set data, send mqtt messages like : Topic: "home/sensor1/variable1" -> Payload: "1"
To Get data, subscribe to "home/sensor1/variable1"
and publish message "home/sensor1/variable1/$get" -> Payload : "ANY"
The data will come in subscribed topic.
You can also get TIMESTAMP using same function just replace "variable1" with "time" using same method written above.
add a mqtt in (with your sensor root topic like "home/sensor1/#") and mqtt out (without topic) to output
Note:
The Time is in IST. To convert to Your Host Time Remove This Part : " + IST_offset;"
The Function Node Code :
var topic = msg.topic;
var payload = msg.payload;
var isget = false;
//IS GET REQUEST
if (topic.endsWith("/$get")) {
topic = topic.replace("/$get", "");
isget = true;
}
//Extract sensor_var
var topicParts = topic.split('/');
var nodename = topicParts[1];
var command = topicParts[topicParts.length - 1];
var variablename = nodename + "_" + command;
//GET REQUEST
if (isget) {
if (topic.endsWith("/time")) {
var date = new Date();
var IST_offset = 5.5 * 60 * 60 * 1000;
var IST_timestamp_ms = date.getTime() + IST_offset;
var IST_timestamp_sec = Math.floor(IST_timestamp_ms / 1000); // Convert to seconds (32-bit Unix timestamp)
msg.topic = topic;
msg.payload = IST_timestamp_sec;
return msg;
} else if (topic.endsWith("status") || topic.startsWith("reboot")) {
//STATUS OR REBOOT
//IGNORE
} else {
//TIME
// ALL TOPICS
let da = flow.get(variablename);
if (da == undefined) da = 0;
msg.topic = topic;
msg.payload = da;
return msg;
}
} else {
//SAVE
if (topic.endsWith("status") || topic.endsWith("/time") || topic.startsWith("reboot")) {
//STATUS TIME OR REBOOT
//IGNORE
} else {
//ALL OTHER
flow.set(variablename, payload);
}
}