forked from snowdd1/homebridge-knx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
536 lines (485 loc) · 21.3 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
/*
* Platform shim for use with nfarina's homebridge plugin system
* This is the version for plugin support
* ********************************************************************************************
*
ALL NEW VERSION WITH OWN PERSISTENCE LAYER (file based, anyhow)
ECMA-Script 2015 (6.0) Language required
*/
/* jshint esversion: 6, strict: true, node: true */
'use strict';
var KNXDevice = require('./lib/knxdevice.js');
var userOpts = require('./lib/user').User;
var Service, Characteristic; // passed default objects from hap-nodejs
var globs = {}; // the storage for cross module data pooling;
//var iterate = require('./lib/iterate');
var knxmonitor = require('./lib/knxmonitor');
var KNXAccess = require("./lib/knxaccess");
var getServiceData = require("./lib/servicedata"); // the data for the web server to show available services and characteristics
// Define a custom require that treats requires in the remote addins as local
global.knxRequire = name => require(`${name}`);
var http = require('http');
/**
* KNXPlatform
*
* @constructor
* @param {function} log - logging function for console etc. out
* @param {object} config - configuration object from global config.json
*/
function KNXPlatform(log, config, newAPI) {
var that = this;
this.log = log;
//this.Old_config = config;
// new API for creating accessory and such.
globs.newAPI = newAPI;
/**
* Talkative Info spitting thingy.
*
* @param {string} comment
*
*/
globs.info = function (comment) {
that.log.info(comment);
};
globs.debug = function (comment) {
that.log.debug(comment);
};
globs.errorlog = function (comment) {
that.log.error(comment);
};
/* our own config file */
globs.debug("Trying to load user settings");
userOpts.setStoragePath(newAPI.user.storagePath()); // get path from homebridge!
globs.debug(userOpts.configPath());
this.config = userOpts.loadConfig();
globs.config = this.config;
globs.restoredAccessories = []; //plugin-2
/* we should have now:
* - knxd_ip
* - knxd_port
* - GroupAddresses object
* - Devices Object
*/
globs.knxd = this.config.knxd;
globs.knxd_ip = this.config.knxd_ip;
globs.knxd_port = this.config.knxd_port || 6720;
globs.log = log;
globs.knxmonitor = knxmonitor;
/**
* To store all unique read requests
*
* @type {string[]}
*/
globs.readRequests = {};
KNXAccess.setGlobs(globs); // init link for module;
knxmonitor.setGlobs(globs);
knxmonitor.startMonitor({
host: globs.knxd_ip,
port: globs.knxd_port
});
// plugin-2 system: wait for the homebridge to finish restoring the accessories from its own persistence layer.
if (newAPI) {
newAPI.on('didFinishLaunching', function () {
globs.info('homebridge event didFinishLaunching');
this.configure();
}.bind(this));
}
}
/**
* Registers the plugin with homebridge. Will be called by homebridge if found in directory structure and package.json
* is right This function needs to be exported.
*
* @param {homebridge/lib/api.js~API} homebridgeAPI - The API Object made available by homebridge. Contains the HAP type library e.g.
*
*/
function registry(homebridgeAPI) {
console.log("homebridge API version: " + homebridgeAPI.version);
/*
* Experimental: Look for a user file called knx-ignore.txt in the user config path.
* If it is there, exit here and DO NOT REGISTER the platform
*/
let fs = require('fs');
let path = require('path');
let checkfilepath = path.join(homebridgeAPI.user.storagePath(), 'knx-ignore.txt');
if (fs.existsSync(checkfilepath)) {
console.log('[WARNING] Found blocking file, exiting now. To load homebridge-knx, remove ' + checkfilepath);
return;
}
// END OF INSERTION FOR BRANCH ignore-option
Service = homebridgeAPI.hap.Service;
Characteristic = homebridgeAPI.hap.Characteristic;
globs.Service = Service;
globs.Characteristic = Characteristic;
globs.API = homebridgeAPI;
/* load our custom types
*
*/
require('./lib/customtypes/knxthermostat.js')(homebridgeAPI);
/*
* get the data for the web server (show available services and characteristics)
*/
globs.webdata = getServiceData(globs);
// third parameter dynamic = true
homebridgeAPI.registerPlatform("homebridge-knx", "KNX", KNXPlatform, true); //update signature for plugin-2
}
module.exports = registry;
//Function invoked when homebridge tries to restore cached accessory
//Developer can configure accessory at here (like setup event handler)
//Update current value
/**
* configureAccessory() is invoked for each accessory homebridge restores from its persistence layer. The restored
* accessory has all the homekit properties, but none of the implementation at this point of time. This happens before
* the didFinishLaunching event.
*
* @param {platformAccessory} accessory
*/
KNXPlatform.prototype.configureAccessory = function (accessory) {
console.log("Plugin - Configure Accessory: " + accessory.displayName + " --> Added to restoredAccessories[]");
// set the accessory to reachable if plugin can currently process the accessory
// otherwise set to false and update the reachability later by invoking
// accessory.updateReachability()
accessory.updateReachability(false);
// collect the accessories
globs.restoredAccessories.push(accessory);
};
/**
* With plugin-2 system, accessories are re-created by the homebridge itself, but without all the event functions etc.
*
* We need to re-connect all our accessories to the right functions
*
* This is my event handler for the "didFinishLaunching" event of the newAPI
*/
KNXPlatform.prototype.configure = function () {
globs.info('Configuration starts');
userOpts.LogHomebridgeKNXSTarts();
// homebridge has now finished restoring the accessories from its persistence layer.
// Now we need to get their implementation back to them
globs.debug('We think homebridge has restored ' + globs.restoredAccessories.length + ' accessories.');
/* *************** read the config the first time
*
*/
if (!this.config.GroupAddresses) {
this.config.GroupAddresses = [];
}
// iterate through all devices the platform my offer
// for each device, create an accessory
// read accessories from file !!!!!
var foundAccessories = this.config.Devices || [];
//create array of accessories
/** @type {lib/knxdevice.js~knxDevice[]} */
globs.devices = [];
for (var int = 0; int < foundAccessories.length; int++) {
var currAcc = foundAccessories[int];
globs.info("Reading from config: Device/Accessory " + (int + 1) + " of " + foundAccessories.length);
globs.debug("Match device [" + currAcc.DeviceName + "]");
//match them to the restored accessories:
/** @type {homebridge/lib/platformAccessory.js/PlatformAccessory} */
var matchAcc = getAccessoryByUUID(globs.restoredAccessories, currAcc.UUID);
if (matchAcc) {
// we found one
globs.debug('Matched an accessory: ' + currAcc.DeviceName + ' === ' + matchAcc.displayName);
// Instantiate and pass the existing platformAccessory
matchAcc.active = true;
globs.devices.push(new KNXDevice(globs, foundAccessories[int], matchAcc));
} else {
// this one is new
globs.debug('New accessory found: ' + currAcc.DeviceName);
globs.devices.push(new KNXDevice(globs, foundAccessories[int]));
}
// do not construct here: var acc = new accConstructor(globs,foundAccessories[int]);
globs.info("Done with [" + currAcc.DeviceName + "] accessory");
}
// now the globs.devices contains an array of working accessories, that are not yet passed to homebridge
globs.info('We have read ' + globs.devices.length + ' devices from file.');
//now we need to store our updated config file to disk, or else all that is in vain next startup!
globs.info('Saving config file!');
userOpts.storeConfig();
// here needs the hook for global "finished" event to go into
for (var i = 0; i < globs.devices.length; i++) {
let matchAcc2 = globs.devices[i];
for (var i_serv = 0; i_serv < matchAcc2.services.length; i_serv++) {
var myKNXService = matchAcc2.services[i_serv];
if (myKNXService.customServiceAPI && myKNXService.customServiceAPI.handler) {
if (typeof myKNXService.customServiceAPI.handler.onHomeKitReady === 'function') {
globs.debug(matchAcc2.name + "/" + myKNXService.name + ": Custom Handler onHomeKitReady()");
myKNXService.customServiceAPI.handler.onHomeKitReady();
}
}
}
}
/*********************************************************************************/
// start the tiny web server for deleting orphaned devices
globs.debug('BEFORE http.createServer');
var that = this;
this.startUpDateAndTime = new Date();
this.startUpDateAndTimeString = this.startUpDateAndTime.toString();
this.blacklistedCharProps = {
"_events": true,
"_eventsCount": true,
"_maxListeners": true,
"iid": true,
"value": true,
"status": true,
"subscriptions": true
}
this.requestServer = http.createServer(function (request, response) {
globs.debug('http.createServer CALLBACK FUNCTION URL=' + request.url);
var reqparsed = request.url.substr(1).split('?');
var params = {};
var paramstemp = [];
if (reqparsed[1]) {
paramstemp = reqparsed[1].split('&');
for (var i = 0; i < paramstemp.length; i++) {
/** @type {string[]} */
var b = paramstemp[i].split('=');
params[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
}
}
/*
* Now we have: path in reqparsed[0] like "list" or "delete"
* param
*/
if (request.url === "/list") {
//response.writeHead(200);
response.write('<HEAD><meta http-equiv="content-type" content="text/html; charset=utf-8"><TITLE>Homebridge-KNX</TITLE></HEAD>');
response.write('<BODY>');
response.write('<h1>homebridge-knx</h1>');
response.write('homebridge-knx started at ' + that.startUpDateAndTimeString);
response.write('<hr>');
response.write('<h2>Restored devices from homebridge cache:</h2>');
response.write('<table><tr><th>Device</th><th>Actions</th></tr>');
var idev = 0, tdev = {};
for (idev = 0; idev < globs.restoredAccessories.length; idev++) {
tdev = globs.restoredAccessories[idev];
// debug spit-out:
//response.write('<BR><HR><BR>' + JSON.stringify(tdev) + '<BR><BR>');
globs.debug(tdev.UUID);
if (tdev.UUID !== 'ERASED') {
response.write('<tr><td> ' + tdev.displayName);
response.write('</td><td><a href="/delete?UUID=' + tdev.UUID + '">[Delete from cache!]</a> ');
if (!tdev.active) {
response.write(' (orphaned) ');
}
response.write('</td></tr>');
}
}
response.write('</table>');
response.write('<H2><BR>Devices from homebridge-knx config:</h2>');
response.write('<table><tr><th>Device</th><th>Actions</th></tr>');
for (idev = 0; idev < globs.devices.length; idev++) {
tdev = globs.devices[idev].getPlatformAccessory();
if (tdev.UUID !== 'ERASED') {
response.write('<tr><td> ' + tdev.displayName);
response.write('</td><td><a href="/delete?UUID=' + tdev.UUID + '">[Delete from cache!]</a> ' + ' </td></tr>');
// TODO: List Services here - Services are the prime homekit objects!
}
}
response.write('</table>');
if (that.config.AllowKillHomebridge === true) {
response.write(' <br><h2>Debug Activities</h2><br><a href="/kill">Kill homebridge</a> by throwing an Error. Use this to restart HomeBridge if you have it configured as a self-starting service ' + ' <BR>');
}
response.write('<HR><BR>Available pages are <br><a href="/list">list devices</a> and <br><a href="/availservices">list available services</a><br><a href="/availcharacteristics">list available characteristics</a>');
response.write('<BR><BR>URL<BR>' + request.url + '<BR>');
response.write(JSON.stringify(params) + '<BR>');
response.end('</BODY>');
} else if (reqparsed[0] === 'delete') {
// now delete the accessory from homebridge
globs.debug("delete accessory with UUID ");
if (params.UUID) {
try {
globs.debug(params.UUID);
var delAcc = getAccessoryByUUID(globs.restoredAccessories, params.UUID);
if (delAcc) {
globs.newAPI.unregisterPlatformAccessories(undefined, undefined, [delAcc]);
delAcc.UUID = "ERASED";
} else {
delAcc = getAccessoryByUUID(globs.devices, params.UUID);
if (delAcc) {
globs.newAPI.unregisterPlatformAccessories(undefined, undefined, [delAcc]);
delAcc.UUID = "ERASED";
}
}
globs.debug(params.UUID + ' deleted');
} catch (err) {
globs.errorlog('ERR Could not delete accessory with UUID ' + params.UUID);
} finally {
response.end('<HEAD><meta http-equiv="refresh" content="0; url=http:/list" /></HEAD><BODY> done. Go back in browser and refresh</BODY>');
}
}
} else if (reqparsed[0] === 'kill') {
// commit suicide
if (that.config.AllowKillHomebridge === true) {
response.end('<HEAD><meta http-equiv="refresh" content="20; url=http:/list" /></HEAD><BODY> Committed suicide. Reloading in 20 seconds.</BODY>');
var timerX = setTimeout(function () {
throw "Commited_Suicide";
}, 500);
}
} else if (reqparsed[0] === 'availservices') {
// list the Services that homebridge knows about
response.write('<HEAD><TITLE>Homebridge-KNX</TITLE></HEAD>');
response.write('<BODY>');
response.write('<h1>Available services for homebridge are: </h1>');
response.write('<table><tr><th>ObjectName</th><th>Service Name</th></tr>');
for (let srvName in globs.webdata.servData) {
if (globs.webdata.servData.hasOwnProperty(srvName)) {
let srv = globs.webdata.servData[srvName];
response.write('<tr><td><a href="/servicedata?name=' + srvName + '">' + srv.displayName + '</a></td><td>' + srv.localized.en.displayName + '</td></tr>');
}
}
response.write('</table>');
response.write('<HR><BR>Available pages are <br><a href="/list">list devices</a> and <br><a href="/availservices">list available services</a><br><a href="/availcharacteristics">list available characteristics</a>');
response.write('<BR><BR>URL<BR>' + request.url + '<BR>');
response.write(JSON.stringify(params) + '<BR>');
response.end('</BODY>');
} else if (reqparsed[0] === 'availcharacteristics') {
// list the Characteristics that homebridge knows about
response.write('<HEAD><TITLE>Homebridge-KNX</TITLE></HEAD>');
response.write('<BODY>');
response.write('<h1>Available characteristics for homebridge are: </h1>');
response.write('<table><tr><th>Property</th><th>Value</th></tr>');
for (let chrName in globs.webdata.charData) {
if (globs.webdata.charData.hasOwnProperty(chrName)) {
let chr = globs.webdata.charData[chrName];
console.dir(chr);
response.write('<tr><td><a href="/chardata?name=' + chr.displayName + '">' + chr.displayName + '</a></td></tr>');
}
}
response.write('</table>');
response.write('<HR><BR>Available pages are <br><a href="/list">list devices</a> and <br><a href="/availservices">list available services</a><br><a href="/availcharacteristics">list available characteristics</a>');
response.write('<BR><BR>URL<BR>' + request.url + '<BR>');
response.write(JSON.stringify(params) + '<BR>');
response.end('</BODY>');
} else if (reqparsed[0] === 'servicedata') {
// show service
response.write('<HEAD><TITLE>Homebridge-KNX</TITLE></HEAD>');
response.write('<BODY>');
if (params.name && globs.webdata.availableServices.Services[params.name]) {
let service1 = globs.webdata.availableServices.Services[params.name];
let disp1 = globs.webdata.servData[params.name];
response.write('<H1>' + disp1.displayName + '</H1>');
response.write('<H2>Mandatory characteristics</H2>');
response.write('<H4>Mandatory characteristics are created automatically by homebridge. If they are not connected to group addresses they are dysfunct although displayed in HomeKit apps.</H4>');
response.write('<table><tr><th>ObjectName</th><th>Display Name</th></tr>');
for (let chrName in service1.characteristics) { // service1.characteristics is a numbered array !!!
if (service1.characteristics.hasOwnProperty(chrName)) {
let chr1 = globs.webdata.charData[service1.characteristics[chrName].displayName];
response.write('<tr><td><a href="/chardata?name=' + chr1.displayName + '">' + chr1.objectName + '</a></td><td>' + chr1.localized.en.displayName + '</td></tr>'); // TODO localisation
}
}
response.write('</table>');
response.write('<H2>Optional characteristics</H2>');
response.write('<H4>Optional characteristics are created if listed in configuration. Any other characteristic might also work, these are thought by Apple to work best with the service</H4>');
response.write('<table><tr><th>ObjectName</th><th>Display Name</th></tr>');
for (let chrName in service1.optionalCharacteristics) { // service1.characteristics is a numbered array !!!
if (service1.optionalCharacteristics.hasOwnProperty(chrName)) {
//console.log('Searching for '+service1.optionalCharacteristics[chrName].displayName);
//console.dir(globs.webdata.charData);
let chr1 = globs.webdata.charData[service1.optionalCharacteristics[chrName].displayName];
response.write('<tr><td><a href="/chardata?name=' + chr1.displayName + '">' + chr1.objectName + '</a></td><td>' + chr1.localized.en.displayName + '</td></tr>'); // TODO localisation
}
}
response.write('</table>');
} else {
response.write('<H1>Error in URL</H1>');
}
response.write('<HR><BR>Available pages are <br><a href="/list">list devices</a> and <br><a href="/availservices">list available services</a><br><a href="/availcharacteristics">list available characteristics</a>');
response.write('<BR><BR>URL<BR>' + request.url + '<BR>');
response.write(JSON.stringify(params) + '<BR>');
response.end('</BODY>');
} else if (reqparsed[0] === 'chardata') {
// show characteristic
globs.debug("list characteristic");
response.write('<HEAD><TITLE>Homebridge-KNX</TITLE></HEAD>');
response.write('<BODY>');
if (params.name && globs.webdata.charData[params.name]) {
let disp1 = globs.webdata.charData[params.name];
let char1 = globs.webdata.availableCharacteristics[disp1.objectName];
response.write('<H1>' + disp1.displayName + '</H1>');
response.write('<H2>Properties</H2>');
response.write('<H4>Properties define the behaviour of the characteristic</H4>');
response.write('<table><tr><th>Property</th><th>Value</th></tr>');
for (let prop in char1) { //
if (char1.hasOwnProperty(prop)) {
if (!that.blacklistedCharProps[prop]) {
try {
if (typeof char1[prop] !== 'function') {
if (prop !== 'props') {
response.write('<tr><td>' + prop + '</td><td>' + char1[prop] + '</td></tr>'); // TODO localisation
} else {
for (let pp in char1[prop]) {
if (char1[prop].hasOwnProperty(pp)) {
response.write('<tr><td>' + pp + '</td><td>' + char1[prop][pp] + '</td></tr>'); // TODO localisation
}
}
}
}
} catch (error) {
console.dir(error);
}
}
}
}
response.write('</table>');
} else {
response.write('<H1>Error in URL</H1>');
console.dir(globs.webdata.charData);
}
response.write('<HR><BR>Available pages are <br><a href="/list">list devices</a> and <br><a href="/availservices">list available services</a><br><a href="/availcharacteristics">list available characteristics</a>');
response.write('<BR>Debug Information: <BR>URL request<BR>' + request.url + '<BR>');
response.write(JSON.stringify(params) + '<BR>');
response.end('</BODY>');
} else {
// any other URL
response.write('<HEAD><TITLE>Homebridge-KNX</TITLE></HEAD>');
response.write('<BODY>');
response.write('<BR>Available pages are <br><a href="/list">list devices</a> and <br><a href="/availservices">list available services</a><br><a href="/availcharacteristics">list available characteristics</a>');
response.write('<h1>URL<h1/><BR><BR>' + request.url + '<BR>');
response.write(JSON.stringify(params) + '<BR>');
response.end('</BODY>');
}
}.bind(this));
globs.debug('BEFORE requestServer.listen');
if (this.config.AllowWebserver) {
let that = this;
this.requestServer.listen(that.config.WebserverPort || 18081, function () {
console.log("Server Listening...localhost:" + that.config.WebserverPort || 18081 + "/list");
});
}
// we're done, now issue the startup read requests to the bus
KNXAccess.knxreadhash(globs.readRequests);
};
/**
* returns an accessory from an array of accessories if the context property is matched, or undefined.
*
* @param {homebridge/lib/platformAccessory.js~PlatformAccessory[]} accessories The array of accessories.
* @param {String} uuid The context object (presumably a string) to be matched.
* @return {homebridge/lib/platformAccessory.js~PlatformAccessory} or undefined
*
*/
function getAccessoryByUUID(accessories, uuid) {
globs.debug('--compare----------------');
for (var ina = 0; ina < accessories.length; ina++) {
var thisAcc = accessories[ina];
globs.debug('Comparing ' + thisAcc.UUID + ' === ' + uuid + ' ==>' + (thisAcc.UUID === uuid));
//console.log(thisAcc); // spit it out
if (thisAcc.UUID === uuid) {
globs.debug('---------------done---');
return thisAcc;
}
}
// nothing found:
globs.debug('-----none----------return-undefined--');
return undefined;
}
/**
* Search the globs object's devices[] array for an knxDevice with name 'name'
*/
globs.getDeviceByName = function (name) {
for (var idevice = 0; idevice < globs.devices.length; idevice++) {
var oDevice = globs.devices[idevice];
if (oDevice.name === name) {
return oDevice;
}
}
return undefined;
};