-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
606 lines (525 loc) · 17.1 KB
/
index.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
import { MeianSocket, MeianDataHandler, MeianLogger, MeianConnection, MeianStatusDecoder } from 'ialarm'
import { MqttPublisher } from './utils/mqtt-publisher.js'
import { configHandler } from './utils/config-handler.js'
export const ialarmMqtt = (config) => {
const logger = MeianLogger(config.debug ? 'debug' : 'info')
if (!config) {
console.error('Please provide a valid config.json')
process.exit(1)
}
let errorCount = 0
let discovered = false
const publisher = new MqttPublisher(config)
// if we configured 17 zone, there is no need to call GetZone or GetByWay for all 40/128 default zones
const maxZone = Math.max(...config.server.zones)
const commandsLimits = {
GetZone: maxZone,
GetByWay: maxZone,
GetLog: 10 // this is huge (512) and actually not used
}
// single connection for all messages
const socket = new MeianSocket(
config.server.host,
config.server.port,
config.server.username,
config.server.password,
config.verbose ? 'debug' : 'info',
commandsLimits
)
function connectToAlarm () {
logger.info('Starting TCP connection...')
// connect
socket.connect()
}
function executeCommand (commands, args) {
try {
const delay = MeianConnection.status.isReady() ? 0 : 200
// idle or autenticating
const requestTime = new Date().getTime()
const commandInterval = setInterval(async () => {
const executionTime = new Date().getTime()
// async command
if (MeianConnection.status.isReady() || (executionTime - requestTime) > 10000) {
clearInterval(commandInterval)
await socket.executeCommand(commands, args)
} else {
logger.info(`A request is in progress...we will wait for response before sending ${JSON.stringify(commands)} (${JSON.stringify(args)})`)
}
},
delay)
} catch (error) {
handleError(error)
}
}
/**
* ready to send commands
*/
socket.onConnected(async (connectionResponse) => {
logger.info(`logged in (${connectionResponse})`)
logger.info('Setting up first TCP command to retrieve mac address...')
// send commands
executeCommand('GetNet')
logger.info(`First connection OK: alarm panel responded ${JSON.stringify(config.deviceInfo)}`)
logger.info('Retrieving zone info ...')
if (configHandler.isFeatureEnabled(config, 'zoneNames')) {
executeCommand('GetZone')
}
// availability
publisher.publishAvailable(true)
// we are ready to start tcp polling
startPolling()
})
// command
socket.onResponse(async (commandResponse) => {
try {
// formatted payload
const payload = commandResponse.payloads?.data
// mac address, ip, etc
if (payload.GetNet) {
parseNet(payload.GetNet)
}
// parse zone names and put them into cache
if (payload.GetZone) {
parseZones(payload.GetZone)
}
/* try {
if (commandResponse.payloads?.rawData && commandResponse.payloads?.rawData?.SetArea) {
logger.info(`******** DEBUG ******* SetArea RAW: ${JSON.stringify(commandResponse.payloads?.rawData?.SetArea)}`)
}
if (payload.SetArea) {
logger.info(`******** DEBUG ******* SetArea formatted: ${JSON.stringify(payload.SetArea)}`)
}
} catch (error) {
logger.info(`******** DEBUG ******* SetArea payload: ${JSON.stringify(commandResponse)}`)
} */
// status and sensors
if ((payload.GetAlarmStatus || payload.GetArea) && payload.GetByWay) {
parseStatusAndSensors(payload.GetAlarmStatus || payload.GetArea, payload.GetByWay, payload.GetZone || zonesCache.zones)
}
if (payload.SetByWay || payload.SetAlarmStatus || payload.SetArea) {
if (payload.SetByWay) {
// gets the latest state sensor from mqtt cache and updates only the submitted properties
const zoneNumber = payload.SetByWay.zone + 1
publisher.updateStateSensor(zoneNumber, { bypass: payload.SetByWay.bypass })
}
if (payload.SetAlarmStatus) {
publisher.publishStateIAlarm({
status_1: payload.SetAlarmStatus
})
}
// TODO UNTESTED!!! SetArea
if (payload.SetArea && payload.SetArea.status) {
// { "area": 2, "status": "ARMED_HOME" }
const areaStatus = {}
const areaNum = (payload.SetArea.area || 1) + 1
areaStatus[`status_${areaNum}`] = payload.SetArea.status
publisher.publishStateIAlarm(areaStatus)
}
logger.debug(`Received response: ${JSON.stringify(commandResponse)}`)
if (!isPolling()) {
startPolling()
}
}
Object.keys(commandResponse).forEach(command => {
if (commandResponse[command] && (commandResponse[command].error || commandResponse[command].timeout)) {
logger.log('error', `${command} responded with an error "${commandResponse[command].error}" or timed out ${commandResponse[command].timeout}`)
}
})
// once received GetNet and GetZones we are ready to start discovery
if (zonesCache.zones && !discovered) {
// home assistant discovery (if enabled)
discovery(config.hadiscovery.enabled)
}
} catch (error) {
handleError(error)
}
})
function isResponseValid (response) {
return response && !response.error
}
/**
* Mac address, ip, etc
* @param {*} GetNet
*/
function parseNet (GetNet) {
if (!isResponseValid(GetNet)) {
return
}
config.deviceInfo = GetNet
}
/**
* Zone Names
* @param {*} GetZone
*/
function parseZones (GetZone) {
if (!isResponseValid(GetZone)) {
return
}
let zoneNames = []
// zone names disabled, building them
if (!configHandler.isFeatureEnabled(config, 'zoneNames')) {
// config check
if (!Array.isArray(config.server.zones)) {
throw new Error('config.server.zones must be an array')
}
for (let index = 0; index < config.server.zones.length; index++) {
const zoneNumber = config.server.zones[index]
zoneNames.push(
{
typeId: 2, // using Perimetrale as default
type: 'Perimetrale',
voiceId: 1,
voiceName: 'Fisso',
id: zoneNumber,
zone: zoneNumber,
name: 'Device'
}
)
}
} else if (GetZone) {
zoneNames = MeianDataHandler.getZoneInfo(GetZone)
}
if (zoneNames && zoneNames.length > 0) {
logger.info(`got ${Object.keys(zoneNames).length} ' zones info'`)
// remove empty or disabled zones
zonesCache.zones = removeDisabledZones(zoneNames, config.server.showUnnamedZones)
zonesCache.caching = false
}
}
/**
* Alarm status and sensors data
* @param {*} GetAlarmStatus
* @param {*} GetByWay
* @param {*} GetZone
*/
function parseStatusAndSensors (GetAlarmStatus, GetByWay, GetZone) {
// create stubs
GetByWay = isResponseValid(GetByWay) ? GetByWay : { zones: [] }
GetZone = isResponseValid(GetZone) ? GetZone : { zones: [] }
// full response
const zonesResponse = MeianDataHandler.getZoneStatus(
GetAlarmStatus, // alarm status
GetByWay, // sensor states
GetZone, // zone names (cache or previous fetch)
config.server.zones // configured zones
)
// mqtt
publishFullState(zonesResponse.status, zonesResponse.zones || [])
// alarm is responding
if (zonesResponse.status && zonesResponse.zones) {
publisher.publishConnectionStatus(!MeianConnection.status.isDisconnected(), 'OK')
}
}
// push events
socket.onPush(async (pushResponse) => {
logger.debug(`Received push: ${JSON.stringify(pushResponse)}`)
if (!configHandler.isFeatureEnabled(config, 'events')) {
logger.debug('Events disabled in config file')
return
}
try {
const data = pushResponse.data
if (data || !data.zone) {
const zoneCache = getZoneCache(data.zone)
if (zoneCache) {
data.name = zoneCache.name || data.zoneName
data.type = zoneCache.type
}
let description = data.zone
if (data.name) {
description = description + ' ' + data.name
}
description = data.content + ' (zone ' + description + ')'
// publish only if changed or empty
publisher.publishEvent({
...data,
description,
lastUpdated: new Date().toISOString()
})
} else {
logger.warning(`Received an empty push event: ${JSON.stringify(data)}`)
}
} catch (error) {
handleError(error)
}
})
socket.onDisconnected(async (disconnectionResponse) => {
logger.info(`disconnected (type: ${disconnectionResponse}, errorCount: ${errorCount})`)
// availability
publisher.publishAvailable(false)
errorCount = 0
})
socket.onError(async (error) => {
errorCount++
// clean errors
publisher.publishConnectionStatus(!MeianConnection.status.isDisconnected(), error.message || 'Generic error')
logger.info(`Error ${error.message} - ${JSON.stringify(error.stack)}`)
// stop
stopPolling()
// disconnect
if (errorCount > 10) {
socket.disconnect('error')
// retry after some time
setTimeout(() => {
connectToAlarm()
}, 5000)
}
})
let zonesCache = {}
const pollings = []
function handleError (e) {
let msg
if (typeof e === 'string') {
msg = e
} else if (e.message) {
msg = e.message
}
const stack = e.stack ? JSON.stringify(e.stack) : ''
publisher.publishConnectionStatus(!MeianConnection.status.isDisconnected(), msg, stack)
}
function getZoneCache (id) {
if (zonesCache &&
zonesCache.zones &&
zonesCache.zones[id]) {
return zonesCache.zones.find(z => z.id === id)
}
return undefined
};
/**
* removes empty or disabled zones
* @param {*} zones
* @returns
*/
function removeDisabledZones (zones, showUnnamedZones) {
return zones.filter(z => {
if (!z.typeId || z.typeId <= 0) {
logger.info(`removeDisabledZones: filtering out zone ${z.id} with typeId disabled`, z)
return false
}
if (!showUnnamedZones && !z.name) {
logger.info(`removeDisabledZones: filtering out zone ${z.id} with empty name`, z)
return false
}
return true
})
}
/**
* Read and publis state
*/
async function fetchStatus () {
try {
if (!configHandler.isFeatureEnabled(config, ['armDisarm', 'sensors'])) {
return
}
const commands = []
if (configHandler.isFeatureEnabled(config, 'sensors')) {
// sensor status with names, type, etc
commands.push('GetByWay')
}
// if needed fetch zones
if ((!zonesCache.zones || zonesCache.zones.length === 0) &&
configHandler.isFeatureEnabled(config, 'zoneNames')) {
commands.push('GetZone')
}
// if needed fetch alarm/area status
if (configHandler.isFeatureEnabled(config, 'armDisarm')) {
const command = config.server.areas > 1 ? 'GetArea' : 'GetAlarmStatus'
commands.push(command)
}
// 1, 2 or 3 commands
executeCommand(commands)
} catch (error) {
handleError(error)
}
}
/**
* publish received state and fetch new events
* @param {*} param0
*/
function publishFullState (status, zones) {
// alarm
publisher.publishStateIAlarm(status)
// zone config override
if (zones && config.zones) {
config.zones.forEach(zoneConfig => {
const zoneId = zoneConfig.number
const zoneNumber = parseInt(zoneId)
const zone = zones.find(z => z.id === zoneNumber)
if (zone) {
// normally open /normally closed (default closed)
if (zoneConfig.contactType === 'NO') {
const fault = zone[zoneConfig.statusProperty || 'fault']
// invert open/problem data
zone[zoneConfig.statusProperty || 'fault'] = !fault
}
}
})
}
// publish sensors
publisher.publishStateSensor(zones)
}
async function armDisarm (commandType, numArea) {
if (!configHandler.isFeatureEnabled(config, 'armDisarm')) {
return
}
try {
const alarmStatusName = MeianStatusDecoder.fromStatusToTcpValue(commandType)
if (!commandType || !alarmStatusName) {
logger.error(`Received invalid alarm command: ${commandType}`)
} else {
logger.info(`Received alarm command: ${commandType}`)
// stop polling
stopPolling()
// force publish on next round
publisher.resetCache()
// command
const commandName = config.server.areas > 1 ? 'SetArea' : 'SetAlarmStatus'
// area index is 0 based
const commandArgs = config.server.areas > 1 ? [[parseInt(numArea) - 1, alarmStatusName]] : [[alarmStatusName]]
executeCommand(commandName, commandArgs)
if (config.debug) {
logger.info('DEBUG MODE: IGNORING SET COMMAND RECEIVED for alarm.' + commandType + '()')
logger.info('DEBUG MODE: FAKING SET COMMAND RECEIVED for alarm.' + commandType + '()')
publisher.publishStateIAlarm(commandType)
}
}
} catch (error) {
handleError(error)
}
}
async function bypassZone (zoneNumber, bypass) {
if (!configHandler.isFeatureEnabled(config, 'bypass')) {
return
}
try {
/* if (config.server.zones && !config.server.zones.includes(zoneNumber)) {
console.error('bypassZone: received not configured zone number: ' + zoneNumber)
return
} */
const maxZones = configHandler.getMaxZones()
if (!zoneNumber || zoneNumber > maxZones) {
console.error('bypassZone: received invalid zone number: ' + zoneNumber)
return
}
bypass = bypass || false
// stop polling
stopPolling()
logger.info('Received bypass ' + bypass + ' for zone number ' + zoneNumber)
// force publish on next round
publisher.resetCache()
// zone 0-indexed
executeCommand('SetByWay', [[zoneNumber - 1, bypass]])
} catch (error) {
handleError(error)
}
}
function discovery (enabled) {
// clean errors
publisher.publishConnectionStatus(!MeianConnection.status.isDisconnected(), 'OK')
// home assistant mqtt discovery (if not enabled it will reset all /config topics)
publisher.publishHomeAssistantMqttDiscovery(Object.values(zonesCache.zones), enabled, config.deviceInfo)
if (!enabled) {
logger.warn('Home assistant discovery disabled (empty config.hadiscovery)')
}
discovered = true
}
function resetCache () {
logger.warn('iAlarm cache cleared')
publisher.resetCache()
// sending fresh data
fetchStatus()
}
/**
* mqtt init
*/
function startMqtt (onConnected, onDisconnected) {
// mqtt init
const commandHandler = {}
commandHandler.armDisarm = armDisarm
commandHandler.bypassZone = bypassZone
commandHandler.discovery = discovery
commandHandler.resetCache = resetCache
publisher.connectAndSubscribe(
commandHandler,
// connected
onConnected,
// disconnected
onDisconnected)
}
/**
* stop polling
*/
function stopPolling () {
// reset timers
if (pollings.length > 0) {
clearInterval(pollings)
}
}
/**
* Check if any timeout is currently active
* @returns
*/
function isPolling () {
return pollings && pollings.length > 0
}
/**
* set up pollings
* @returns
*/
function startPolling () {
if (isPolling()) {
return
}
pollings.push(setInterval(function () {
publisher.publishAvailable(true)
}, 300000))
// alarm and sensor status
if (configHandler.isFeatureEnabled(config, ['armDisarm', 'sensors', 'bypass'])) {
logger.info(`Status polling every ${config.server.polling_status}ms`)
pollings.push(setInterval(function () {
if ((!zonesCache.zones || zonesCache.zones.length === 0) && !config.deviceInfo) {
publisher.publishConnectionStatus(!MeianConnection.status.isDisconnected(), 'Missing network and zone infos')
return
}
fetchStatus()
}, config.server.polling_status))
} else {
logger.debug('Status disabled in config file')
}
}
// start loop
function start () {
logger.info('Starting up...')
const host = config.server.host
const port = config.server.port
const username = config.server.username
const password = config.server.password
if (!host || !port || !username || !password) {
throw new Error('Missing required configuration')
}
if (!zonesCache) {
zonesCache = { zones: {}, caching: true }
}
// mqtt connection first
startMqtt(
// on connection start tcp polling
() => {
// reset timers
stopPolling()
connectToAlarm()
},
// on disconnection end polling and close app
() => {
stop(pollings)
}
)
}
function stop () {
logger.info('Stopping...')
// reset timers
stopPolling()
// exit ialarm-mqtt
process.exit(1)
}
start()
}