-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththings.js
More file actions
executable file
·1778 lines (1588 loc) · 72.2 KB
/
Copy paththings.js
File metadata and controls
executable file
·1778 lines (1588 loc) · 72.2 KB
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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Thing Configurations
- in file config/thingDefinitions.yaml
- each entry defined one entity
- Entry Prototype:
id-of-entry: <- id of entity
disabled: false <- optional. If true, entry is ignored. Defaults to false.
name: Entry Name <- Display Name
group: MyLivingRoom <- group ID, as defined in /config/thingGroupDefinitions.yaml
api: [see below]
render: <- optional
icon: fa/bolt.svg <- optional, which icon to use on the UI. Defaults to a lightbulb
icon-on: fa/bolt-solid.svg <- optional, which icon to use on the UI for the 'on' state. Defaults to whatever is set with 'icon'
autohide: true <- optional, if true, will by default only be shown when in unexpected state (according to the scenario). Default: false
hiddenIfDead: true <- optional. If the device does not react, it will not be shown at all. Defaults to be shown as unreachable.
split: true <- optional. Click on icon reacts, click on text opens a modal (to be defined in thingGroupDefinitions.yaml with the same id as this thing)
- Several API providers exist:
- api: tasmota <- default Tasmota controlled device, connected via mqtt
Additional config lines:
- device: grag-main-light <- the device name, will be used to construct mqtt topics
- power: POWER <- for switches, the Tasmota command which output is used (e.g. "POWER", "POWER1", "POWER2")
- api: button <- button on the UI with a special function (not directly associated to a single entity)
Additional config lines:
- type: mqtt <- currently only supports 'mqtt'
- mqtt: my/topic cmd <- mqtt topic [space] mqtt command to send (can include spaces)
Examples:
- cmnd/grag-main-blinds2/BACKLOG POWER2 ON; DELAY 100; POWER2 OFF
- cmnd/scenario goodmorning
- api: mpd <- Music Player Daemon
Additional config lines:
- device: grag-mpd1
- togglevalues: <- when clicking on the icon, what action should be send depending on the current mpd state (allowed actions are 'play', 'pause', 'toggle')
play: pause
'': play
- api: composite <- combines multiple entities, uses a popup to control
Additional config lines:
- togglevalues: <- when clicking on the icon, what action should be send depending on the current entity state
'': 'ON'
- things: <- entity ids which are part of this composite. Will be acted upon when clicking the icon, will be individually shown in a popup when clicking on the text
- id: main-light-door
'': Door
- id: main-light-window
'': Window
- api: onkyo <- used mqtt to control a script which communicates with Onkyo audio via eth
Additional config lines:
- device: onkyo
- api: ledstrip.js <- my original Raspberry Pi based ledstrip controller
Additional config lines:
- device: grag-main-strip
- power: POWER
- api: tasmotaSensor
todo
- api: AIonEdge
todo
- api: zigbee2mqtt <- for Zigbee devices reachable via MQTT bridge
Additional config lines:
- topic: main-fridge <- will be used to construct the mqtt topic
*/
// Class documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes
const winston = require('winston')
const fs = require('fs')
const yaml = require('js-yaml')
const WebSocket = require('ws')
// https://stackoverflow.com/a/16608045/131146
var isObject = function(a) {
return (!!a) && (a.constructor === Object);
}
var isArray = function(a) {
return (!!a) && (a.constructor === Array);
}
var god, logger
class ThingStatus {
static ignored = new ThingStatus('ignored', 3) // this thing is ignored by the staleness-check
static uninitialized = new ThingStatus('uninitialized', 2) // we have no value yet (but might have asked for it already)
static alive = new ThingStatus('alive', 4) // we have a value, and it's not stale
static stale = new ThingStatus('stale', 1) // we have a value, but it hasn't been updated/confirmed for some time (but we poked it when setting this status, and will poke again)
static dead = new ThingStatus('dead', 0) // we haven't heard back from the thing, even after poking (will poke again)
constructor(name, order) {
this.name = name
this.order = order // used for composite things
}
}
class Thing {
static consideredStaleMs = 90 * 1000 // how long after the last update to consider a value stale and start poking
static consideredDeadMs = 120 * 1000 // how long after the last update to consider thing dead (but continue poking)
static pokeIntervalMs = 60 * 1000 // interval to poke stale/dead things
static staleCheckIntervalMs = 15 * 1000 // interval to check for all of the above, used in setInterval()
thingController = undefined // is injected after construction
constructor(id, def, ownLogger) {
this.def = def
if (this.def.id != id) logger.error('Thing id doesn\'t match definition id, something will probably fail somewhere') // TODO
this.logger = ownLogger ? ownLogger: logger
this.god = god
this.status = ThingStatus.uninitialized
this.lastUpdated = 0,
this.lastpoked = 0
// normalizing data
if (this.def.render === false) this.def.render = { hidden: true }
if (!(this.def.render instanceof Object)) this.def.render = {}
}
/** called after all things have been loaded, for initializing references */
init() {
}
/** JSON representation of the current state (extended by subclasses) */
get json() {
return {
id: this.def.id,
lastUpdated: this.lastUpdated,
lastpoked: this.lastpoked,
status: this.status.name,
scenarioStatus: this.getScenarioStatus(),
value: this.getValue(),
}
}
getValue() { return '<abstract>' }
/** JSON representation of the current state plus the thing definition */
get fullJson() {
let json = this.json
json.def = this.def
return json
}
get id() {
return this.def.id
}
// WIP - bring the status calculation from the frontend to the backend. Currently not finished and not used.
getScenarioStatus() {
let currentScenario = this.thingController.getCurrentScenario()
if (!currentScenario) return { isPartOfScenario: false, isAsExpected: true }
let expected = currentScenario.things[this.def.id]
if (!expected) return { isPartOfScenario: false, isAsExpected: true }
let isAsExpected = false
let expectedValues = []
let hideInOverview = false
let value = this.getValue()
if (isObject(expected)) { // complex case - expectation is an object
if (!isObject(value)) {
// expected is an object, but value isn't - assume it's "power"
value = { power: value }
}
// TODO
// define intermediate result - and if it makes sense to have it at all?
return { isWIP: true }
} else { // simple case - expectation is just a value
isAsExpected = (value == expected)
expectedValues = [ expected ]
}
if (this.def.partOfComposite) hideInOverview = true // just assume if it's part of a composite than the composite will include it
return { isPartOfScenario: true, isAsExpected: isAsExpected, expectedValues: expectedValues, hideInOverview: hideInOverview }
}
/** This function is called when a thing-specific action should be triggered, e.g. "switch light on". For most things this sends the appropriate MQTT commands */
onAction(action) {
this.logger.warn('Abstract base class for ' + this.id + ': action not supported')
}
/** internally used to change this.status, propagates the new value to listeners (can be skipped if done manually anyway) */
setstatus(newStatus, propagateChange = true) {
if (this.status != newStatus) {
if (this.status == ThingStatus.dead) this.logger.info(this.def.id + ' is alive again')
this.status = newStatus;
if (propagateChange) god.onThingChanged.forEach(cb => cb(this))
}
}
// called from timer - with now = the current Date() - to check if our value is stale. If yes, pokes the thing
checkAlive(now) {
switch (this.status) {
case ThingStatus.ignored:
// no updating, no poking
break;
case ThingStatus.alive:
if (now - this.lastUpdated > Thing.consideredStaleMs) {
this.setstatus(ThingStatus.stale)
this.logger.debug('Status for ' + this.def.id + ' has gone stale, poking it')
this.poke(now)
}
break;
case ThingStatus.uninitialized:
case ThingStatus.stale:
if (now - this.lastUpdated > Thing.consideredDeadMs) {
this.setstatus(ThingStatus.dead)
this.logger.info(this.def.id + ' appears to be dead :(')
this.poke(now)
}
if (now - this.lastpoked > Thing.pokeIntervalMs) {
this.poke(now)
}
break;
case ThingStatus.dead:
if (now - this.lastpoked > Thing.pokeIntervalMs) {
this.poke(now)
}
break;
default:
this.logger.error('ThingStatus for ' + this.id + ' is invalid: ' + this.status)
this.setstatus(ThingStatus.ignored)
break;
}
}
/** Called from checkAlive() when a thing is considered stale/dead. Should try to provoke the thing to answer something. */
poke(now) {
this.logger.warn('Abstract base class for ' + this.id + ': poking not supported')
this.lastpoked = now
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
class MusicPlayerDaemon extends Thing {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
this.lastState = {}
god.mqtt.addTrigger('tele/' + def.device + '/STATE', def.id, this.onMpdMqttStateUpdate.bind(this))
}
get json() {
return { ...super.json,
type: 'MPD',
}
}
getValue() { return this.lastState }
// Callback for MQTT messages for the MPD subsystem
async onMpdMqttStateUpdate(trigger, topic, message, packet) {
let newState = message.toString()
try {
let json = JSON.parse(newState)
newState = json
} catch(e) {
this.logger.error('MQTT: Failed to parse JSON: ' + newState)
}
if (newState.status == 'offline') {
// mpd.js responds, but actual mpd connection is down - treat as 'no answer'
return
}
this.lastState = newState
// calculated values
this.lastState.power = (this.lastState.status.state == 'play') ? 'ON' : 'OFF'
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
god.onThingChanged.forEach(cb => cb(this))
}
onAction(action) {
this.logger.debug('Action for %s: %o', this.def.id, action)
let translate = { 'play': 'play', 'pause': 'pause', 'toggle': 'toggle' }
let mpdAction = translate[action]
if (mpdAction) {
god.mqtt.publish('cmnd/' + this.def.device + '/' + mpdAction, '1')
}
}
poke(now) {
god.mqtt.publish('cmnd/' + this.def.device + '/status', '')
this.lastpoked = now
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
class LyrionMusicPlayer extends Thing {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
this.playerId = this.def.playerId
this.lastState = {
volume: 0,
muted: false,
mode: 'unknown', // play, paused, pause, stop
title: '',
}
this.volumeFader = {
startVolume: 0,
endVolume: 0,
resetVolume: 0,
targetState: undefined,
callback: undefined,
startDate: 0,
endDate: 0
}
god.lms_controller.connect()
god.lms_controller.on('playerStatus', this.onPlayerStatus.bind(this))
god.lms_controller.on('data', this.onNotification.bind(this))
}
get json() {
return { ...super.json,
type: 'LMS',
}
}
getValue() { return this.lastState }
async onPlayerStatus({ playerId, playerStatus }) {
if (playerId != this.def.playerId) {
// player data for a different client - ignored
// TODO we COULD use this to try to identify 'our' player if the playerId is unknown in the config
this.logger.silly("Player '%s' with playerId '%s' ignored data meant for playerId '%s'", this.def.id, this.def.playerId, playerId)
return
}
this.faderTimerId = undefined
this.lastState = {
clientName: playerStatus.clientName,
clientModel: playerStatus.clientModel,
clientModelname: playerStatus.clientModelname,
clientIp: playerStatus.player_ip,
mode: playerStatus.mode, // expected: play, paused, pause, stop
volume: playerStatus['mixer volume'],
title: playerStatus.current_title,
muted: false, // I guess?
}
this.logger.debug("Player '%s' status: mode=%s, volume=%s, title='%s'", this.def.id, this.lastState.mode, this.lastState.volume, this.lastState.title)
this.lastUpdated = new Date()
this.setstatus(ThingStatus.alive, false)
god.onThingChanged.forEach(cb => cb(this))
}
onNotification({ playerId, parts, line }) {
if (!playerId) {
this.onGlobalNotification(parts, line)
} else if (playerId == this.def.playerId) {
this.onPlayerNotification(parts, line)
} else {
// player data for a different client - ignored
this.logger.silly("Player '%s' with playerId '%s' ignored data meant for playerId '%s'", this.def.id, this.def.playerId, playerId)
}
}
onGlobalNotification(parts, line) {
const cmd = parts[0]
let handled = false
if (cmd === 'rescan' && parts[1] === 'done') {
this.logger.debug("Player '%s' (global): LMS rescan done", this.def.id)
handled = true
}
if (cmd === 'library' && parts[1] === 'changed') {
this.logger.debug("Player '%s' (global): LMS library changed", this.def.id)
handled = true
}
if (cmd === 'listen') {
this.logger.debug("Player '%s' (global): listen %s", this.def.id, parts[1])
handled = true
}
if (cmd === 'material-skin') { // ignore all those
handled = true
}
if (cmd === 'prefset' || cmd === 'favorites changed' || cmd === 'playergroups') { // ignore all those
handled = true
}
if (!handled) {
this.logger.warn("Player '%s' (global): unhandled LMS notification: '%s'", this.def.id, parts.join(' '))
return
}
// note: nothing here yet which is of interest, therefor no need to call-back our watchers
}
async onPlayerNotification(parts, line) {
const playerId = parts[0]
const cmd = parts[1]
let newThingStatus = ThingStatus.alive
let handled = false
// TODO I've also seen (on iPad) first "mixer volume xx" once, then "prefset server volume xx"
if (cmd === 'mixer' && parts[2] === 'volume') {
if (parts[3][0] === '+' || Number(parts[3]) == 0) {
this.logger.debug("Player '%s': volume non-change, as reply to poking", this.def.id)
} else {
const isRelative = (parts[3][0] === '+' || parts[3][0] === '-')
const volume = Number(parts[3])
if (isRelative) {
this.lastState.volume += volume
this.logger.debug("Player '%s' changed volume by %d to %d", this.def.id, volume, this.lastState.volume)
} else {
this.logger.debug("Player '%s' changed volume from %d to %d", this.def.id, this.lastState.volume, volume)
this.lastState.volume = volume
}
}
handled = true
}
if (cmd === 'mixer' && parts[2] === 'muting') {
const muted = parts[3] === '1'
this.logger.debug("Player '%s' changed muting %d -> %d", this.def.id, this.lastState.muted, muted)
this.lastState.muted = muted
handled = true
}
if (cmd === 'pause') {
// comes together with playlist pause 1
this.logger.info("Player '%s' is now paused", this.def.id)
this.lastState.mode = 'pause'
}
if (cmd === 'play') {
// comes together with playlist jump 0
this.logger.info("Player '%s' is now playing", this.def.id)
this.lastState.mode = 'play'
}
if (cmd === 'playlist') {
const sub = parts[2];
if (sub === 'newsong') {
const title = parts[3] || '';
const playlistIndex = parts[4] ? Number(parts[4]) : undefined;
this.logger.info("Player '%s' now plays '%s'", this.def.id, title)
this.lastState.title = title
this.lastState.mode = 'play' // assume playing
handled = true
} else if (sub === 'pause') {
const mode = parts[3] === '1' ? 'pause' : 'play'
this.logger.info("Player '%s' is now %s", this.def.id, mode)
this.lastState.mode = mode
handled = true
} else if (sub === 'stop') {
const mode = 'stop'
this.logger.info("Player '%s' is now %s", this.def.id, mode)
this.lastState.mode = mode
handled = true
} else if (sub === 'jump') {
// ignored
handled = true
} else if (sub === 'open') {
// TODO "playlist open <url>" came after restart after pausing (twice)
handled = true
} else if (sub === 'addtracks') {
// ignored
handled = true
}
}
if (cmd === 'client') {
const sub = parts[2];
if (sub === 'new') {
// TODO
const status = await god.lms_controller.lms.trigggerPlayerStatusRefresh(playerId);
this.logger.info("Player %s connected", this.def.id)
handled = true
} else if (sub === 'disconnect') {
newThingStatus = ThingStatus.dead
this.logger.info("Player %s disconnected", this.def.id)
handled = true
} else if (sub === 'reconnect') {
// TODO
const status = await god.lms_controller.lms.trigggerPlayerStatusRefresh(playerId);
this.logger.info("Player %s reconnected", this.def.id)
}
}
if (cmd === 'menustatus' || cmd === 'prefset' || cmd === 'playerpref' || cmd === 'alarm') { // ignore all those
handled = true
}
if (!handled) {
this.logger.debug("Player '%s': unhandled LMS notification: '%s'", this.def.id, parts.join(' '))
return
}
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(newThingStatus, false)
god.onThingChanged.forEach(cb => cb(this))
}
async fadePause(iDelayTimeSec) {
if (this.lastState.mode == "play" || (this.faderTimerId && this.volumeFader.targetState == "play")) {
// quick fadeoff
if (this.faderTimerId && (this.volumeFader.targetState == "pause" || this.volumeFader.targetState == "stop")) {
iDelayTimeSec = 1
}
this.volumeFader.startVolume = this.lastState.volume
this.volumeFader.endVolume = 0
this.volumeFader.targetState = "pause"
if (!this.faderTimerId) { this.volumeFader.resetVolume = this.lastState.volume }
this.volumeFader.callback = (async function() {
this.logger.info("Fadedown completed, now set back to " + this.volumeFader.targetState)
if (this.volumeFader.targetState == "pause") await god.lms_controller.lms.pause(this.playerId)
if (this.volumeFader.targetState == "stop") await god.lms_controller.lms.stop(this.playerId)
await god.lms_controller.lms.setVolume(this.playerId, this.volumeFader.resetVolume)
}).bind(this)
this.startFading(iDelayTimeSec)
var msg = "Starting fade-down (from " + this.lastState.volume + ", reset to " + this.volumeFader.resetVolume + ", in " + iDelayTimeSec + " sec)"
return msg
} else {
return "not playing"
}
}
startFading(iDelayTimeSec) {
this.logger.debug("Start fading")
clearInterval(this.faderTimerId)
this.volumeFader.startDate = Date.now()
this.volumeFader.endDate = this.volumeFader.startDate + iDelayTimeSec * 1000
this.faderTimerId = setInterval((async function() {
if (this.volumeFader.endDate <= Date.now()) {
clearInterval(this.faderTimerId)
this.faderTimerId = 0
this.logger.debug("Fading volume, last step: volume=%s", this.volumeFader.endVolume)
await god.lms_controller.lms.setVolume(this.playerId, this.volumeFader.endVolume)
if (this.volumeFader.callback) this.volumeFader.callback()
return
}
var deltaT = this.volumeFader.endDate - this.volumeFader.startDate
var p = (Date.now() - this.volumeFader.startDate) / deltaT
p = p > 1 ? 1 : p
var deltaV = this.volumeFader.endVolume - this.volumeFader.startVolume
var newV = Math.floor(this.volumeFader.startVolume + deltaV * p)
this.logger.debug("Fading volume, current step: volume=%s", newV)
await god.lms_controller.lms.setVolume(this.playerId, newV)
}).bind(this), 50)
}
async onAction(action) {
// TODO
this.logger.debug('Action for %s: %o', this.def.id, action)
let parts = action.split(' ')
action = parts[0]
switch(action) {
case '0': // from Tasmota "lair - hoard-light", if lights were off before toggling
case 'play':
try {
await god.lms_controller.lms.play(this.playerId)
} catch(e) {
this.logger.error("Player %s: error on play: %o", this.def.id, e)
}
break
case '1': // from Tasmota "lair - hoard-light", if lights were on before toggling
case 'pause':
try {
if (parts[1]) this.fadePause(parts[1])
else await god.lms_controller.lms.pause(this.playerId)
} catch(e) {
this.logger.error("Player %s: error on pause: %o", this.def.id, e)
}
break
case 'stop':
try {
await god.lms_controller.lms.stop(this.playerId)
} catch(e) {
this.logger.error("Player %s: error on stop: %o", this.def.id, e)
}
break
case 'vol+':
try {
await god.lms_controller.lms.changeVolume(this.playerId, parts[1])
} catch(e) {
this.logger.error("Player %s: error on changeVolume(%o): %o", this.def.id, parts[1], e)
}
break
case 'vol-':
try {
await god.lms_controller.lms.changeVolume(this.playerId, -parts[1])
} catch(e) {
this.logger.error("Player %s: error on changeVolume(%o): %o", this.def.id, parts[1], e)
}
break
case 'setvol':
try {
await god.lms_controller.lms.setVolume(this.playerId, parts[1])
} catch(e) {
this.logger.error("Player %s: error on setVolume(%o): %o", this.def.id, parts[1], e)
}
break
}
}
async poke(now) {
// nothing to do here - LMS connection is established automatically, LMS clients are handled by LMS itself
try {
await god.lms_controller.lms.changeVolume(this.playerId, 0)
} catch(e) {
this.logger.debug("Player %s: error while trying to poke: %o", this.def.id, e)
}
this.lastpoked = now
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
class TasmotaThing extends Thing {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
// TODO copy TasmotaSwitch to TasmotaStrip, with value { power, channel2 }
// how to best do this with re-using existing code?
// also, grag3.html needs to correctly parse this
class TasmotaSwitch extends TasmotaThing {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
let mqttTopic = 'stat/' + def.device + '/' + def.power
this.logger.debug('Registering TasmotaSwitch %s (%s)', def.id, mqttTopic)
this.value = undefined
this.targetValue = undefined
// register to status changes
this.onMqttTasmotaSwitch = this.onMqttTasmotaSwitch.bind(this)
god.mqtt.addTrigger(mqttTopic, def.id, this.onMqttTasmotaSwitch)
god.mqtt.addTrigger('tele/' + def.device + '/STATE', def.id, this.onMqttTasmotaSwitch)
god.mqtt.addTrigger('stat/' + def.device + '/RESULT', def.id, this.onMqttTasmotaSwitch)
god.mqtt.addTrigger('stat/' + def.device + '/STATUS11', def.id, this.onMqttTasmotaSwitch)
// trigger retrieval of current status
this.poke(new Date())
}
poke(now) {
let topic = 'cmnd/' + this.def.device + '/status'
let value = '11'
this.logger.debug('Poking ' + this.def.id + ' with: ' + topic + ' = ' + value)
god.mqtt.publish(topic, value)
this.lastpoked = now
}
get json() {
return { ...super.json,
type: 'TasmotaSwitch',
targetValue: this.targetValue,
}
}
getValue() { return this.value }
// Callback for MQTT messages for tasmota-based switches
async onMqttTasmotaSwitch(trigger, topic, message, packet) {
let def = this.thingController.thingDefinitions[trigger.id]
let propagateChange = false
let newValue = message.toString()
try {
let json = JSON.parse(newValue)
newValue = json
} catch(e) {}
if (topic == 'stat/' + def.device + '/RESULT') { // an action has set a new target power value (unfortunately this is also sent on bootup, so can't be used for crash detection)
if (newValue.hasOwnProperty(def.power)) {
newValue = newValue[def.power]
let oldTargetValue = this.targetValue
this.targetValue = newValue
this.logger.debug('%s target value changed (RESULT): %o -> %o', def.id, oldTargetValue, newValue)
propagateChange = true
} else {
this.logger.silly('Tasmota %s sent RESULT which is uninteresting for thing %s which is looking for %s: %o', topic, def.id, def.power, newValue)
}
} else if (topic == 'stat/' + def.device + '/STATUS11') { // generic status information, which might contain our power value, and which might be un/changed
if (!newValue['StatusSTS']) {
this.logger.error('Tasmota %s STATUS11 does not include expected "StatusSTS"', topic)
} else if (newValue['StatusSTS'].hasOwnProperty(def.power)) {
newValue = newValue['StatusSTS'][def.power]
let oldValue = this.value
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
if (oldValue != newValue) {
this.value = newValue
this.logger.debug('%s value changed (StatusSTS): %o -> %o (target: %o)', def.id, oldValue, newValue, this.targetValue)
} else {
this.logger.silly('%s value unchanged (StatusSTS): %o (target: %o)', def.id, oldValue, this.targetValue)
}
} else {
this.logger.debug('Tasmota %s StatusSTS does not include %s for thing %s: %o', topic, def.power, def.id, newValue)
}
} else if (topic == 'tele/' + def.device + '/STATE') { // state information
if (newValue.hasOwnProperty(def.power)) {
newValue = newValue[def.power]
let oldValue = this.value
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
if (oldValue != newValue) {
this.value = newValue
this.logger.debug('%s value changed (tele/STATE): %o -> %o (target: %o)', def.id, oldValue, newValue, this.targetValue)
} else {
this.logger.silly('%s value unchanged (tele/STATE): %o (target: %o)', def.id, oldValue, this.targetValue)
}
} else {
this.logger.debug('Tasmota %s tele/STATE does not include %s for thing %s: %o', topic, def.power, def.id, newValue)
}
} else if (topic == 'stat/' + def.device + '/' + def.power) { // state has been changed
let oldValue = this.value
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
if (oldValue != newValue) {
this.value = newValue
this.logger.debug('%s value changed (stat): %o -> %o (target: %o)', def.id, oldValue, newValue, this.targetValue)
} else {
this.logger.silly('%s value unchanged (stat): %o (target: %o)', def.id, oldValue, this.targetValue)
}
} else {
this.logger.silly('Mqtt callback called for %s, but %s is not interested in this.', topic, def.id)
}
if (propagateChange) {
god.onThingChanged.forEach(cb => cb(this))
}
}
onAction(action) {
this.logger.debug('Action for %s: %o', this.def.id, action)
if (['ON', 'OFF', 'TOGGLE'].includes(action)) {
this.targetValue = action
god.mqtt.publish('cmnd/' + this.def.device + '/' + this.def.power, action)
}
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
// TODO WIP
class TasmotaSensor extends TasmotaThing {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
let mqttTopic = 'stat/' + def.device + '/' + def.power
this.logger.debug('Registering TasmotaSensor %s (%s)', def.id, mqttTopic)
this.value = undefined
this.targetValue = undefined
// register to status changes
this.onMqttTasmotaSensor = this.onMqttTasmotaSensor.bind(this)
god.mqtt.addTrigger(mqttTopic, def.id, this.onMqttTasmotaSensor)
god.mqtt.addTrigger('tele/' + def.device + '/STATE', def.id, this.onMqttTasmotaSensor)
god.mqtt.addTrigger('stat/' + def.device + '/SENSOR', def.id, this.onMqttTasmotaSensor)
god.mqtt.addTrigger('stat/' + def.device + '/STATUS11', def.id, this.onMqttTasmotaSensor)
// trigger retrieval of current status
this.poke(new Date())
}
poke(now) {
let topic = 'cmnd/' + this.def.device + '/status'
let value = '11'
this.logger.debug('Poking ' + this.def.id + ' with: ' + topic + ' = ' + value)
god.mqtt.publish(topic, value)
this.lastpoked = now
}
get json() {
return { ...super.json,
type: 'TasmotaSensor',
targetValue: this.targetValue,
}
}
getValue() { return this.value }
// Callback for MQTT messages for tasmota-based sensors
// TODO WIP copied from TasmotaSwitch
async onMqttTasmotaSensor(trigger, topic, message, packet) {
let def = this.thingController.thingDefinitions[trigger.id]
let propagateChange = false
let newValue = message.toString()
try {
let json = JSON.parse(newValue)
newValue = json
} catch(e) {}
if (topic == 'stat/' + def.device + '/RESULT') { // an action has set a new target power value (unfortunately this is also sent on bootup, so can't be used for crash detection)
if (newValue.hasOwnProperty(def.power)) {
newValue = newValue[def.power]
let oldTargetValue = this.targetValue
this.targetValue = newValue
this.logger.debug('%s target value changed (RESULT): %o -> %o', def.id, oldTargetValue, newValue)
propagateChange = true
} else {
this.logger.silly('Tasmota %s sent RESULT which is uninteresting for thing %s which is looking for %s: %o', topic, def.id, def.power, newValue)
}
} else if (topic == 'stat/' + def.device + '/STATUS11') { // generic status information, which might contain our power value, and which might be un/changed
if (!newValue['StatusSTS']) {
this.logger.error('Tasmota %s STATUS11 does not include expected "StatusSTS"', topic)
} else if (newValue['StatusSTS'].hasOwnProperty(def.power)) {
newValue = newValue['StatusSTS'][def.power]
let oldValue = this.value
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
if (oldValue != newValue) {
this.value = newValue
this.logger.debug('%s value changed (StatusSTS): %o -> %o (target: %o)', def.id, oldValue, newValue, this.targetValue)
} else {
this.logger.silly('%s value unchanged (StatusSTS): %o (target: %o)', def.id, oldValue, this.targetValue)
}
} else {
this.logger.debug('Tasmota %s StatusSTS does not include %s for thing %s: %o', topic, def.power, def.id, newValue)
}
} else if (topic == 'tele/' + def.device + '/STATE') { // state information
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
} else if (topic == 'stat/' + def.device + '/' + def.power) { // state has been changed
let oldValue = this.value
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
if (oldValue != newValue) {
this.value = newValue
this.logger.debug('%s value changed (stat): %o -> %o (target: %o)', def.id, oldValue, newValue, this.targetValue)
} else {
this.logger.silly('%s value unchanged (stat): %o (target: %o)', def.id, oldValue, this.targetValue)
}
} else {
this.logger.silly('Mqtt callback called for %s, but %s is not interested in this.', topic, def.id)
}
if (propagateChange) {
god.onThingChanged.forEach(cb => cb(this))
}
}
onAction(action) {
// Sensors have nothing. Or do they?
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
class AIonEdge extends Thing {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
let mqttTopic = def.device + '/main/json'
this.logger.debug('Registering AIonEdge %s (%s)', def.id, mqttTopic)
this.value = undefined
// register to status changes
god.mqtt.addTrigger(mqttTopic + '/#', def.id, this.onMqtt.bind(this))
// trigger retrieval of current status
this.poke(new Date())
}
poke(now) {
// TODO don't know how to poke
this.lastpoked = now
}
get json() {
return { ...super.json,
type: 'AIonEdge',
}
}
getValue() { return this.value }
// { "value": "183.7062", "raw": "00183.7062", "pre": "183.7062", "error": "no error", "rate": "0.000000", "timestamp": "2023-11-11T18:37:39+0100" }
async onMqtt(trigger, topic, message, packet) {
let def = this.thingController.thingDefinitions[trigger.id]
let propagateChange = false
let newValue = message.toString()
try {
let json = JSON.parse(newValue)
newValue = json
} catch(e) {}
if (topic == mqttTopic) {
newValue = newValue['value']
let oldValue = this.value
this.lastUpdated = new Date() // update timestamp even if the value is unchanged
this.setstatus(ThingStatus.alive, false)
propagateChange = true
if (oldValue != newValue) {
this.value = newValue
this.logger.debug('%s value changed: %o -> %o', def.id, oldValue, newValue)
} else {
this.logger.debug('%s value unchanged: %o -> %o', def.id, oldValue, newValue)
}
} else {
this.logger.silly('Mqtt callback called for %s, but %s is not interested in this.', topic, def.id)
}
if (propagateChange) {
god.onThingChanged.forEach(cb => cb(this))
}
}
onAction(action) {
// Sensors have nothing. Or do they?
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
// Raspberry-based proprietary Ledstrip
class LedstripJs extends TasmotaSwitch {
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
}
poke(now) {
let topic = 'cmnd/' + this.def.device + '/POWER'
let value = ''
this.logger.debug('Poking ' + this.def.id + ' with: ' + topic + ' = ' + value)
god.mqtt.publish(topic, value)
this.lastpoked = now
}
}
// ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
class WLED extends Thing {
socket = null
state = {}
closedRetry = 0
constructor(id, def, ownLogger) {
super(id, def, ownLogger)
this.connectWs()
}
connectWs() {
this.socket = new WebSocket('ws://' + this.def.device + '/ws')
this.logger.debug('Connecting to %s via websocket', this.def.name);
this.socket.on('open', () => {
this.logger.info('Connected to %s via websocket', this.def.name);
this.closedRetry = 0
})
this.socket.on('message', this.onMessage.bind(this))
this.socket.on('close', (code, reason) => {
this.closedRetry++
if (this.closedRetry < 5) {
this.logger.error('Websocket to %s closed: %s %s (retrying)', this.def.name, code, reason);
this.connectWs()
} else {
this.logger.error('Websocket to %s closed: %s %s (retry limit reached)', this.def.name, code, reason);
}
})
this.socket.on('error', error => {
this.logger.error('Websocket to %s error: %s', this.def.name, error);
// TODO what now?
})
}
getValue() {
return this.state?.on ? "ON" : "OFF"
}
async onMessage(data, isBinary) {
let propagateChange = false
try {
let wled = JSON.parse(data)
this.logger.debug('%s websocket received: %o', this.def.name, wled);
this.setstatus(ThingStatus.alive, false)
if (wled.success === true) return // response if we poke it with "v:false"
if (!wled.state) {
this.logger.warn('"state" missing in wled="%o"', wled)
return
}
if (this.state.on != wled.state.on) propagateChange = true // only update UI for relevant state changes
this.state = wled.state
} catch(e) {
this.logger.error('%s websocket parsing error (isBinary=%s): %s -> data is %o', this.def.name, isBinary, e, String(data));
}
if (propagateChange) {
god.onThingChanged.forEach(cb => cb(this))
}
}
poke(now) {
// TODO if offline, re-establish connection?
switch (this.socket.readyState) {
case WebSocket.CONNECTING: break // we'll get called soon enough
case WebSocket.OPEN:
this.logger.debug('Poking %s', this.def.id)
this.socket.send(JSON.stringify({"v":true}))
this.lastpoked = now
break;
case WebSocket.CLOSING: break // just wait for the next round...
case WebSocket.CLOSED:
this.connectWs()
break;
default:
this.logger.warn('%s websocket readyState=%s unrecognized', this.def.name, this.socket.readyState)
}