Node-REDを実案件で運用していると、時間によってなにかを切り替えるような要望が発生します。
そんなときに使える方法をメモしておきます。
フロー
こちらがフロー。
Node-REDで時間を判断するときに、milsecという単位になおすと便利です。
上のフローは時間と分を入力するとmilsecに直すもの。
下のフローは現在の時刻から現在が昼か夜かを判断するもの。
春夏秋冬で昼と夜を切り替える時間が違うので、本当は日付によって春夏秋冬を判断したかったのですが、その場しのぎをしているので、まだ実装していません。(だれかつくったらおしえて)
フロー
[{"id":"e170d2bee7af3bce","type":"inject","z":"cb1d259c68175b7c","name":"日時","props":[{"p":"hour","v":"16","vt":"num"},{"p":"minute","v":"00","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","x":190,"y":120,"wires":[["f34017097ad6c3af"]]},{"id":"f34017097ad6c3af","type":"function","z":"cb1d259c68175b7c","name":"MilSec計算","func":"var hour = msg.hour;\nvar minute = msg.minute;\n\nvar milSec = getMilSec(hour,minute);\n\nmsg.payload = milSec;\n\nreturn msg;\n\n\nfunction getMilSec(hour,minute) {\n let milSec = hour*3600+minute*60;\n return milSec;\n}\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":290,"y":180,"wires":[["2e0d0e079e189742"]]},{"id":"2e0d0e079e189742","type":"debug","z":"cb1d259c68175b7c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":410,"y":240,"wires":[]},{"id":"c957d823fac86897","type":"function","z":"cb1d259c68175b7c","name":"day or night?","func":"// 昼か夜か?\nvar dayStatus = \"day\";\n\n// 日付オブジェクトを生成\nlet date = new Date();\n\n//年・月・日を取得する\nlet month = date.getMonth()+1;\nlet day = date.getDate();\n\n//時・分・秒を取得する\nlet hour = date.getHours();\nlet minute = date.getMinutes();\n\n//現在時刻のミリ秒作成\nlet currentMilSec = getMilSec(hour,minute);\n\n\n// Summer 5:00 〜 18:30\n// 18000 〜 66600\n// Fall 6:00 〜 17:00\n// 21600 - 61200\n// Winter 7:20 - 16:00\n// 26400 〜 57600\n\nif ( currentMilSec>26400 && currentMilSec < 57600){\n dayStatus = \"day\";\n\n} else {\n dayStatus = \"night\";\n}\n\nmsg.payload = dayStatus;\n\nreturn msg;\n\n// ミリセックを計算する関数\n\nfunction getMilSec(hour,minute) {\n let milSec = hour*3600+minute*60;\n return milSec;\n}\n\n\n\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":290,"y":380,"wires":[["2722e99e57459794"]]},{"id":"4ed8067d46627a7a","type":"inject","z":"cb1d259c68175b7c","name":"チェック","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":180,"y":320,"wires":[["c957d823fac86897"]]},{"id":"2722e99e57459794","type":"debug","z":"cb1d259c68175b7c","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":390,"y":440,"wires":[]}]
まとめ
思った以上に実プロジェクトでNode-REDが使われるようになりましたね。
Node-REDの時間での運用はこちらで採用しています。