Advertisement
csongorvarga

Sensor On Time calculation in Node-Red

Feb 10th, 2021
773
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JSON 2.50 KB | None | 0 0
  1. [{"id":"ff5524ca.c696f8","type":"comment","z":"2934a51a.93393a","name":"Sensor on time calculation","info":"","x":140,"y":4280,"wires":[]},{"id":"40df9d42.df01f4","type":"inject","z":"2934a51a.93393a","name":"Sensor on","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"mysensor","payload":"on","payloadType":"str","x":180,"y":4360,"wires":[["596af5c7.3cc10c"]]},{"id":"7414f277.c733cc","type":"inject","z":"2934a51a.93393a","name":"Sensor off","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"mysensor","payload":"off","payloadType":"str","x":180,"y":4400,"wires":[["596af5c7.3cc10c"]]},{"id":"f0e008e2.dd8a68","type":"inject","z":"2934a51a.93393a","name":"Update","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"1","crontab":"","once":false,"onceDelay":0.1,"topic":"update","payload":"","payloadType":"date","x":180,"y":4480,"wires":[["596af5c7.3cc10c"]]},{"id":"596af5c7.3cc10c","type":"function","z":"2934a51a.93393a","name":"On time calculation","func":"let store = context.get(\"store\") || {};\nlet now = new Date();\n\nif (msg.topic===\"update\") {\n    // This is the part of the flow which updates the state in the context \n    if (store.state===undefined) {\n        // we did not get data from the sensor yet\n        node.status({fill:\"grey\",shape:\"dot\",text:\"no data\"});    \n        return;\n    } else {\n        if (!store.state) {\n            // sensor is off, nothing to do\n            return;\n        } else {\n            let ontime=Math.floor((now-store.laston)/1000); \n            node.status({fill:\"green\",shape:\"ring\",text:\"On, \"+ontime +\" sec\"});    \n            return [{topic: \"ontime\", payload: ontime}];\n        }\n    }\n\n    \n} else {\n    // This is the part which evaluates the state changes\n    if (msg.payload===\"on\") {\n        store.state = true;\n        store.laston = now;\n        node.status({fill:\"green\",shape:\"ring\",text:\"On\"});\n    }\n    if (msg.payload===\"off\") {\n        store.state = false;\n        node.status({fill:\"grey\",shape:\"dot\",text:\"Off\"});\n    }\n    context.set(\"store\", store);\n}\n","outputs":1,"noerr":0,"initialize":"","finalize":"","x":510,"y":4380,"wires":[["682be6ed.e32e58"]]},{"id":"682be6ed.e32e58","type":"debug","z":"2934a51a.93393a","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":780,"y":4380,"wires":[]}]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement