UNPKG

node-red-contrib-services-mentor

Version:

Mentor Services

57 lines (46 loc) 2.5 kB
module.exports = function(RED) { require('./date-format.js') var log = RED.log; function IntervalTimerNode(config) { RED.nodes.createNode(this,config); var node = this; var interval = 1000*config.interval; var timer; this.initialdefer = parseInt(config.initialdefer, 5) || 0; var timeHandler = function() { var date = Date.now(); if (node.initialdefer > 0) node.status({fill:"yellow",shape:"dot",text:"Defering " + node.initialdefer + " seconds(s)"}); else node.status({fill:"green",shape:"dot",text:"Next: " + formatDate(date + (interval - (date % interval)))}); setTimeout(function () { node.send({payload: config.payload || date - (date % interval)}); node.status({fill:"green",shape:"dot",text:"Next: " + formatDate(date + (interval - (date % interval)))}); }, node.initialdefer*1000) timer = setTimeout(timeHandler, interval - (date % interval)); // setInterval apparently has a considerable drift, so we use setTimeout to stay within the time grid as much as possible }; if (interval > 0) { var date = Date.now(); timer = setTimeout(timeHandler, interval - (date % interval)); node.status({fill:"green",shape:"dot",text:"Next: " + formatDate(date + (interval - (date % interval)))}); } else node.status({fill:"yellow",shape:"dot",text:"OFF"}); node.on('close', function() { clearTimeout(timer); }); } function formatDate (date) { now = new Date(date); return now.format('d-m-Y H:i:s P'); /* year = "" + now.getFullYear(); month = "" + (now.getMonth() + 1); if (month.length == 1) { month = "0" + month; } day = "" + now.getDate(); if (day.length == 1) { day = "0" + day; } hour = "" + now.getHours(); if (hour.length == 1) { hour = "0" + hour; } minute = "" + now.getMinutes(); if (minute.length == 1) { minute = "0" + minute; } second = "" + now.getSeconds(); if (second.length == 1) { second = "0" + second; } return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; */ } RED.nodes.registerType("Interval", IntervalTimerNode); }