-
-
Notifications
You must be signed in to change notification settings - Fork 210
/
Gateway.js
executable file
·1696 lines (1465 loc) · 50.8 KB
/
Gateway.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
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
/* eslint-disable no-case-declarations */
/* eslint-disable no-prototype-builtins */
/* eslint-disable no-eval */
/* eslint-disable one-var */
'use strict'
const fs = require('fs')
const path = require('path')
const reqlib = require('app-root-path').require
const utils = reqlib('/lib/utils.js')
const EventEmitter = require('events')
const { AlarmSensorType } = require('zwave-js')
const { CommandClasses } = require('@zwave-js/core')
const { socketEvents } = reqlib('/lib/SocketManager.js')
const Constants = reqlib('/lib/Constants.js')
const logger = reqlib('/lib/logger.js').module('Gateway')
const inherits = require('util').inherits
const hassCfg = reqlib('/hass/configurations.js')
const hassDevices = reqlib('/hass/devices.js')
const version = reqlib('package.json').version
const NODE_PREFIX = 'nodeID_'
// const GW_TYPES = ['valueID', 'named', 'manual']
// const PY_TYPES = ['time_value', 'zwave_value', 'just_value']
const CUSTOM_DEVICES = reqlib('config/app.js').storeDir + '/customDevices'
let allDevices = hassDevices // will contain customDevices + hassDevices
// watcher initiates a watch on a file. if this fails (e.g., because the file
// doesn't exist), instead watch the directory. If the directory watch
// triggers, cancel it and try to watch the file again. Meanwhile spam `fn()`
// on any change, trusting that it's idempotent.
const watchers = new Map()
const watch = (filename, fn) => {
try {
watchers.set(
filename,
fs.watch(filename, e => {
fn()
if (e === 'rename') {
watchers.get(filename).close()
watch(filename, fn)
}
})
)
} catch {
watchers.set(
filename,
fs.watch(path.dirname(filename), (e, f) => {
if (!f || f === 'customDevices.js' || f === 'customDevices.json') {
watchers.get(filename).close()
watch(filename, fn)
fn()
}
})
)
}
}
const customDevicesJsPath = utils.joinPath(true, CUSTOM_DEVICES) + '.js'
const customDevicesJsonPath = utils.joinPath(true, CUSTOM_DEVICES) + '.json'
let lastCustomDevicesLoad = null
// loadCustomDevices attempts to load a custom devices file, preferring `.js`
// but falling back to `.json` only if a `.js` file does not exist. It stores
// a sha of the loaded data, and will skip re-loading any time the data has
// not changed.
const loadCustomDevices = () => {
let loaded = ''
let devices = null
try {
if (fs.existsSync(customDevicesJsPath)) {
loaded = customDevicesJsPath
devices = reqlib(CUSTOM_DEVICES)
} else if (fs.existsSync(customDevicesJsonPath)) {
loaded = customDevicesJsonPath
devices = JSON.parse(fs.readFileSync(loaded))
} else {
return
}
} catch (error) {
logger.error(`failed to load ${loaded}:`, error)
return
}
const sha = require('crypto')
.createHash('sha256')
.update(JSON.stringify(devices))
.digest('hex')
if (lastCustomDevicesLoad === sha) {
return
}
logger.info(`loading custom devices from ${loaded}`)
lastCustomDevicesLoad = sha
allDevices = Object.assign({}, hassDevices, devices)
logger.info(
`Loaded ${Object.keys(devices).length} custom Hass devices configurations`
)
}
loadCustomDevices()
watch(customDevicesJsPath, loadCustomDevices)
watch(customDevicesJsonPath, loadCustomDevices)
/**
* The constructor
*/
function Gateway (config, zwave, mqtt) {
if (!(this instanceof Gateway)) {
return new Gateway(config)
}
this.config = config || { type: 1 }
// clients
this.mqtt = mqtt
this.zwave = zwave
EventEmitter.call(this)
}
inherits(Gateway, EventEmitter)
Gateway.prototype.start = async function () {
// gateway configuration
this.config.values = this.config.values || []
// Object where keys are topic and values can be both zwave valueId object
// or a valueConf if the topic is a broadcast topic
this.topicValues = {}
this.discovered = {}
// topic levels for subscribes using wildecards
this.topicLevels = []
if (this.mqtt) {
this.mqtt.on('writeRequest', onWriteRequest.bind(this))
this.mqtt.on('broadcastRequest', onBroadRequest.bind(this))
this.mqtt.on('apiCall', onApiRequest.bind(this))
this.mqtt.on('hassStatus', onHassStatus.bind(this))
this.mqtt.on('brokerStatus', onBrokerStatus.bind(this))
}
if (this.zwave) {
this.zwave.on('valueChanged', onValueChanged.bind(this))
this.zwave.on('nodeStatus', onNodeStatus.bind(this))
this.zwave.on('notification', onNotification.bind(this))
this.zwave.on('scanComplete', onScanComplete.bind(this))
this.zwave.on('nodeSceneEvent', onNodeSceneEvent.bind(this))
this.zwave.on('nodeRemoved', onNodeRemoved.bind(this))
if (this.config.sendEvents) {
this.zwave.on('event', onEvent.bind(this))
}
// this is async but doesn't need to be awaited
this.zwave.connect()
} else {
logger.error('Zwave settings are not valid')
}
}
/**
* Catch all Zwave events
*/
function onEvent (emitter, eventName, ...args) {
const topic = `${this.mqtt.eventsPrefix}/${
this.mqtt.clientID
}/${emitter}/${eventName.replace(/\s/g, '_')}`
this.mqtt.publish(topic, { data: args }, { qos: 1, retain: false })
}
/**
* Zwave event triggered when a scan is completed
*/
// eslint-disable-next-line no-unused-vars
function onScanComplete (nodes) {}
/**
* Zwave event triggered when a node is removed
*/
function onNodeRemoved (node) {
const prefix = node.id + '-'
// delete discovered values
for (const id in this.discovered) {
if (id.startsWith(prefix)) {
delete this.discovered[id]
}
}
}
/**
* Zwave event triggered when there is a node or scene event
*/
function onNodeSceneEvent (event, node, code) {
let topic = this.nodeTopic(node)
if (event === 'node') {
topic += '/event'
} else if (event === 'scene') {
topic += '/scene/event'
} else {
return
}
let data
if (this.config.payloadType === 2) data = code
else data = { time: Date.now(), value: code }
this.mqtt.publish(topic, data, { qos: 1, retain: false })
}
/**
* Zwave event triggered when a value changes
*/
function onValueChanged (valueId, node, changed) {
valueId.lastUpdate = Date.now()
// emit event to socket
if (this.zwave) {
this.zwave.sendToSocket(socketEvents.valueUpdated, valueId)
}
const isDiscovered = this.discovered[valueId.id]
// check if this value isn't discovered yet (values added after node is ready)
if (this.config.hassDiscovery && !isDiscovered) {
this.discoverValue(node, valueId.id.replace(valueId.nodeId + '-', ''))
}
const result = this.valueTopic(node, valueId, true)
if (!result) return
// if there is a valid topic for this value publish it
const topic = result.topic
const valueConf = result.valueConf
// Parse valueId value and create the payload
let tmpVal = valueId.value
if (valueConf) {
if (isValidOperation(valueConf.postOperation)) {
tmpVal = eval(valueId.value + valueConf.postOperation)
}
if (valueConf.parseSend) {
const parsedVal = evalFunction(valueConf.sendFunction, valueId, tmpVal)
if (parsedVal != null) {
tmpVal = parsedVal
}
}
}
// Check if I need to update discovery topics of this device
if (changed && valueId.list && this.discovered[valueId.id]) {
const hassDevice = this.discovered[valueId.id]
const isOff = hassDevice.mode_map
? hassDevice.mode_map.off === valueId.value
: false
if (hassDevice && hassDevice.setpoint_topic && !isOff) {
const setId = hassDevice.setpoint_topic[valueId.value]
if (setId && node.values[setId]) {
// check if the setpoint topic has changed
const setpoint = node.values[setId]
const setTopic = this.mqtt.getTopic(this.valueTopic(node, setpoint))
if (setTopic !== hassDevice.discovery_payload.temperature_state_topic) {
hassDevice.discovery_payload.temperature_state_topic = setTopic
hassDevice.discovery_payload.temperature_command_topic =
setTopic + '/set'
this.publishDiscovery(hassDevice, node.id)
}
}
}
}
let data
switch (this.config.payloadType) {
case 1: // entire zwave valueId object
data = copy(valueId)
data.value = tmpVal
break
case 2: // just value
data = tmpVal
break
default:
data = { time: Date.now(), value: tmpVal }
}
if (this.config.includeNodeInfo && typeof data === 'object') {
data.nodeName = node.name
data.nodeLocation = node.loc
}
// valueId is writeable, subscribe for updates
if (valueId.writeable && !this.topicValues[topic]) {
const levels = topic.split('/').length
if (this.topicLevels.indexOf(levels) < 0) {
this.topicLevels.push(levels)
this.mqtt.subscribe(
'+'
.repeat(levels)
.split('')
.join('/')
)
}
// I need to add the conf to the valueId but I don't want to edit
// original valueId object so I create a copy
if (valueConf) {
valueId = copy(valueId)
valueId.conf = valueConf
}
this.topicValues[topic] = valueId
}
this.mqtt.publish(topic, data)
}
function onNotification (node, notificationLabel, parameters) {
const topic =
this.nodeTopic(node) +
'/notification/' +
this.mqtt.cleanName(notificationLabel)
let data
parameters = parameters ? parameters.toString() : null
if (this.config.payloadType === 2) {
data = parameters
} else {
data = { time: Date.now(), value: parameters }
}
this.mqtt.publish(topic, data)
}
function onNodeStatus (node) {
if (node.ready && this.config.hassDiscovery) {
for (const id in node.hassDevices) {
if (node.hassDevices[id].persistent) {
this.publishDiscovery(node.hassDevices[id], node.id)
}
}
// check if there are climates to discover
this.discoverClimates(node)
const nodeDevices = allDevices[node.deviceId] || []
nodeDevices.forEach(device => this.discoverDevice(node, device))
// discover node values (that are not part of a device)
for (const id in node.values) {
this.discoverValue(node, id)
}
}
// TODO: Zwavejs doesn't support polling right now
// if (node.ready) {
// // enable poll and /or verify changes if required
// var values = this.config.values.filter(
// v => (v.enablePoll || v.verifyChanges) && v.device === node.deviceId
// )
// for (var i = 0; i < values.length; i++) {
// // don't edit the original object, copy it
// var v = copy(values[i].value)
// v.nodeId = node.id
// try {
// if (values[i].verifyChanges) {
// this.zwave.callApi('setChangeVerified', v, true)
// }
// if (values[i].enablePoll) {
// if (!this.zwave.client.isPolled(v)) {
// this.zwave.callApi('enablePoll', v, values[i].pollIntensity || 1)
// }
// } else if (this.zwave.client.isPolled(v)) {
// this.zwave.callApi('disablePoll', v)
// }
// } catch (error) {
// const op = values[i].verifyChanges ? 'verify changes' : 'enable poll'
// logger.error(`Error while call ${op} ${error.message}`)
// }
// }
// }
if (this.zwave) {
this.zwave.sendToSocket(socketEvents.nodeUpdated, node)
}
if (!this.config.ignoreStatus) {
const topic = this.nodeTopic(node) + '/status'
let data
if (this.config.payloadType === 2) {
data = node.ready
} else {
data = { time: Date.now(), value: node.ready, status: node.status }
}
this.mqtt.publish(topic, data)
}
}
function onBrokerStatus (online) {
if (online) {
this.rediscoverAll()
}
}
function onHassStatus (online) {
logger.info(`Home Assistant is ${online ? 'ONLINE' : 'OFFLINE'}`)
if (online) {
this.rediscoverAll()
}
}
async function onApiRequest (topic, apiName, payload) {
if (this.zwave) {
const args = payload.args || []
const result = await this.zwave.callApi(apiName, ...args)
this.mqtt.publish(topic, result)
} else {
logger.error(`Requested Zwave api ${apiName} doesn't exist`)
}
}
function onBroadRequest (parts, payload) {
const topic = parts.join('/')
const values = Object.keys(this.topicValues).filter(t => t.endsWith(topic))
if (values.length > 0) {
// all values are the same type just different node,parse the Payload by using the first one
payload = this.parsePayload(
payload,
this.topicValues[values[0]],
this.topicValues[values[0]].conf
)
for (let i = 0; i < values.length; i++) {
this.zwave.writeValue(this.topicValues[values[i]], payload)
}
}
}
function onWriteRequest (parts, payload) {
const valueId = this.topicValues[parts.join('/')]
if (valueId) {
payload = this.parsePayload(payload, valueId, valueId.conf)
this.zwave.writeValue(valueId, payload)
}
}
/**
* Checks if an operation is valid, it must exist and must contains
* only numbers and operators
*/
function isValidOperation (op) {
return op && !/[^0-9.()\-+*/,]/g.test(op)
}
/**
* Evaluate the return value of a custom parse Function
*
* @param {String} code The function code
* @param {Object} valueId The valueId object
* @param {*} value The actual value to parse
* @returns
*/
function evalFunction (code, valueId, value) {
let result = null
try {
/* eslint-disable no-new-func */
const parseFunc = new Function('value', code)
result = parseFunc(value)
} catch (error) {
logger.error(`Error eval function of value ${valueId.id} ${error.message}`)
}
return result
}
/**
* Converts an integer to 2 digits hex number
*
* @param {Number} rgb A decimal value from 0 to 255
* @returns An hex string of 2 chars
*/
function rgbToHex (rgb) {
let hex = Number(rgb).toString(16)
if (hex.length < 2) {
hex = '0' + hex
}
return hex
}
/**
* Get node name from node object
*
* @param {Object} node The Zwave Node Object
* @returns A string in the format [<location>-]<name>, if location doesn't exist it will be ignored, if the node name doesn't exists the node id with node prefix string will be used
*/
function getNodeName (node) {
return (
(node.loc ? node.loc + '-' : '') +
(node.name ? node.name : NODE_PREFIX + node.id)
)
}
/**
* Deep copy of an object
*
* @param {*} obj The object to copy
* @returns The copied object
*/
function copy (obj) {
return JSON.parse(JSON.stringify(obj))
}
/**
* Checks if an object_id is a rgb_dimmer
*
* @param {String} id object id of the hass discovery payload
* @returns true if the discovery payload object id is a rgb_dimmer
*/
function isRgbDimmer (id) {
return id.startsWith('rgb_dimmer')
}
/**
* Get the device Object to send in discovery payload
*
* @param {Object} node A Zwave Node Object
* @param {String} nodeName Node name from getNodeName function
* @returns The Hass device object
*/
function deviceInfo (node, nodeName) {
return {
identifiers: ['zwavejs2mqtt_' + this.zwave.homeHex + '_node' + node.id],
manufacturer: node.manufacturer,
model: node.productDescription + ' (' + node.productLabel + ')',
name: nodeName,
sw_version: node.firmwareVersion || version
}
}
/**
* Get the Hass discovery topic for the specific node and hassDevice
*
* @param {Object} hassDevice The Hass device object configuration
* @param {String} nodeName Node name from getNodeName function
* @returns The topic string for this device discovery
*/
function getDiscoveryTopic (hassDevice, nodeName) {
return `${hassDevice.type}/${nodeName}/${hassDevice.object_id}/config`
}
/**
* Sanitize ids removing chars that could break discovery
*
* @param {String} id The id string
* @returns The sanitized id, lower cases and without spaces
*/
function sanitizeId (id) {
return id.replace(/\s/g, '_').toLocaleLowerCase()
}
/**
* Calculate the correct template string to use for modes templates
* based on gateway settings and mapped mode values
*
* @param {Object} modeMap The Object with mode mapping key : value
* @param {String} defaultValue The default value for the mode
* @returns {String} The template to use for the mode
*/
function getMappedValuesTemplate (modeMap, defaultValue) {
const map = []
// JSON.stringify converts props to strings and this breaks the template
// Error: "0": "off" Working: 0: "off"
for (const key in modeMap) {
map.push(
`${
typeof modeMap[key] === 'number'
? modeMap[key]
: '"' + modeMap[key] + '"'
}: "${key}"`
)
}
return `{{ {${map.join(
','
)}}[value_json.value] | default('${defaultValue}') }}`
}
/**
* Calculate the correct template string to use for templates with state
* list based on gateway settings and mapped mode values
*
* @param {Object} state The object list which is translated to map
* @param {String} defaultValueKey The key to use for default value
* @returns {String} The template to use for the template
*/
function getMappedStateTemplate (state, defaultValueKey) {
const map = []
let defaultValue = 'value_json.value'
for (const listKey in state) {
map.push(
`${
typeof state[listKey].value === 'number'
? state[listKey].value
: '"' + state[listKey].value + '"'
}: "${state[listKey].text}"`
)
if (state[listKey].value === defaultValueKey) {
defaultValue = `'${state[listKey].text}'`
}
}
return `{{ {${map.join(',')}}[value_json.value] | default(${defaultValue}) }}`
}
/**
* Retrives the value of a property from the node valueId
*
* @param {Object} payload discovery payload
* @param {String} prop property name
* @param {Object} node node object
*/
function setDiscoveryValue (payload, prop, node) {
if (typeof payload[prop] === 'string') {
const valueId = node.values[payload[prop]]
if (valueId && valueId.value != null) {
payload[prop] = valueId.value
}
}
}
/**
* Parse the value of the payload received from mqtt
* based on the type of the payload and the gateway config
*/
Gateway.prototype.parsePayload = function (payload, valueId, valueConf) {
try {
payload =
typeof payload === 'object' && payload.hasOwnProperty('value')
? payload.value
: payload
const hassDevice = this.discovered[valueId.id]
// Hass payload parsing
if (hassDevice) {
// parse payload for switches
const isDimmer = isRgbDimmer(hassDevice.object_id)
if (
(valueId.type === 'boolean' || isDimmer) &&
typeof payload === 'string'
) {
if (/\btrue\b|\bon\b|\block\b/gi.test(payload)) payload = true
else if (/\bfalse\b|\boff\b|\bunlock\b/gi.test(payload)) payload = false
}
if (isDimmer) {
// TODO: should we use valueId.max instead of 99 ?
if (typeof payload === 'boolean') {
payload = payload ? 99 : 0
} else if (!isNaN(payload)) {
payload = Math.round((payload / 255) * 99)
}
}
// map modes coming from hass
if (valueId.list && isNaN(payload)) {
// for thermostat_fan_mode command class use the fan_mode_map
if (
valueId.commandClass === CommandClasses['Thermostat Fan Mode'] &&
hassDevice.fan_mode_map
) {
payload = hassDevice.fan_mode_map[payload]
} else if (
valueId.commandClass === CommandClasses['Thermostat Mode'] &&
hassDevice.mode_map
) {
// for other command classes use the mode_map
payload = hassDevice.mode_map[payload]
}
}
if (valueId.commandClass === CommandClasses['Binary Toggle Switch']) {
payload = 1
} else if (
valueId.commandClass === CommandClasses['Multilevel Toggle Switch']
) {
payload = valueId.value > 0 ? 0 : 0xff
} else if (
valueId.commandClass === CommandClasses['Color Switch'] &&
typeof payload === 'string'
) {
const rgb = payload.split(',')
if (rgb.length === 3) {
payload = '#' + rgbToHex(rgb[0]) + rgbToHex(rgb[1]) + rgbToHex(rgb[2])
}
}
}
if (valueId.type === 'any') {
if (payload.type === 'Buffer' && payload.data) {
payload = Buffer.from(payload.data)
} else {
payload = Buffer.from(payload)
}
}
if (valueConf) {
if (isValidOperation(valueConf.postOperation)) {
let op = valueConf.postOperation
// revert operation to write
if (op.includes('/')) op = op.replace(/\//, '*')
else if (op.includes('*')) op = op.replace(/\*/g, '/')
else if (op.includes('+')) op = op.replace(/\+/, '-')
else if (op.includes('-')) op = op.replace(/-/, '+')
payload = eval(payload + op)
}
if (valueConf.parseReceive) {
const parsedVal = evalFunction(
valueConf.receiveFunction,
valueId,
payload
)
if (parsedVal != null) {
payload = parsedVal
}
}
}
} catch (error) {
logger.error(
`Error while parsing payload ${payload} for valueID ${valueId}`
)
}
return payload
}
/**
* Method used to close clients connection, use this before destroy
*/
Gateway.prototype.close = async function () {
this.closed = true
logger.info('Closing Gateway...')
if (this.mqtt) {
await this.mqtt.close()
}
if (this.zwave) {
await this.zwave.close()
}
}
/**
* Calculates the node topic based on gateway settings
*
* @param {NodeObj} node internal node object
* @returns The node topic
*/
Gateway.prototype.nodeTopic = function (node) {
const topic = []
if (node.loc && !this.config.ignoreLoc) topic.push(node.loc)
switch (this.config.type) {
case 2: // manual
case 1: // named
topic.push(node.name ? node.name : NODE_PREFIX + node.id)
break
case 0: // valueid
if (!this.config.nodeNames) {
topic.push(node.id)
} else {
topic.push(node.name ? node.name : NODE_PREFIX + node.id)
}
break
default:
topic.push(NODE_PREFIX + node.id)
}
// clean topic parts
// eslint-disable-next-line no-redeclare
for (let i = 0; i < topic.length; i++) {
topic[i] = this.mqtt.cleanName(topic[i])
}
return topic.join('/')
}
/**
* Calculates the valueId topic based on gateway settings
*
* @param {NodeObj} node Internal node object
* @param {ValueObj} valueId Internal ValueId object
* @param {boolean} returnObject Set this to true to also return the targetTopic and the valueConf
* @returns The value topic string or an object
*/
Gateway.prototype.valueTopic = function (node, valueId, returnObject = false) {
const topic = []
let valueConf
const vID = valueId.id
// check if this value is in configuration values array
const values = this.config.values.filter(v => v.device === node.deviceId)
if (values && values.length > 0) {
valueConf = values.find(v => v.value.id === vID)
}
if (valueConf && valueConf.topic) {
topic.push(node.name ? node.name : NODE_PREFIX + valueId.nodeId)
topic.push(valueConf.topic)
}
let targetTopic
if (returnObject && valueId.targetValue) {
const targetValue = node.values[valueId.targetValue]
if (targetValue) {
targetTopic = this.valueTopic(node, targetValue, false)
}
}
// if is not in configuration values array get the topic
// based on gateway type if manual type this will be skipped
if (topic.length === 0) {
switch (this.config.type) {
case 1: // named
topic.push(node.name ? node.name : NODE_PREFIX + valueId.nodeId)
topic.push(Constants.commandClass(valueId.commandClass))
topic.push('endpoint_' + (valueId.endpoint || 0))
topic.push(valueId.propertyName)
if (valueId.propertyKey) {
topic.push(valueId.propertyKey)
}
break
case 0: // valueid
if (!this.config.nodeNames) {
topic.push(valueId.nodeId)
} else {
topic.push(node.name ? node.name : NODE_PREFIX + valueId.nodeId)
}
topic.push(valueId.commandClass)
topic.push(valueId.endpoint || '0')
topic.push(valueId.property)
if (valueId.propertyKey) {
topic.push(valueId.propertyKey)
}
break
}
}
// if there is a valid topic for this value publish it
if (topic.length > 0) {
// add location prefix
if (node.loc && !this.config.ignoreLoc) topic.unshift(node.loc)
// clean topic parts
for (let i = 0; i < topic.length; i++) {
topic[i] = this.mqtt.cleanName(topic[i])
}
const toReturn = {
topic: topic.join('/'),
valueConf: valueConf,
targetTopic: targetTopic
}
return returnObject ? toReturn : toReturn.topic
} else {
return null
}
}
/**
* Rediscover all hass devices of this node
*
* @param {number} nodeID
*/
Gateway.prototype.rediscoverNode = function (nodeID) {
const node = this.zwave.nodes[nodeID]
if (node) {
// delete all discovered values
onNodeRemoved.call(this, node)
node.hassDevices = {}
// rediscover all values
const nodeDevices = allDevices[node.deviceId] || []
nodeDevices.forEach(device => this.discoverDevice(node, device))
// discover node values (that are not part of a device)
for (const id in node.values) {
this.discoverValue(node, id)
}
this.zwave.sendToSocket(socketEvents.nodeUpdated, node)
}
}
/**
* Disable the discovery of all devices of this node
*
* @param {number} nodeID
*/
Gateway.prototype.disableDiscovery = function (nodeID) {
const node = this.zwave.nodes[nodeID]
if (node && node.hassDevices) {
for (const id in node.hassDevices) {
node.hassDevices[id].ignoreDiscovery = true
}
this.zwave.sendToSocket(socketEvents.nodeUpdated, node)
}
}
/**
* Publish a discovery payload to discover a device in hass using mqtt auto discovery
*
* @param {HassDevice} hassDevice The hass device configuration to use for the discovery
* @param {number} nodeId The node id
* @param {boolean} deleteDevice Enable this to remove the selected device from hass discovery
* @param {boolean} update Update an hass device of a specific node in zwaveClient and send the event to socket
*/
Gateway.prototype.publishDiscovery = function (
hassDevice,
nodeId,
deleteDevice,
update
) {
try {
this.setDiscovery(nodeId, hassDevice, deleteDevice)
// don't discovery this device when ignore is true
if (!hassDevice.ignoreDiscovery) {
if (this.config.payloadType === 2) {
// Payload is set to "Just Value"
const p = hassDevice.discovery_payload
const template =
'value' +
(p.hasOwnProperty('payload_on') && p.hasOwnProperty('payload_off')
? " == 'true'"
: '')
for (const k in p) {
if (typeof p[k] === 'string') {
p[k] = p[k].replace(/value_json\.value/g, template)
}
}
}
this.mqtt.publish(
hassDevice.discoveryTopic,
deleteDevice ? '' : hassDevice.discovery_payload,
{ qos: 0, retain: this.config.retainedDiscovery || false },
this.config.discoveryPrefix
)
}
if (update) {
this.zwave.updateDevice(hassDevice, nodeId, deleteDevice)
}
} catch (error) {
logger.error(`Error while publishing node ${nodeId}: ${error.message}`)
}
}
/**
* Set internal discovery reference of a valueId
*
* @param {number} nodeId The node id
* @param {HassDevice} hassDevice Hass device configuration
* @param {boolean} deleteDevice Remove the device from the map
*/
Gateway.prototype.setDiscovery = function (