-
Notifications
You must be signed in to change notification settings - Fork 2
/
presence-faker.js
281 lines (242 loc) · 7.77 KB
/
presence-faker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
const { createSchedule, stripPastBlocks, setDebugFn } = require('./pf')
const CronJob = require('cron').CronJob
const dayjs = require('dayjs')
module.exports = function (RED) {
function PresenceFakerNode(config) {
RED.nodes.createNode(this, config)
const node = this
let windowBeginCron
let windowEndCron
let msgCrons = []
let isEnabled = false
const debug = function (debugMsg) {
if (config.isLoggingEnabled) {
node.warn(debugMsg)
}
}
setDebugFn(debug)
const setNodeStatusForBlock = function (block) {
const text = `${block.isOn ? 'ON' : 'OFF'} [${block.beginString} - ${
block.endString
}]`
node.status({
fill: 'yellow',
shape: block.isOn ? 'dot' : 'ring',
text,
})
debug(`new node status: ${text}`)
}
const setNodeStatus = function (text) {
node.status({
fill: 'grey',
shape: 'dot',
text: text,
})
debug(`new node status: ${text}`)
}
const isNowWithinWindow = function () {
const now = dayjs()
let begin = dayjs(now.format('YYYY-MM-DD') + 'T' + config.windowBegin)
let end = dayjs(now.format('YYYY-MM-DD') + 'T' + config.windowEnd)
const duration = end.diff(begin, 'seconds')
// handle special case of windowBegin > windowEnd, i.e. windows spanning two days
if (duration < 0) {
if (now.isBefore(end)) {
begin = begin.subtract(1, 'day')
} else if (now.isAfter(begin)) {
end = end.add(1, 'day')
}
}
const result =
(now.isAfter(begin) && now.isBefore(end)) ||
now.isSame(begin) ||
now.isSame(end)
debug(`isNowWithinWindow? ${result ? 'Yes' : 'No'}`)
return result
}
const scheduleWindowCrons = function () {
stopCrons()
const now = dayjs()
const begin = dayjs(now.format('YYYY-MM-DD') + 'T' + config.windowBegin)
const end = dayjs(now.format('YYYY-MM-DD') + 'T' + config.windowEnd)
const windowBeginCronCallback = function () {
debug('executing windowBeginCronCallback')
const schedule = stripPastBlocks(createSchedule(config))
debug('created new schedule: ' + JSON.stringify(schedule))
if (schedule.length > 0) {
const currentBlock = schedule.shift()
executeBlock(currentBlock)
}
scheduleMsgCrons(schedule)
}
if (isNowWithinWindow()) {
windowBeginCronCallback()
} else {
setNodeStatus(`next cycle: ${begin.format('HH:mm')}`)
}
windowBeginCron = CronJob.from({
cronTime: `0 ${begin.minute()} ${begin.hour()} * * *`, // sec min hour dom month dow
onTick: windowBeginCronCallback,
})
windowBeginCron.start()
windowEndCron = CronJob.from({
cronTime: `0 ${end.minute()} ${end.hour()} * * *`, // sec min hour dom month dow
// cronTime: fakeCronTime,
onTick: () => {
setNodeStatus('cycle completed')
},
})
windowEndCron.start()
debug(
`window crontabs set up for ${begin.format('HH:mm')} and ${end.format(
'HH:mm'
)}`
)
}
const scheduleMsgCrons = function (schedule) {
msgCrons = schedule.map((block) => {
const cron = CronJob.from({
cronTime: block.begin.toDate(),
onTick: () => {
executeBlock(block)
},
})
try {
cron.start()
} catch (e) {
debug(e)
}
return cron
})
debug(`installed crons for ${schedule.length} blocks`)
}
const stopCrons = function () {
if (windowBeginCron) {
windowBeginCron.stop()
windowEndCron.stop()
debug(`window crons deleted`)
}
let deletedCronsCount = 0
if (msgCrons.length > 0) {
msgCrons.forEach((cron) => {
cron.stop()
deletedCronsCount++
})
msgCrons = []
}
debug(`${deletedCronsCount} message crons deleted`)
}
const executeBlock = (block) => {
debug('executing block: ' + JSON.stringify(block))
ejectMsg(block.isOn)
setNodeStatusForBlock(block)
}
const ejectMsg = function (isOn, sendHandler) {
const castPayload = (payload, payloadType) => {
if (payloadType === 'num') {
return Number(payload)
} else if (payloadType === 'bool') {
return payload === 'true'
} else if (payloadType === 'json') {
return JSON.parse(payload)
} else {
return payload
}
}
let payload = isOn ? config.onPayload : config.offPayload
let payloadType = isOn ? config.onPayloadType : config.offPayloadType
let msgToSend = {
topic: isOn ? config.onTopic : config.offTopic,
payload: castPayload(payload, payloadType),
}
if (sendHandler) {
sendHandler(msgToSend)
} else {
node.send(msgToSend)
}
}
node.on('input', function (msg, send, done) {
send =
send ||
function () {
node.send.apply(node, arguments)
}
if (
msg.payload === true ||
msg.payload === 'true' ||
msg.payload === 'enable' ||
msg.payload === 'activate'
) {
// activate!
isEnabled = true
scheduleWindowCrons()
} else if (
msg.payload === false ||
msg.payload === 'false' ||
msg.payload === 'disable' ||
msg.payload === 'deactivate'
) {
// deactivate!
isEnabled = false
stopCrons()
if (isNowWithinWindow() && config.actionOnDisable !== 'none') {
ejectMsg(config.actionOnDisable === 'on', send)
}
setNodeStatus('inactive')
} else if (typeof msg.payload === 'object') {
// config object received as msg.payload
debug(`!!!! CONFIG OBJECT RECEIVED !!!`)
if (msg.payload.windowBegin) {
debug(`new windowBegin: ${msg.payload.windowBegin}`)
config.windowBegin = msg.payload.windowBegin
this.context().set('windowBegin', config.windowBegin)
}
if (msg.payload.windowEnd) {
debug(`new windowEnd: ${msg.payload.windowEnd}`)
config.windowEnd = msg.payload.windowEnd
this.context().set('windowEnd', config.windowEnd)
}
if (msg.payload.minDuration) {
debug(`new minDuration: ${msg.payload.minDuration}`)
config.minDuration = Number(msg.payload.minDuration)
this.context().set('minDuration', config.minDuration)
}
if (msg.payload.maxDuration) {
debug(`new maxDuration: ${msg.payload.maxDuration}`)
config.maxDuration = Number(msg.payload.maxDuration)
this.context().set('maxDuration', config.maxDuration)
}
if (msg.payload.minCount) {
debug(`new minCount: ${msg.payload.minCount}`)
config.minCount = Number(msg.payload.minCount)
this.context().set('minCount', config.minCount)
}
if (msg.payload.maxCount) {
debug(`new maxCount: ${msg.payload.maxCount}`)
config.maxCount = Number(msg.payload.maxCount)
this.context().set('maxCount', config.maxCount)
}
// force re-scheduling
if (isEnabled) {
node.emit('input', { payload: true })
}
}
if (done) {
done()
}
})
node.on('close', function () {
stopCrons()
})
;(function () {
// on startup:
if (config.startupBehavior === 'onStartup') {
node.emit('input', { payload: true })
} else {
setNodeStatus('starting up...')
setTimeout(() => setNodeStatus('inactive upon load'), 1000)
}
})()
}
RED.nodes.registerType('presence-faker', PresenceFakerNode)
}