This repository has been archived by the owner on May 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
ccu.io.js
2689 lines (2366 loc) · 90 KB
/
ccu.io.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
/**
* CCU.IO
*
* Socket.IO based HomeMatic Interface
*
* Copyright (c) 2013, 2014 http://hobbyquaker.github.io
*
* CC BY-NC 3.0
*
* Kommerzielle Nutzung nicht gestattet!
*
*/
var settings = require(__dirname+'/settings.js');
settings.version = "1.0.52";
settings.basedir = __dirname;
settings.datastorePath = __dirname+"/datastore/";
settings.stringTableLanguage = settings.stringTableLanguage || "de";
settings.regahss.metaScripts = [
"favorites",
"variables",
"programs",
"rooms",
"functions",
"devices",
"channels",
"datapoints",
"alarms"
];
var fs = require('fs'),
logger = require(__dirname + '/logger.js'),
binrpc = require(__dirname + "/binrpc.js"),
rega = require(__dirname + "/rega.js"),
express = require('express'),
http = require('http'),
https = require('https'),
crypto = require('crypto'),
request = require('request'),
childProcess = require('child_process'),
url = require('url'),
socketio = require('socket.io'),
scheduler = require('node-schedule'),
mime = require('mime'),
os = require('os'),
app,
appSsl,
server,
serverSsl,
serverV6,
serverSslV6,
io,
ioSsl,
ioV6,
ioSslV6,
devlogCache = [],
notFirstVarUpdate = false,
children = [],
childrenAdapter = {},
timerAdapter = {},
childScriptEngine,
pollTimer,
ccuReachable = false,
ccuRegaUp = false,
webserverUp = false,
initsDone = false,
extDone = false,
lastEvents = {},
authHash = "",
restApiDelayed = {
timer: null,
responseType: '',
response: null,
waitId: 0
};
if (settings.ioListenPort) {
app = express();
if (settings.authentication && settings.authentication.enabled) {
app.use(express.basicAuth(settings.authentication.user, settings.authentication.password));
}
server = require('http').createServer(app);
if (settings.useIPv6) {
serverV6 = require('http').createServer(app);
}
}
// Create md5 hash of user and password
if (settings.authentication.user && settings.authentication.password) {
// We can add the client IP address, so the key will be different for every client, but the server should calculate hash on the fly
authHash = crypto.createHash('md5').update(settings.authentication.user+settings.authentication.password).digest("hex");
}
if (settings.ioListenPortSsl) {
var options = null;
// Zertifikate vorhanden?
try {
options = {
key: fs.readFileSync(__dirname + '/cert/privatekey.pem'),
cert: fs.readFileSync(__dirname + '/cert/certificate.pem')
};
} catch(err) {
logger.error(err.message);
}
if (options) {
appSsl = express();
if (settings.authentication && settings.authentication.enabledSsl) {
appSsl.use(express.basicAuth(settings.authentication.user, settings.authentication.password));
}
serverSsl = require('https').createServer(options, appSsl);
if (settings.useIPv6) {
serverSslV6 = require('http').createServer(options, appSsl);
}
}
}
if (settings.binrpc.checkEvents && settings.binrpc.checkEvents.enabled) {
setInterval(function () {
if (initsDone && ccuRegaUp) {
var now = Math.floor((new Date()).getTime() / 1000);
var check = now - settings.binrpc.checkEvents.testAfter;
var reinit = now - settings.binrpc.checkEvents.reinitAfter;
for (var i = 0; i < settings.binrpc.inits.length; i++) {
var init = settings.binrpc.inits[i];
if (init.id == "io_cuxd") continue;
if (lastEvents[init.id] < reinit) {
if (settings.binrpc.checkEvents.testTrigger[init.id]) {
logger.warn("binrpc --> re-init "+init.id);
homematic.request(init.port, "init", ["xmlrpc_bin://"+settings.binrpc.listenIp+":"+settings.binrpc.listenPort,init.id], function(data, name) {
if (data === "") {
logger.info("binrpc <-- init on "+name+" successful");
lastEvents[init.id] = Math.floor((new Date()).getTime() / 1000);
} else {
logger.error("binrpc <-- init on "+name+" failure");
}
});
} else {
logger.warn("binrpc checkEvent.trigger undefined for "+init.id);
}
} else if (lastEvents[init.id] < check) {
logger.verbose("binrpc checking init "+init.id);
if (settings.binrpc.checkEvents.testTrigger[init.id]) {
if (regaIndex.Name[settings.binrpc.checkEvents.testTrigger[init.id]]) {
var id = regaIndex.Name[settings.binrpc.checkEvents.testTrigger[init.id]][0];
regahss.script("dom.GetObject("+id+").State(true);");
} else {
logger.warn("binrpc checkEvent.trigger undefined for "+init.id);
}
} else {
logger.warn("binrpc checkEvent.trigger undefined for "+init.id);
}
} else {
logger.verbose("binrpc init "+init.id+" ok - last event "+(now-lastEvents[init.id])+"s ago");
}
}
}
updateStatus();
}, (settings.binrpc.checkEvents.interval * 1000));
}
var socketlist = [],
homematic,
stringtable = {},
datapoints = {},
regaObjects = {},
regaIndex = {
Name: {},
Address: {},
ENUM_ROOMS: [],
ENUM_FUNCTIONS: [],
FAVORITE: [],
DEVICE: [],
CHANNEL: [],
HSSDP: [],
VARDP: [],
ALDP: [],
ALARMDP: [],
PROGRAM: []
},
regaReady = false;
var ignoreNextUpdate = [];
logger.info("ccu.io starting version "+settings.version + " copyright (c) 2013, 2014 hobbyquaker http://hobbyquaker.github.io");
logger.verbose("ccu.io commandline "+JSON.stringify(process.argv));
loadPersistentObjects();
loadDatapoints();
initWebserver();
// Create language variable
datapoints[69999] = [settings.language || 'en', formatTimestamp(), true];
regaObjects[69999] = {Name:"SYSTEM.LANGUAGE", TypeName: "VARDP", DPInfo: "DESC", ValueType: 20, ValueSubType: 11};
regaIndex.VARDP.push(69999);
regaIndex.Name[69999] = [13305, "VARDP", null];
var regahss = new rega({
ccuIp: settings.ccuIp,
ready: function(err) {
if (err == "ReGaHSS down") {
logger.error("rega ReGaHSS down");
ccuReachable = true;
ccuRegaUp = false;
emitEvent("regaDown");
initExtensions();
updateStatus();
tryReconnect();
} else if (err == "CCU unreachable") {
if (settings.ccuIp && settings.ccuIp != '0.0.0.0') {
logger.error("ccu.io CCU unreachable");
}
ccuReachable = false;
ccuRegaUp = false;
emitEvent("ccuDown");
initExtensions();
updateStatus();
tryReconnect();
} else {
logger.info("rega ReGaHSS up");
ccuReachable = true;
ccuRegaUp = true;
regahss.loadStringTable(settings.stringTableLanguage, function (data) {
stringtable = data;
regahss.checkTime(loadRegaData);
});
updateStatus();
}
}
});
function updateStatus () {
var status = {
ccuReachable: ccuReachable,
ccuRegaUp: ccuRegaUp,
ccuRegaData: regaReady,
initsDone: initsDone
}
emitEvent("updateStatus", status);
}
if (settings.logging.enabled) {
setInterval(writeLog, settings.logging.writeInterval * 1000);
if (settings.logging.move) {
scheduler.scheduleJob('0 0 * * *', function(){
moveLog(settings.logging.file);
});
}
}
function emitEvent(msg, arg) {
if (io) {
io.sockets.emit(msg, arg);
}
if (ioSsl) {
ioSsl.sockets.emit(msg, arg);
}
if (ioSslV6) {
ioSslV6.sockets.emit(msg, arg);
}
if (ioV6) {
ioV6.sockets.emit(msg, arg);
}
}
var stats = {
clients: 0,
cuxd: 0,
wired: 0,
rf: 0,
start: ((new Date()).getTime()),
uptime: function() {
var mseconds = ((new Date()).getTime()) - stats.start;
var diff = new Date(mseconds);
var hours = diff.getHours();
var days = Math.floor(hours/24);
hours = hours - (24 * days);
return days+" Tage, "+(hours-1)+" Stunden, "+ diff.getMinutes()+" Minuten, "+diff.getSeconds()+" Sekunden";
},
log: function() {
logger.info("ccu.io stats cuxd: "+(stats.cuxd/settings.statsIntervalMinutes).toFixed(0)+"msg/min, wired: "+(stats.wired/settings.statsIntervalMinutes).toFixed(0)+"msg/min, rf: "+(stats.rf/settings.statsIntervalMinutes).toFixed(0)+"msg/min");
logger.info("ccu.io stats "+socketlist.length+" Socket.IO Clients connected");
logger.verbose("ccu.io uptime "+stats.uptime());
stats.cuxd = 0;
stats.wired = 0;
stats.rf = 0;
}
}
if (settings.stats) {
setInterval(stats.log, settings.statsIntervalMinutes * 60000);
}
function sendEvent(arr) {
logger.verbose("socket.io --> broadcast event "+JSON.stringify(arr))
emitEvent("event", arr);
}
function setDatapoint(id, val, ts, ack, lc) {
if (id < 65535 && !regaReady) { return; }
// unescape HomeMatic Script WriteURL()
if (typeof val == "string") {
val = unescape(val);
}
var oldval = datapoints[id];
var obj; // Event argument
logger.verbose("setDatapoint "+JSON.stringify(oldval)+" -> "+JSON.stringify([val,ts,ack,lc]));
if (!oldval) {
// Neu
if (!regaObjects[id]) {
logger.warn("rega <-- unknown variable "+id);
}
sendEvent(obj);
datapoints[id] = [val,ts,ack,lc];
obj = [id,val,ts,ack,lc];
sendEvent(obj);
} else {
// Änderung
if (!lc && val != oldval[0]) {
lc = formatTimestamp();
} else {
lc = oldval[3];
}
datapoints[id] = [val,ts,ack,lc];
obj = [id,val,ts,ack,lc];
if (val == oldval[0] && ack == oldval[2] && ts == oldval[1] && lc == oldval[3]) {
// Keine Änderung
} else {
sendEvent(obj);
}
/*
if (ack && !oldval[2]) {
// Bestätigung
logger.info("ack "+JSON.stringify(oldval)+" -> "+JSON.stringify([val,ts,ack,lc]));
sendEvent(obj);
} else if (val != oldval[0]) {
// Änderung
logger.info("chg "+JSON.stringify(oldval)+" -> "+JSON.stringify([val,ts,ack,lc]));
sendEvent(obj);
} else if (ts !== oldval[1]) {
// Aktualisierung
logger.info("ts "+JSON.stringify(oldval)+" -> "+JSON.stringify([val,ts,ack,lc]));
sendEvent(obj);
} else {
// Keine Änderung
logger.info("eq "+JSON.stringify(oldval)+" -> "+JSON.stringify([val,ts,ack,lc]));
}
*/
}
}
function tryReconnect() {
if (settings.ccuIp != '0.0.0.0') {
if (regahss && regahss.options && regahss.options.ccuIp) {
if (regahss.options.ccuIp == "0.0.0.0") {
logger.warn("ccu.io invalid CCU ip address " + regahss.options.ccuIp);
regahss.options.ccuIp = "";
return;
}
logger.info("ccu.io trying to reconnect to CCU");
request('http://'+regahss.options.ccuIp+'/ise/checkrega.cgi', function (error, response, body) {
if (!error && response.statusCode == 200) {
if (body == "OK") {
logger.info("ccu.io ReGaHSS up");
ccuReachable = true;
ccuRegaUp = true;
updateStatus();
reconnect();
} else {
logger.error("ccu.io ReGaHSS down");
ccuRegaUp = false;
updateStatus();
setTimeout(tryReconnect, 10000);
}
} else {
logger.error("ccu.io CCU unreachable");
ccuRegaUp = false;
ccuReachable = false;
updateStatus();
setTimeout(tryReconnect, 10000);
}
});
}
}
}
function reconnect() {
regahss.loadStringTable(settings.stringTableLanguage, function (data) {
stringtable = data;
});
if (initsDone) {
initsDone = false;
homematic.stopInits();
updateStatus();
}
regaReady = false;
updateStatus();
clearRegaData();
setTimeout(function () {
regahss.checkTime(function () {
loadRegaData(0, null, null, true);
});
}, 2500);
}
function pollRega() {
if (pollTimer) clearTimeout(pollTimer);
logger.debug('ccu.io pollRega');
regahss.runScriptFile("polling", function (data) {
try {
data = JSON.parse(data);
} catch (e) {
logger.error("ccu.io pollRega invalid JSON "+e);
ccuRegaUp = false;
tryReconnect();
return false;
}
if (!data) return;
for (id in data) {
var val;
if (!data[id] || typeof data[id][0] === 'undefined') continue;
if (settings.logging.enabled) {
var ts = Math.round((new Date()).getTime() / 1000);
if (typeof data[id][0] == "string") {
val = unescape(data[id][0]);
} else {
val = data[id][0];
}
if (datapoints[id] && settings.logging.varChangeOnly && notFirstVarUpdate) {
if (datapoints[id][0] !== val || !datapoints[id][2]) {
devLog(ts, id, val);
}
} else {
devLog(ts, id, val);
}
// Hat sich die Anzahl der Servicemeldungen geändert?
if (id == 41 && datapoints[id][0] != val) {
pollServiceMsgs();
}
}
setDatapoint(id, data[id][0], formatTimestamp(), true, data[id][1]);
}
notFirstVarUpdate = true;
pollTimer = setTimeout(pollRega, settings.regahss.pollDataInterval);
});
}
function pollServiceMsgs() {
logger.info("ccu.io polling service messages");
regahss.runScriptFile("alarms", function (data) {
if (!data) {
ccuRegaUp = false;
tryReconnect();
return false;
}
var data = JSON.parse(data);
var val;
for (id in data) {
var ts = Math.round((new Date()).getTime() / 1000);
devLog(ts, id, data[id].AlState);
setDatapoint(id, data[id].AlState, data[id].LastTriggerTime, true, data[id].AlOccurrenceTime);
}
});
}
function loadRegaData(index, err, rebuild, triggerReload, onlyOne) {
if (!index) { index = 0; }
var type = settings.regahss.metaScripts[index];
logger.info("rega fetching "+type);
regahss.runScriptFile(type, function (data) {
var data = JSON.parse(data);
logger.info("ccu.io indexing "+type);
var timestamp = formatTimestamp();
for (var id in data) {
var idInt = parseInt(id, 10);
// HomeMatic Script "WriteURL" dekodieren
for (var key in data[id]) {
// Nur Strings und auf keinen Fall Kanal- oder Datenpunkt-Arrays
if (typeof data[id][key] == "string" && key !== "Channels" && key !== "DPs") {
data[id][key] = unescape(data[id][key]);
}
// Datenpunkt-Namen dekodieren
if (key == "DPs") {
for (var subkey in data[id][key]) {
var val = data[id][key][subkey];
delete data[id][key][subkey];
data[id][key][unescape(subkey)] = val;
}
}
}
// Index erzeugen
if (type == "alarms") {
var TypeName = "ALDP";
} else {
var TypeName = data[id].TypeName;
}
// Typen-Index (einfach ein Array der IDs)
if (!regaIndex[TypeName]) {
regaIndex[TypeName] = [];
}
if (regaIndex[TypeName].indexOf(idInt) == -1) {
regaIndex[TypeName].push(idInt);
}
// Namens-Index
regaIndex.Name[data[id].Name] = [idInt, TypeName, data[id].Parent];
// ggf. Adressen-Index
if (data[id].Address) {
regaIndex.Address[data[id].Address] = [idInt, TypeName, data[id].Parent];
}
// ggf. Werte setzen
if (type == "variables") {
datapoints[id] = [data[id].Value, data[id].Timestamp, true, data[id].Timestamp];
// Werte aus data Objekt entfernen
delete data[id].Value;
delete data[id].Timestamp;
}
if (type == "datapoints") {
datapoints[id] = [data[id].Value, timestamp, true, data[id].Timestamp];
// Werte aus data Objekt entfernen
delete data[id].Value;
delete data[id].Timestamp;
}
if (type == "alarms") {
if (regaObjects[data[id].Parent]) {
// ggf Kanal ergänzen
if (!regaObjects[data[id].Parent].ALDPs) {
regaObjects[data[id].Parent].ALDPs = {};
}
var tmpType = data[id].Name.split(".");
tmpType = tmpType[1];
regaObjects[data[id].Parent].ALDPs[tmpType] = parseInt(id, 10);
}
// Wert setzen
datapoints[id] = [data[id].AlState, data[id].LastTriggerTime, true, data[id].AlOccurrenceTime];
// Werte aus data Objekt entfernen
delete data[id].AlState;
delete data[id].LastTriggerTime;
delete data[id].AlOccurrenceTime;
}
if (data[id].ValueUnit && data[id].ValueUnit == "�C") {
data[id].ValueUnit = "°C";
}
// Meta-Daten setzen
regaObjects[id] = data[id];
}
if (onlyOne) return;
index += 1;
if (index < settings.regahss.metaScripts.length) {
loadRegaData(index, null, rebuild);
} else {
regaReady = true;
initExtensions();
updateStatus();
if (rebuild) {
logger.info("rega data succesfully reloaded");
logger.info("socket.io --> broadcast reload");
emitEvent("reload");
} else {
logger.info("rega data succesfully loaded");
}
if (!rebuild) {
if (settings.regahss.pollData) {
pollRega();
}
initRpc();
if (!webserverUp) {
initWebserver();
}
if (triggerReload) {
logger.info("socket.io --> broadcast reload")
emitEvent("regaUp");
emitEvent("reload");
}
}
}
});
}
function initRpc() {
for (var i = 0; i < settings.binrpc.inits.length; i++) {
lastEvents[settings.binrpc.inits[i].id] = Math.floor((new Date()).getTime() / 1000);
}
if (!homematic && settings.ccuIp) {
homematic = new binrpc({
ccuIp: settings.ccuIp,
listenIp: settings.binrpc.listenIp,
listenPort: settings.binrpc.listenPort,
inits: settings.binrpc.inits,
methods: {
event: function (obj) {
if (!regaReady) { return; }
var timestamp = formatTimestamp();
var bidcos;
switch (obj[0]) {
case "io_cuxd":
case "CUxD":
lastEvents.io_cuxd = Math.floor((new Date()).getTime() / 1000);
stats.cuxd += 1;
bidcos = "CUxD." + obj[1] + "." + obj[2];
break;
case "io_rf":
lastEvents.io_rf = Math.floor((new Date()).getTime() / 1000);
stats.rf += 1;
bidcos = "BidCos-RF." + obj[1] + "." + obj[2];
break;
case "io_wired":
lastEvents.io_wired = Math.floor((new Date()).getTime() / 1000);
stats.wired += 1;
bidcos = "BidCos-Wired." + obj[1] + "." + obj[2];
break;
default:
//
}
if (settings.regahss.pollDataTriggerEnabled && bidcos == settings.regahss.pollDataTrigger) {
clearTimeout(pollTimer);
pollRega();
}
// STATE korrigieren
if (obj[2] == "STATE") {
if (obj[3] === "1" || obj[3] === 1) {
obj[3] = true;
} else if (obj[3] === "0" || obj[3] === 0) {
obj[3] = false;
}
}
// Get ReGa id
var regaObj = regaIndex.Name[bidcos];
if (regaObj && regaObj[0] && ignoreNextUpdate.indexOf(regaObj[0]) != -1) {
logger.verbose("ccu.io ignoring event dp "+regaObj[0]);
ignoreNextUpdate.splice(ignoreNextUpdate.indexOf(regaObj[0]), 1);
return;
}
// Logging
if (regaObj && regaObj[0] && settings.logging.enabled) {
if (!regaObjects[regaObj] || !regaObjects[regaObj].dontLog) {
var ts = Math.round((new Date()).getTime() / 1000);
devLog(ts, regaObj[0], obj[3]);
}
}
if (regaObj && regaObj[0]) {
var id = regaObj[0];
var val = obj[3];
logger.verbose("socket.io --> broadcast event "+JSON.stringify([id, val, timestamp, true]))
var event = [id, val, timestamp, true, timestamp];
if (datapoints[id]) {
if (datapoints[id][0] != val) {
// value changed
datapoints[id] = [val, timestamp, true, timestamp];
} else {
// no change - keep LastChange
datapoints[id] = [val, timestamp, true, datapoints[id][3]];
event = [id, val, timestamp, true, datapoints[id][3]];
}
} else {
datapoints[id] = [val, timestamp, true, timestamp];
}
emitEvent("event", event);
}
return "";
}
}
});
} else {
homematic.init();
}
initsDone = true;
updateStatus();
}
function uploadParser(req, res, next) {
var urlParts = url.parse(req.url, true);
var query = urlParts.query;
//console.log(query);
// get the temporary location of the file
var tmpPath = req.files.file.path;
logger.info("webserver <-- file upload "+req.files.file.name+" ("+req.files.file.size+" bytes) to "+tmpPath);
logger.info("webserver <-- file upload query params "+JSON.stringify(query));
var newName;
if (query.id) {
newName = query.id + "." + req.files.file.name.replace(/.*\./, "");
} else {
newName = req.files.file.name;
}
// set where the file should actually exists - in this case it is in the "images" directory
var targetPath = __dirname + "/" + query.path + newName;
logger.info("webserver move uploaded file "+tmpPath+" -> "+targetPath);
// move the file from the temporary location to the intended location
fs.rename(tmpPath, targetPath, function(err) {
if (err) throw err;
// delete the temporary file, so that the explicitly set temporary upload dir does not get filled with unwanted files
fs.unlink(tmpPath, function(err) {
if (err) throw err;
res.send('File uploaded to: ' + targetPath + ' - ' + req.files.file.size + ' bytes');
});
});
}
function findDatapoint(needle, hssdp) {
if (!datapoints[needle]) {
if (regaIndex.Name[needle]) {
// Get by Name
needle = regaIndex.Name[needle][0];
if (hssdp) {
// Get by Name and Datapoint
if (regaObjects[needle].DPs) {
return regaObjects[needle].DPs[hssdp];
} else {
return false;
}
}
} else if (regaIndex.Address[needle]) {
needle = regaIndex.Address[needle][0];
if (hssdp) {
// Get by Channel-Address and Datapoint
if (regaObjects[needle].DPs && regaObjects[needle].DPs[hssdp]) {
needle = regaObjects[needle].DPs[hssdp];
}
}
} else if (needle && needle.match(/[a-zA-Z-]+\.[0-9A-Za-z-]+:[0-9]+\.[A-Z_]+/)) {
// Get by full BidCos-Address
addrArr = needle.split(".");
if (regaIndex.Address[addrArr[1]]) {
needle = regaObjects[regaIndex.Address[addrArr[1]]].DPs[addArr[2]];
}
} else {
return false;
}
}
return needle;
}
function restApiPost(req, res) {
var path = req.params[0];
var tmpArr = path.split("/");
var command = tmpArr[0];
var response;
var responseType = "json";
var status = 500;
res.set("Access-Control-Allow-Origin", "*");
switch(command) {
case "setBulk":
response = [];
status = 200;
for (var item in req.body) {
var parts = item.split("/");
var dp = findDatapoint(parts[0], parts[1]);
if (dp == false) {
sres = {error: "datapoint "+item+" not found"};
} else if (req.body[item] === undefined) {
sres = {error: "no value given for "+item};
} else {
sres = {id:dp,value:req.body[item]};
setState(dp,req.body[item]);
}
response.push(sres);
}
break;
default:
response = {error: "command "+command+" unknown"};
}
switch (responseType) {
case "json":
res.json(response);
break;
case "plain":
res.set('Content-Type', 'text/plain');
res.send((typeof response == "object" && response.hasOwnProperty("value")) ? response.value.toString() : response);
break;
}
}
function restApiDelayedAnswer() {
clearTimeout(restApiDelayed.timer);
restApiDelayed.timer = null;
restApiDelayed.id = 0;
switch (restApiDelayed.responseType) {
case "json":
restApiDelayed.res.json(restApiDelayed.response);
break;
case "plain":
restApiDelayed.res.set('Content-Type', 'text/plain');
restApiDelayed.res.send((typeof restApiDelayed.response == "object" && restApiDelayed.response.hasOwnProperty("value")) ? restApiDelayed.response.value.toString() : restApiDelayed.response);
break;
}
restApiDelayed.res = null;
restApiDelayed.response = null;
}
function restApi(req, res) {
var path = req.params[0];
var tmpArr = path.split("/");
var command = tmpArr[0];
var response;
var wait = 0;
var responseType = "json";
var status = 500;
res.set("Access-Control-Allow-Origin", "*");
switch(command) {
case "getPlainValue":
responseType = "plain";
if (!tmpArr[1]) {
response = "error: no datapoint given";
break;
}
var dp = findDatapoint(tmpArr[1], tmpArr[2]);
if (!dp || !datapoints[dp]) {
response = "error: datapoint not found";
} else {
response = String(datapoints[dp][0]);
status = 200;
}
break;
case "get":
if (!tmpArr[1]) {
response = {error: "no object/datapoint given"};
break;
}
var dp = findDatapoint(tmpArr[1], tmpArr[2]);
if (!dp) {
response = {error: "object/datapoint not found"};
} else {
status = 200;
response = {id:dp};
if (datapoints[dp]) {
response.value = datapoints[dp][0];
response.ack = datapoints[dp][2];
response.timestamp = datapoints[dp][1];
response.lastchange = datapoints[dp][3];
}
if (regaObjects[dp]) {
for (var attr in regaObjects[dp]) {
response[attr] = regaObjects[dp][attr];
}
}
}
break;
case "getBulk":
if (!tmpArr[1]) {
response = {error: "no datapoints given"};
break;
}
status = 200;
response = {};
var dps = tmpArr[1].split(",");
for (var i = 0; i < dps.length; i++) {
var parts = dps[i].split(";");
dp = findDatapoint(parts[0], parts[1]);
if (dp) {
response[dps[i]] = {"val":datapoints[dp][0], "ts":datapoints[dp][3]};
}
}
break;
case "setPlain":
case "set":
if (!tmpArr[1]) {
response = {error: "object/datapoint not given"};
}
var dp = findDatapoint(tmpArr[1], tmpArr[2]);
var value;
if (req.query) {
value = req.query.value;
wait = req.query.wait || 0;
}
if (!value) {
if (command == "setPlain") {
response = "Error: no value given";
} else {
response = {error: "no value given"};
}
wait = 0;
} else {
if (value === "true") {
value = true;
} else if (value === "false") {
value = false;
} else if (!isNaN(value)) {
value = parseFloat(value);
}
setState(dp, value);
status = 200;
if (command == "setPlain") {
responseType = "plain";
}
response = {id: dp, value: value};
}
break;
case "toggle":
if (!tmpArr[1]) {
response = {error: "object/datapoint not given"};
}
var dp = findDatapoint(tmpArr[1], tmpArr[2]);
var value = datapoints[dp][0];
if (value === true) value = 1;
if (value === false) value = 0;
value = 1 - parseInt(value, 10);
setState(dp, value);
status = 200;
response = {id: dp, value: value};
break;
case "setBulk":
response = [];
status = 200;
for (var item in req.query) {
var parts = item.split("/");
var dp = findDatapoint(parts[0], parts[1]);
if (dp == false) {
sres = {error: "datapoint "+item+" not found"};