-
Notifications
You must be signed in to change notification settings - Fork 0
/
grag.js
executable file
·934 lines (801 loc) · 36.1 KB
/
grag.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
#!/usr//bin/node
/*
TODO
- move even more into modules
- change doLater() blackbox to a 'pending tasks list' which can be queried
- transmogrify most config into 'things'
- watch for LWT from tasmota on tele/grag-xx/LWT, and use LWT ourselves: https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options -> 'will'
*/
const app = require('express')()
const http = require('http')
const https = require('https')
const fs = require('fs')
const path = require('path')
const Q = require('q')
const {promisify} = require('util')
const base64 = require('base-64')
const dict = require("dict")
const to = require('await-to-js').default
const winston = require('winston')
const { exec } = require("child_process")
const socketIo = require('socket.io')
const dns = require('dns')
const moment = require('moment')
const yaml = require('js-yaml')
const util = require('util')
const exec2 = util.promisify(require('child_process').exec);
// Warning: async loading
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args))
console.log('Press <ctrl>+C to exit.')
let sConfigFile = 'prod.yaml'
console.log("Loading config " + sConfigFile)
let config = yaml.load(fs.readFileSync(path.resolve(__dirname, 'config', sConfigFile), 'utf8'))
var isTerminated = false
async function terminate(errlevel) {
if (isTerminated) {
console.error("Quick kill")
process.exit(errlevel)
}
isTerminated = true
await Promise.all(god.preterminateListeners.map(async listener => {
try {
await listener()
} catch (e) {
if (this.logger) { this.logger.error("Exception during pre-terminate callback: %o", e) } else { console.log("Exception during pre-terminate callback: ", e) }
}
}))
await Promise.all(god.terminateListeners.map(async listener => {
try {
await listener()
} catch (e) {
if (this.logger) { this.logger.error("Exception during terminate callback: %o", e) } else { console.log("Exception during terminate callback: ", e) }
}
}))
process.nextTick(function () { process.exit(errlevel) })
}
var god = {
preterminateListeners: [],
terminateListeners: [],
terminate: terminate,
ioSocketList: {},
ioBase: {}, // io,
io: {}, // io.of('/browser'),
ioOnConnected: [],
state: {},
things: {},
thingController: undefined,
sensors: {},
historicValueCache: {},
onStateChanged: [],
onThingChanged: [],
onSensorUpdated: [],
onHistoricValueUpdated: [],
config: config,
app: app,
serverRunningSince: new Date(),
}
god.whiteboard = {
_callbacks: {},
addCallback: function(name, cb) {
if (!this._callbacks[name]) this._callbacks[name] = []
this._callbacks[name].push(cb)
},
getCallbacks: function(name) {
return this._callbacks[name] ? this._callbacks[name] : []
},
}
// ---- trap the SIGINT and reset before exit
process.on('SIGINT', function () {
console.log("Bye, Bye...")
terminate(0)
})
process.on('error', (err) => {
console.error(config.name + ": Unhandled error, terminating")
console.error(err)
terminate(0)
})
process.on('unhandledRejection', (reason, promise) => {
if (logger) logger.error(config.name + ": Unhandled Async Rejection at %o, reason %o", promise, reason)
else console.error(config.name + ": Unhandled Async Rejection at", promise, "reason", reason)
terminate(0)
})
/* Cert created with
openssl genrsa -out grag-key.pem
openssl req -new -key grag-key.pem -out csr.pem
openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out grag-cert.cert
rm csr.pem
*/
app.get("/", (req, res) => {
res.status(301).redirect(config.web.index)
})
app.use('/', require('express').static(__dirname + '/public'))
var httpServer = http.createServer(app)
httpServer.listen(config.web.port, function(){
logger.info('listening on *:' + config.web.port)
})
var io = socketIo(httpServer)
god.ioBase = io
god.io = io.of('/browser')
if (config.web.tls) {
let httpsOptions = {
key: fs.readFileSync(config.web.tls.pem),
cert: fs.readFileSync(config.web.tls.cert)
}
var httpsServer = https.createServer(httpsOptions, app)
httpsServer.listen(config.web.tls.port, function(){
logger.info('listening on *:' + config.web.tls.port)
})
io.attach(httpsServer)
}
function addNamedLogger(name, level = 'debug', label = name) {
let { format } = require('logform');
let prettyJson = format.printf(info => {
if (info.message.constructor === Object) {
info.message = JSON.stringify(info.message, null, 4)
}
return `${info.timestamp} [${info.level}]\t[${info.label}]\t${info.message}`
})
let getFormat = (label, colorize = false) => {
let nop = format((info, opts) => { return info })
return format.combine(
colorize ? format.colorize() : nop(),
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss',
}),
format.label({ label: label }),
format.splat(),
prettyJson
)
}
winston.loggers.add(name, {
level: level,
transports: [
new winston.transports.Console({
format: getFormat(label, true),
}),
new winston.transports.File({
format: getFormat(label, false),
filename: 'winston.log'
})
]
})
}
// prepareNamedLoggers
(()=>{
Object.keys(config.logger).forEach(name => {
let level = config.logger[name]
addNamedLogger(name, level)
})
})()
const logger = winston.loggers.get('main')
logger.info(config.name + ' waking up and ready for service')
const mqtt = require('./mqtt')(config.mqtt, god)
god.mqtt = mqtt
// initialization race condition, hope for the best... (later code parts could already access mpd1/2 before the async func finishes)
var mpd1
(async () => { mpd1 = await require('./mpd')(god, 'localhost', 'mpd1', 'grag-mpd1') })()
var mpd2
(async () => { mpd2 = await require('./mpd')(god, 'grag-hoardpi', 'mpd2', 'grag-mpd2') })()
const web = require('./web')(god, 'web')
const gpio = require('./gpio')(god, 'gpio')
const allnet = require('./allnet')(god, 'allnet')
const ubnt = require('./ubnt')(god, 'ubnt')
const displayPos = require('./POS')(god, 'POS')
const displayFlipdot = require('./Flipdot')(god, 'Flipdot')
const tasmota = require('./tasmota')(god, 'tasmota')
const network = require('./network')(god, 'net')
const scenario = require('./scenario')(god, 'scenario')
const screenkeys = require('./screenkeys')(god, 'keys')
god.thingController = require('./things')(god, 'things')
const crestron = require('./crestron')(god, 'Crestron')
async function runCommand(cmd) {
logger.warn("Calling system command: %s", cmd)
const { stdout, stderr } = await exec2(cmd);
console.log('stdout:', stdout);
console.log('stderr:', stderr);
return stdout + "\n" + stderr
}
/* Starts a timer to monitor a value
*
* Every 'intervalSec' the function 'fnWatch' is queried, then on each change of the return value 'fnOnChange' is called
*/
timer = {
timers: dict(),
watchChange: async function(name, intervalSec, fnWatch, fnOnChange) {
var self = this
console.log("Timer: added change watch '%s' every %d sec", name, intervalSec)
var timerId = setInterval(async () => {
let value = await fnWatch()
let lastValue = self.timers.get(name).lastValue
self.timers.get(name).lastValue = value
if (value != lastValue) {
console.log("Timer: change detected for '%s': %s -> %s", name, lastValue, value)
await fnOnChange(value)
}
}, intervalSec * 1000)
self.timers.set(name, { id: timerId })
return timerId
}
}
/* Call functions on repeated button presses
*
* Returns an async function which counts invocations and calls the given callback when 'count' invocations have occured in the last 'sec' seconds
*/
var multipress = function(name, count, sec, fn) {
// init private fields
if (!this.id) {
this.id = 0
this.multipressData = []
}
// current id as closure
let mpId = this.id++
this.multipressData[mpId] = {
name: name,
count: count,
msec: sec * 1000,
log: []
}
return async () => {
let mpData = this.multipressData[mpId]
let now = new Date()
while (mpData.log.length > 0 && now - mpData.log[0] > mpData.msec) {
mpData.log.shift()
}
mpData.log.push(now)
if (mpData.log.length >= mpData.count) {
logger.debug("Multipress '%s' triggered", mpData.name)
mpData.log = []
let r = await fn()
return "mp triggered: " + r
} else {
logger.debug("Multipress '%s', count %s of %s", mpData.name, mpData.log.length, mpData.count)
return "mp=" + mpData.log.length + "/" + mpData.count
}
}
}
// TODO WIP
let laterList = []
let doLaterFunc = undefined
async function doLater(func, seconds) {
clearTimeout(doLaterFunc)
timerSpeaker = setTimeout(async function() {
return await func()
}, seconds * 1000)
return "Do something " + seconds + " seconds later"
}
/** Allowed targets and parameters for the proxy
* key: name of target device
* url: base url
* cmd: array of allowed parameters, which are appended to the base url
*/
var proxyCommands = {
'off': 'Power1 0',
'on': 'Power1 1',
'toggle': 'Power1 2',
'off2': 'Power2 0',
'on2': 'Power2 1',
'onb': 'Backlog Power1 1; Delay 50; Power1 0',
}
var proxyCommandsBlinds = {
'up': 'Backlog Power2 0; Power1 1; Delay 200; Power1 0',
'down': 'Backlog Power1 0; Power2 1; Delay 200; Power2 0',
'stop': 'Backlog Power1 0; Power2 0',
}
var proxyTargets = {
'hoard-light': { 'url': 'http://grag-hoard-light.lair.clawtec.de/cm?cmnd=', cmd: proxyCommands } ,
'hoard-fan': { 'url': 'http://grag-hoard-fan.lair.clawtec.de/cm?cmnd=', cmd: proxyCommands } ,
'container-light': { 'url': 'http://grag-container-light.lair.clawtec.de/cm?cmnd=', cmd: proxyCommands } ,
'blinds1': { 'url': 'http://grag-main-blinds.lair.clawtec.de/cm?cmnd=', cmd: proxyCommandsBlinds } ,
'blinds2': { 'url': 'http://grag-main-blinds2.lair.clawtec.de/cm?cmnd=', cmd: proxyCommandsBlinds } ,
'plug1': { 'url': 'http://grag-plug1.lair.clawtec.de/cm?cmnd=', cmd: proxyCommands },
}
async function proxy(targetId, cmd) {
let target = proxyTargets[targetId]
if (!target) return "[target unknown]"
if (!target.cmd[cmd]) return "[cmd unknown]"
let param = encodeURIComponent(target.cmd[cmd])
try {
let res = await fetch(target.url + param)
let resText = await res.text()
logger.info("proxy " + targetId + " responsed: " + res.status + " " + resText)
return resText
} catch(e) {
logger.error("proxy " + targetId + " Error: ")
logger.error(e)
return "[ERROR] " + e
}
}
// https://stackabuse.com/executing-shell-commands-with-node-js/
function auto_mount(host, filename) {
exec("/usr/bin/ssh " + host + '.lair.clawtec.de "ls -alF /mnt/auto/grag-audio/' + filename + '"', (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return false;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return false;
}
console.log(`stdout: ${stdout}`);
return true
});
}
function aplay(host, filename) {
auto_mount(host, filename)
let lowVolume = host == 'grag-hoardpi' ? 25 : 50
let device = host == 'grag-hoardpi' ? 'Speaker' : 'Master'
let cmd = 'amixer set ' + device + ' ' + lowVolume + '%; sudo aplay /mnt/auto/grag-audio/' + filename + '; amixer set ' + device + ' 100%'
if (host != 'grag') {
cmd = '/usr/bin/ssh ' + host + '.lair.clawtec.de "' + cmd + '"'
}
exec(cmd, (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return false;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return false;
}
console.log(`stdout: ${stdout}`);
return true
});
}
io.of('/browser').on('connection', async (socket) => {
god.ioSocketList[socket.id] = {
socket: socket,
subscriptions: {}
}
let ip = socket.client.conn.remoteAddress
logger.debug('a user connected from %s, socket.id=%s', ip, socket.id)
// dns is async. If we would wait for it, we might loose subsequent messages. If we postpone logging the 'user connected' line, the log gets out of order (and in case of crashes, might even not be logged at all)
/*
(async () => {
let rdns = await promisify(dns.reverse)(ip).catch(err => { logger.warn("Can't resolve DNS for " + ip + ": " + err) })
logger.info(ip + " resolves to " + rdns)
})()
*/
socket.on('disconnect', function(data) {
logger.debug('user disconnected, client.id=%s (%s): %s', socket.id, socket.client.conn.remoteAddress, data)
delete god.ioSocketList[socket.id]
})
socket.on('subscribe', function(data) {
god.ioSocketList[socket.id].subscriptions[data] = {}
})
socket.on('unsubscribe', function(data) {
delete god.ioSocketList[socket.id].subscriptions[data]
})
god.ioOnConnected.forEach(callback => callback(socket))
socket.emit('welcome', god.serverRunningSince)
})
// Adds a whiteboard listener to make it available as a subscription for websockets
var socketAvailableSubscriptions = []
function socketWhiteboardSubscription(whiteboardName, subscriptionName = null, ioName = null) {
if (!subscriptionName) subscriptionName = whiteboardName
if (!ioName) ioName = subscriptionName
socketAvailableSubscriptions.push(subscriptionName)
god.whiteboard.addCallback(whiteboardName, async (data) => {
Object.keys(god.ioSocketList).forEach(id => {
let socketData = god.ioSocketList[id]
if (!socketData) {
logger.error("Socket %o", id)
return
}
if (socketData.subscriptions[subscriptionName]) {
socketData.socket.emit(ioName, data)
}
})
})
}
// whiteboard topics which are available for socket.io subscriptions
socketWhiteboardSubscription('screenkeys')
socketWhiteboardSubscription('tasmotaConfigUpdated')
socketWhiteboardSubscription('networkInfoUpdated')
socketWhiteboardSubscription('things')
socketWhiteboardSubscription('thingCurrentScenario')
socketWhiteboardSubscription('thingInfobox')
/** Send a tasmota-style mqtt command
* topic excludes the prefix, but does include the relais, e.g. 'grag-main-light/POWER1'
* topics can be a single string or an array
*/
var mqttAsyncTasmotaCommand = async (topics, message) => {
if (!Array.isArray(topics)) topics = [ topics ]
let commands = {}
for(let i = 0; i < topics.length; i++) {
let topic = topics[i]
let command = {
cmdTopic: 'cmnd/' + topic,
statTopic: 'stat/' + topic,
}
/* TODO this was supposed to be a check to verify that the commend was executed. It was never fully implemented. However the mqtt.removeTrigger seemed to create an inconsistency (wrong trigger removed?) which lead to a crash -> disabled for now
command.uuid = await mqtt.addTrigger(command.statTopic, 'Tasmota', async (trigger, topic, message, packet) => {
// TODO check if the received status is the one we wanted
logger.info("TODO: received %s: %s", topic, message)
mqtt.removeTrigger(topic, trigger.uuid)
})
*/
commands[command.uuid] = command
}
let keys = Object.keys(commands)
for(let i = 0; i < keys.length; i++) {
command = commands[keys[i]]
command.publishPromise = mqtt.publish(command.cmdTopic, message)
}
// TODO start a timeout timer, which rejects this mqttAsyncTasmotaCommand (and also removes the triggers)
let res = ''
for(let i = 0; i < keys.length; i++) {
command = commands[keys[i]]
res = await command.publishPromise
// TODO check for errors
// TODO handle res for i>0
}
// TODO should wait for (and sum up) the callbacks for stat/ and return those instead
return res
}
// TODO move to mqtt?!
god.mqttAsyncTasmotaCommand = mqttAsyncTasmotaCommand
// returns a callback which changes the global state and cascades the change
// id: global state id, will be set to the mqtt message
var onStateChanged = () => {
return async (trigger, topic, message, packet) => {
let id = trigger.id
let oldState = god.state[id]
let newState = message.toString()
try {
let json = JSON.parse(newState)
newState = json
} catch(e) {}
god.state[id] = newState
god.onStateChanged.forEach(cb => cb(id, oldState, newState))
}
}
/** Adds a trigger for incoming MQTT messages to update our global state
* topic: the MQTT topic to subscribe to, e.g. /stat/grag-main-light/POWER1
* id: token which is passed to the callback as 'trigger'
* callback: async(trigger, topic, message, packet), defaults to updating the global state
*/
var addMqttStatefulTrigger = async (topic, id, callback = onStateChanged()) => {
god.state[id] = undefined
mqtt.addTrigger(topic, id, callback)
// trigger a stat call, to get the initial state
if (topic.startsWith('stat/')) {
let topic2 = topic.replace('stat', 'cmnd')
mqtt.publish(topic2, '')
}
}
var onSensorUpdated = () => {
return async (trigger, topic, message, packet) => {
let id = trigger.id
let oldState = JSON.parse(JSON.stringify(god.sensors[id]))
try {
god.sensors[id].value = JSON.parse(message.toString())
} catch(e) {
logger.warn("Couldn't parse SENSOR structure: %o\n%o", e, message.toString())
god.sensors[id].value = message.toString()
}
god.sensors[id].lastUpdated = new Date()
god.sensors[id].dead = false
if ((oldState.value != god.sensors[id].value) || oldState.dead) {
god.onSensorUpdated.forEach(cb => cb(id, oldState, god.sensors[id]))
}
}
}
var addMqttSensor = async (topic, id, callback = onSensorUpdated()) => {
god.sensors[id] = {
value: undefined,
lastUpdated: undefined,
dead: true,
}
mqtt.addTrigger(topic, id, callback)
}
let sensorWatchdog = setInterval(() => {
let now = new Date()
Object.keys(god.sensors).forEach(id => {
if (!god.sensors[id].dead && now - god.sensors[id].lastUpdated > 70 * 1000) {
logger.info("Sensor %s timed out (last updated %s sec ago)", id, (now - god.sensors[id].lastUpdated) / 1000)
let oldState = JSON.parse(JSON.stringify(god.sensors[id]))
god.sensors[id].dead = true
god.onSensorUpdated.forEach(cb => cb(id, oldState, god.sensors[id]))
}
})
}, 10)
// pushes state changes to websocket clients
god.onStateChanged.push((id, oldState, newState) => god.io.emit('state-changed', { id: id, oldState: oldState, newState: newState } ))
god.ioOnConnected.push(socket => socket.emit('state', god.state))
// pushes sensor updates to websocket clients
god.onSensorUpdated.push((id, oldState, newState) => god.io.emit('sensor-updated', { id: id, oldState: oldState, newState: newState } ))
god.ioOnConnected.push(socket => socket.emit('sensors', god.sensors))
// pushes thing state changes to websocket clients
god.ioOnConnected.push(socket => socket.on('things', function(data) {
if (data == 'retrieveAll') {
logger.debug('Pushing full thing-config to client on request')
socket.emit('things', Object.values(god.things).map(thing => thing.fullJson))
}
if (data == 'retrieveThingGroups') {
logger.debug('Pushing all groups to client on request')
socket.emit('thingGroups', god.thingController.getGroupDefinitions())
}
if (data == 'retrieveThingStyling') {
logger.debug('Pushing thing styling to client on request')
socket.emit('thingStyling', god.config.web.styling)
}
if (data == 'retrieveThingQuicklinks') {
logger.debug('Pushing thing quicklinks to client on request')
socket.emit('thingQuicklinks', god.config.web.quicklinks)
}
if (data == 'retrieveScenarios') {
logger.debug('Pushing all scenarios to client on request')
socket.emit('scenarios', god.thingController.getScenario())
socket.emit('thingCurrentScenario', god.thingController.getCurrentScenario())
}
if (data.id && data.action) {
god.thingController.onAction(data.id, data.action)
}
}))
god.onThingChanged.push(thing => god.whiteboard.getCallbacks('things').forEach(cb => cb(thing.json)))
addMqttSensor('tele/grag-sensor1/SENSOR', 'sensor1')
addMqttSensor('tele/grag-sensor2/SENSOR', 'sensor2')
addMqttSensor('tele/grag-sensor3/SENSOR', 'sensor3')
addMqttSensor('sun/sunset', 'sun-sunset')
addMqttSensor('sun/sunfilter', 'sun-sunfilter')
addMqttStatefulTrigger('tele/grag-mpd1/STATE', 'mpd1')
addMqttStatefulTrigger('tele/grag-mpd2/STATE', 'mpd2')
addMqttStatefulTrigger('stat/grag-flipdot/light', 'flipdot-light')
addMqttStatefulTrigger('stat/grag-plug1/POWER', 'plug1')
addMqttStatefulTrigger('stat/grag-hoard-fan/POWER1', 'hoard-fan-out')
addMqttStatefulTrigger('stat/grag-hoard-fan/POWER2', 'hoard-fan-in')
addMqttStatefulTrigger('stat/grag-hoard-light/POWER1', 'hoard-light')
addMqttStatefulTrigger('stat/grag-hoard-light/POWER2', 'hoard-light2')
addMqttStatefulTrigger('stat/grag-attic/POWER1', 'attic-light')
addMqttStatefulTrigger('stat/grag-attic/POWER2', 'main-ventilator')
addMqttStatefulTrigger('stat/grag-main-light/POWER1', 'main-light1')
addMqttStatefulTrigger('stat/grag-main-light/POWER2', 'main-light2')
addMqttStatefulTrigger('stat/grag-main-blinds/POWER1', 'blinds1up')
addMqttStatefulTrigger('stat/grag-main-blinds/POWER2', 'blinds1down', async (trigger, topic, message, packet) => { if (message == 'ON') { mqtt.publish('cmnd/tts/sun-filter-descending', '')}; onStateChanged()(trigger, topic, message, packet) } )
addMqttStatefulTrigger('stat/grag-main-blinds2/POWER1', 'blinds2up')
addMqttStatefulTrigger('stat/grag-main-blinds2/POWER2', 'blinds2down')
addMqttStatefulTrigger('stat/grag-halle-main/POWER1', 'halle-main-light')
addMqttStatefulTrigger('stat/grag-halle-door/POWER1', 'halle-door-light')
addMqttStatefulTrigger('stat/grag-halle-door/POWER2', 'halle-compressor')
addMqttStatefulTrigger('stat/grag-outdoor-light/POWER1', 'outdoor-door-light')
addMqttStatefulTrigger('stat/grag-outdoor-light/POWER2', 'outdoor-main-light')
addMqttStatefulTrigger('stat/grag-usbsw1/POWER', 'usbsw1')
addMqttStatefulTrigger('stat/grag-usbsw2/POWER', 'usbsw2')
addMqttStatefulTrigger('stat/grag-4plug/POWER1', '4plug-1')
addMqttStatefulTrigger('stat/grag-4plug/POWER2', '4plug-2')
addMqttStatefulTrigger('stat/grag-4plug/POWER3', '4plug-3')
addMqttStatefulTrigger('stat/grag-4plug/POWER4', '4plug-4')
addMqttStatefulTrigger('stat/grag-4plug/POWER5', '4plug-usb')
addMqttStatefulTrigger('stat/grag-sonoff-p2/POWER', 'laden-coffee')
addMqttStatefulTrigger('stat/grag-sonoff-p3/POWER', 'test')
addMqttStatefulTrigger('stat/grag-sonoff-p4/POWER', 'laden-camera')
addMqttStatefulTrigger('stat/grag-main-strip/POWER', 'main-strip')
addMqttStatefulTrigger('stat/grag-container2-light/POWER1', 'container2-light-stairs')
addMqttStatefulTrigger('stat/grag-container2-light/POWER2', 'container2-light')
addMqttStatefulTrigger('stat/grag-flur-light/POWER1', 'flur-light')
addMqttStatefulTrigger('stat/grag-flur-light/POWER2', 'flur-light2')
addMqttStatefulTrigger('stat/grag-flur-light2/POWER1', 'door-button')
// onkyo2mqtt on startup triggers a 'system-power=query', and the response should then be available in mqtt
addMqttStatefulTrigger('onkyo/status/system-power', 'main-onkyo-power', async (trigger, topic, message, packet) => {
let id = trigger.id
let oldState = god.state[id]
let json = JSON.parse(message.toString())
logger.debug('Onkyo: %o', json)
if (json.onkyo_raw && json.onkyo_raw.startsWith('PWR')) {
let newState = json.val == 'on' ? 'ON' : json.val
god.state[id] = newState
god.onStateChanged.forEach(cb => cb(id, oldState, newState))
}
})
// get new volume from mqtt 'onkyo/status/master-volume'
// volume can be set with onkyo/set/master-volume (0..80)
addMqttStatefulTrigger('onkyo/status/master-volume', 'main-onkyo-volume', async (trigger, topic, message, packet) => {
let id = trigger.id
let oldState = god.state[id]
let json = JSON.parse(message.toString())
logger.debug('Onkyo: %o', json)
if (json.onkyo_raw && json.onkyo_raw.startsWith('MVL')) {
let newState = json.val
god.state[id] = newState
god.onStateChanged.forEach(cb => cb(id, oldState, newState))
}
})
god.ioOnConnected.push((async socket => {
socket.on('onkyo-setVolume', async (data) => {
logger.info("websocket: onkyo set volume to " + data)
// TODO error handling, input validation
god.mqtt.publish('onkyo/set/master-volume', data)
})
}).bind(this))
mqtt.addTrigger('cmnd/tts/fanoff', 'tts-fanoff', async (trigger, topic, message, packet) => { aplay('grag-hoardpi', 'fan-off-60min.wav') })
// mqtt.addTrigger('cmnd/tts/sun-filter-descending', 'sun-filter-descending', async (trigger, topic, message, packet) => { aplay('grag', 'sun-filter-descending.wav') })
mqtt.addTrigger('shellies/shellyem/emeter/1/power', 'test', async (trigger, topic, message, packet) => {
let power = parseFloat(message.toString())
if (power < 1) {
logger.error("Shelly: %o - Power off", power)
god.mqtt.publish('grag-hoard-light/POWER1', 'ON')
} else {
logger.error("Shelly: %o - Power on", power)
god.mqtt.publish('grag-hoard-light/POWER1', 'OFF')
}
})
const ignore = () => {}
let mpMpd1Vol90 = multipress('MPD1 set volume to 90', 3, 2, async () => mpd1.setVolume(90) )
let mpMpd2Vol50 = multipress('MPD2 set volume to 50', 3, 2, async () => mpd2.setVolume(50) )
god.onStateChanged.push((id, oldState, newState) => { if ((id == 'blinds1a' || id == 'blinds1b') && typeof oldState !== 'undefined') mqttAsyncTasmotaCommand('grag-4plug/POWER3', newState) })
web.addMqttMappingOnOff("main-lights", ['grag-main-light/POWER1', 'grag-main-light/POWER2'])
web.addMqttMappingOnOff("main-ventilator", 'grag-attic/POWER2')
web.addMqttMappingOnOff("main-strip", 'grag-main-strip/POWER')
web.addMqttMappingOnOff("hoard-light", 'grag-hoard-light/POWER1')
web.addMqttMappingOnOff("hoard-light2", 'grag-hoard-light/POWER2')
web.addMqttMappingOnOff("attic-light", 'grag-attic/POWER1')
web.addMqttMappingOnOff("flur-light", 'grag-flur-light/POWER1')
web.addMqttMappingOnOff("flur-light2", 'grag-flur-light/POWER2')
web.addMqttMappingOnOff("door-button", 'grag-flur-light2/POWER1')
web.addMqttMappingOnOff("laden-coffee", 'grag-sonoff-p2/POWER')
web.addMqttMappingOnOff("laden-camera", 'grag-sonoff-p4/POWER')
web.addMqttMappingOnOff("test", 'grag-sonoff-p3/POWER')
web.addMqttMappingOnOff("halle-main-light", 'grag-halle-main/POWER1')
web.addMqttMappingOnOff("halle-door-light", 'grag-halle-door/POWER1')
web.addMqttMappingOnOff("halle-compressor", 'grag-halle-door/POWER2')
web.addMqttMappingOnOff("outdoor-door-light", 'grag-outdoor-light/POWER1')
web.addMqttMappingOnOff("outdoor-main-light", 'grag-outdoor-light/POWER2')
web.addMqttMappingOnOff("container2-lights", ['grag-container2-light/POWER1', 'grag-container2-light/POWER2'])
web.addMqttMappingOnOff("usbsw1", 'grag-usbsw1/POWER')
web.addMqttMappingOnOff("usbsw2", 'grag-usbsw2/POWER')
web.addMqttMappingOnOff("4plug-1", 'grag-4plug/POWER1')
web.addMqttMappingOnOff("4plug-2", 'grag-4plug/POWER2')
web.addMqttMappingOnOff("4plug-3", 'grag-4plug/POWER3')
web.addMqttMappingOnOff("4plug-4", 'grag-4plug/POWER4')
web.addMqttMappingOnOff("4plug-usb", 'grag-4plug/POWER5')
web.addMqttMappingAny("scenario", 'scenario')
web.addListener("xhr", "status", async (req, res) => {
return '{"text":"Dragon", "time": ' +new Date() +'}'
})
web.addListener("hoard-fan-out", "on", async (req, res) => proxy('hoard-fan', 'on'))
web.addListener("hoard-fan-out", "off", async (req, res) => proxy('hoard-fan', 'off'))
web.addListener("hoard-fan-out", "off15min", async (req, res) => { proxy('hoard-fan', 'on'); aplay('grag-hoardpi', 'fan-off-15min.wav'); return doLater(async () => { await proxy('hoard-fan', 'off') }, 15 * 60) } )
web.addListener("hoard-fan-out", "off30min", async (req, res) => { proxy('hoard-fan', 'on'); aplay('grag-hoardpi', 'fan-off-30min.wav'); return doLater(async () => { await proxy('hoard-fan', 'off') }, 30 * 60) } )
web.addListener("hoard-fan-out", "off60min", async (req, res) => { proxy('hoard-fan', 'on'); aplay('grag-hoardpi', 'fan-off-60min.wav'); return doLater(async () => { await proxy('hoard-fan', 'off') }, 60 * 60) } )
web.addListener("plug1", "on", async (req, res) => proxy('plug1', 'on'))
web.addListener("plug1", "off", async (req, res) => proxy('plug1', 'off'))
web.addListener("plug1", "toggle", async (req, res) => proxy('plug1', 'onb'))
web.addListener("plug1", "toggle5min", async (req, res) => doLater(async () => { await proxy('plug1', 'toggle') }, 5 * 60))
// Main MPD
web.addListener("mpd", "fadePause", async (req, res) => mpd1.fadePause(1))
web.addListener("mpd", "fadePauseTest", async (req, res) => { aplay('grag-hoardpi', 'Front_Center.wav'); return doLater(async () => { await mpd2.fadePause(5) }, 30) } )
web.addListener("mpd", "fadePause5min", async (req, res) => doLater(async () => { await mpd1.fadePause(45) }, 5 * 60))
web.addListener("mpd", "fadePause10min", async (req, res) => doLater(async () => { await mpd1.fadePause(45) }, 10 * 60))
web.addListener("mpd", "fadePlay", async (req, res) => (await mpd1.fadePlay(1)) + " (" + (await mpMpd1Vol90()) + ")" )
web.addListener("mpd", "fadePauseToggle", async (req, res) => mpd1.fadePauseToggle(1, 1))
web.addListener("mpd", "volUp", async (req, res) => mpd1.changeVolume(+5))
web.addListener("mpd", "volDown", async (req, res) => mpd1.changeVolume(-5) )
web.addListener("mpd", "status", async (req, res) => mpd1.getStatus())
web.addListener("mpd", "next", async (req, res) => mpd1.next())
web.addListener("mpd", "previous", async (req, res) => mpd1.previous())
var atob = require('atob')
web.addListener("mpd", "youtube-*", async (req, res) => {
let url = req.params.sCmd.substring('youtube-'.length)
url = url.replace(/\./g, '/')
url = atob(url)
logger.error('Got stream url: %s', url)
// https://www.youtube.com/watch?v=ChmLQT7_C4M
god.io.emit('toast', 'Fetching stream for ' + url)
return mpd1.getYoutubeUrl(url);
})
web.addListener("mpd", "sync", async (req, res) => mpd1.sync(mpd2))
// Hoard MPD
web.addListener("mpd2", "fadePause", async (req, res) => mpd2.fadePause(1))
web.addListener("mpd2", "fadePause5min", async (req, res) => doLater(async () => { await mpd2.fadePause(45) }, 5 * 60))
web.addListener("mpd2", "fadePause10min", async (req, res) => doLater(async () => { await mpd2.fadePause(45) }, 10 * 60))
web.addListener("mpd2", "fadePlay", async (req, res) => (await mpd2.fadePlay(1)) + " (" + (await mpMpd2Vol50()) + ")" )
web.addListener("mpd2", "fadePauseToggle", async (req, res) => mpd2.fadePauseToggle(1, 1))
web.addListener("mpd2", "volUp", async (req, res) => mpd2.changeVolume(+5))
web.addListener("mpd2", "volDown", async (req, res) => mpd2.changeVolume(-5))
web.addListener("mpd2", "status", async (req, res) => mpd2.getStatus())
web.addListener("mpd2", "next", async (req, res) => mpd2.next())
web.addListener("mpd2", "previous", async (req, res) => mpd2.previous())
web.addListener("blinds1", "up", async (req, res) => proxy('blinds1', 'up'))
web.addListener("blinds1", "down", async (req, res) => proxy('blinds1', 'down'))
web.addListener("blinds1", "stop", async (req, res) => proxy('blinds1', 'stop'))
web.addListener("blinds2", "up", async (req, res) => proxy('blinds2', 'up'))
web.addListener("blinds2", "down", async (req, res) => proxy('blinds2', 'down'))
web.addListener("blinds2", "stop", async (req, res) => proxy('blinds2', 'stop'))
//web.addListener("redButton", "A", async (req, res) => { mpd1.fadePauseToggle(5, 2); return "mpd2 toggled" })
//web.addListener("redButton", "A", async (req, res) => { mpd1.getYoutubeUrl('https://www.youtube.com/watch?v=ChmLQT7_C4M'); return "yo mama" })
//web.addListener("redButton", "A", async (req, res) => { fetch('http://mendra-s2600cp.lair.clawtec.de:8001/F10') })
//web.addListener("redButton", "B", async (req, res) => { fetch('http://mendra-s2600cp.lair.clawtec.de:8001/F10') })
//web.addListener("redButton", "B", async (req, res) => { return mqttAsyncTasmotaCommand('grag-main-light/POWER1', 'TOGGLE') + mqttAsyncTasmotaCommand('grag-main-light/POWER2', 'TOGGLE') })
web.addListener("redButton", "ping", async (req, res) => { return "pong" })
gpio.addInput(4, "GPIO 4", async value => { console.log("(main) GPIO: " + value); if (value) mpd1.fadePauseToggle(1, 3) })
allnet.addDevice('10.20.30.41', '1')
web.addListener("allnet1", "on", async (req, res) => { let v = await allnet.setState('1', 'on'); return "Switched Allnet #1 " + v })
web.addListener("allnet1", "off", async (req, res) => { let v = await allnet.setState('1', 'off'); return "Switched Allnet #1 " + v })
web.addListener("allnet1", "status", async (req, res) => { let v = await allnet.getState('1'); return "Allnet #1 is " + v })
allnet.addDevice('10.20.30.42', '2')
web.addListener("allnet2", "on", async (req, res) => { let v = await allnet.setState('2', 'on'); return "Switched Allnet #2 " + v })
web.addListener("allnet2", "off", async (req, res) => { let v = await allnet.setState('2', 'off'); return "Switched Allnet #2 " + v })
web.addListener("allnet2", "status", async (req, res) => { let v = await allnet.getState('2'); return "Allnet #2 is " + v })
web.addListener("flipdot-light", "on", async (req, res) => mqttAsyncTasmotaCommand('grag-flipdot/light', 'ON'))
web.addListener("flipdot-light", "off", async (req, res) => mqttAsyncTasmotaCommand('grag-flipdot/light', 'OFF'))
web.addListener("flipdot-cfg", "read", (req, res) => displayFlipdot.controller.getDataForWeb())
web.addListener("flipdot-cfg", "write", (req, res) => console.log(req) /* displayPos.controller.setDataFromWeb() */ )
web.addListener("main-onkyo-power", "on", async (req, res) => mqtt.publish('onkyo/set/system-power', 'on') )
web.addListener("main-onkyo-power", "off", async (req, res) => mqtt.publish('onkyo/set/system-power', 'off') )
/* TODO
Goal: toggle 'Zapper' based on room light and assumed sunlight
- room light off, after sunset -> condition kept for 2min? -> zapper on
- room light on -> condition kept for 5min? -> zapper off
- blinds up, after sunrise -> condition kept for 15sec? -> zapper off
Needs:
- a "condition checker" (rule)
- triggered by events (including time, including sunset/rise times)
- last-changed timestamp and repeatable timer to check for unchanged condition
- remember when the condition already triggered (could use the expiring of a timer for that)
on AnyEvent
for all conditions
update condition status
status changed?
update condition-status-changed timestamp
timer running? -> stop
condition changed to true? -> start new timer
*/
// TODO move to Flipdot.js ?
let flipdot = async (req, res) => {
let text = req.params.sCmd.substring(1)
let cmd = '\f'
let spaces = ' '
if (text != '') {
let lines = (text+'\n\n').split(/\r?\n/)
cmd = '\b' + (lines[0] + spaces).substring(0, 19) + '\n' + (lines[1] + spaces).substring(0, 19)
console.log("Lines #" + lines.length)
console.log(lines)
}
console.log("Pushing: " + cmd)
mqtt.client.publish('grag-flipdot/text', cmd, { retain:true })
return "Message sent to Flipdot"
}
web.addListener("flipdot", "*", flipdot)
// TODO move to POS.js ?
let pos = async (req, res) => {
let text = req.params.sCmd.substring(1)
let cmd = '\f'
let spaces = ' '
if (text != '') {
let lines = (text+'\n\n').split(/\r?\n/)
cmd = '\f' + (lines[0] + spaces).substring(0, 20) + (lines[1] + spaces).substring(0, 20)
//console.log("Lines #" + lines.length)
//console.log(lines)
}
mqtt.client.publish('grag/pos', cmd, { retain:true })
return "Message sent to POS"
}
web.addListener("pos", "*", pos)
let fnMusic = async () => {
if (!mpd1) return ""
let status = await mpd1.getStatus()
if (status.state == "play") {
return "Currently playing\n" + (moment().second() % 4 < 2 ? status.Name : status.Title)
}
return '' // "no music playing"
}
let fnSensor = async () => {
let co2 = god.sensors?.['sensor1']?.value?.['SCD30']?.CarbonDioxide
let hum = god.sensors?.['sensor1']?.value?.['BME280-77']?.Humidity
let temp = god.sensors?.['sensor2']?.value?.['DS18B20-8']?.Temperature
return util.format("%s C / %s %%H\nCO2: %s ppm", temp ? Number(temp).toFixed(1) : '?', hum ? Number(hum).toFixed(0) : '?', co2 ? co2 : '?')
}
//displayPos.addEntry(displayPos.controller.fnText('welcome', ' Welcome to\n Clawtec'))
displayPos.addEntry(displayPos.controller.fnTime('time'))
displayPos.addEntry(displayPos.controller.fnSunfilter('sunfilter'))
displayPos.addEntry(displayPos.controller.fnCallback('sensor', 'Sensor Data', fnSensor))
displayPos.addEntry(displayPos.controller.fnCallback('mpd', 'Main MPD Status', fnMusic))
displayFlipdot.addEntry(displayFlipdot.controller.fnText('welcome', ' Welcome to\n Clawtec'))
displayFlipdot.addEntry(displayFlipdot.controller.fnTime('time'))
displayFlipdot.addEntry(displayFlipdot.controller.fnSunset('sunfilter'))
//displayPos.controller.setDataFromWeb({ welcome: { active: false }})
//console.log(displayPos.controller.getDataForWeb())
/* Voice Output
- Glados from http://15.ai
"The fan will be switched off in XX minutes"
*/