-
Notifications
You must be signed in to change notification settings - Fork 9
/
main.js
2175 lines (2038 loc) · 82.9 KB
/
main.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
/* 120824
/* jshint -W097 */
/* jshint strict:false */
/* global require */
/* global RRule */
/* global __dirname */
/* jslint node: true */
"use strict";
var utils = require('@iobroker/adapter-core');
var adapter;
var eNet = require(__dirname + "/lib/enet");
var Gateway = require(__dirname + "/lib/gateway");
var pollTimerStates = null;
var SyncRoomsAndScenes = false;
var ConnectionType_SSL = false;
var Connection_Port = 80;
var eNetType = "Server";
var crypto = require('crypto');
var SessionID = "";
var CounterID = "";
//var IBN = "";
var ncd = 1;
var Zaehler = 1;
var devtyp='';
var devUID='';
// weitere VAR's
var valuePathArray =[];
var devicePathArray=[];
var sceneActionPathArray=[];
var batteryPathArray=[];
var get_login_digest='{"jsonrpc":"2.0","method":"getDigestAuthentificationInfos","params":null,"id":"$$id$$"}';
var get_configuration='{"jsonrpc":"2.0", "method":"getCurrentConfiguration", "params":null, "id":"$$id$$"}';
var get_locations='{"jsonrpc":"2.0", "method":"getLocations", "params":{"locationUIDs":[]}, "id":"$$id$$"}';
var get_eventid='{"jsonrpc":"2.0", "method":"getDevicesWithParameterFilter", "params":{"deviceUIDs":["$$devuid$$"], "filter":".+\\\\.(SCV1|SCV2|SNA|PSN)\\\\[(.|1.|2.|3.)\\\\]+"}, "id":"$$id$$"}';
var get_devices='{"jsonrpc":"2.0", "method":"getDevices", "params":{"deviceUIDs":["$$devuid$$"]}, "id":"$$id$$"}';
var get_currentvalues='{"jsonrpc":"2.0", "method":"getCurrentValuesFromOutputDeviceFunction", "params":{"deviceFunctionUID":"$$eventuid$$"}, "id":"$$id$$"}';
var set_state='{"jsonrpc":"2.0", "method":"callInputDeviceFunction", "params":{"deviceFunctionUID":"$$UID$$", "values":[{"valueTypeID":"$$valueTypeID$$", "value":$$Wert$$}]}, "id":"$$id$$"}';
var set_client_role='{"jsonrpc":"2.0", "method":"setClientRole", "params":{"clientRole":"CR_VISU"}, "id":"$$id$$"}';
var register_value_change='{"jsonrpc":"2.0", "method": "registerEventValueChanged","params":{"valueUID":"$$uid$$"},"id":"$$id$$"}'
var request_events='{"jsonrpc":"2.0", "method":"requestEvents", "params":null, "id":"$$id$$"}'
var HTTPRequest = (function() {
var adapters = {
false: require('http'),
true: require('https'),
};
return function(connection_type) {
return adapters[adapter.config.connection_type_ssl]
}
}());
function startAdapter(options)
{
options = options || {};
Object.assign(options,{
name: "enet",
stateChange: function (id, state)
{
eNetType = adapter.config.devicetype;
if (eNetType == "Gateway")
{
var eNetChannelArray = id.split(".");
var eNetChannelTemp = eNetChannelArray[2];
if (eNetChannelTemp.search(/channel/g));
{
var eNetChannel = eNetChannelTemp.replace("channel", "");
if (state && !state.ack)
setGatewayChannel(adapter.config.ip, id, eNetChannel, state.val);
}
}
else if (eNetType == "Server")
{
if (id.indexOf('.action') > -1)
{
if (state && !state.ack)
{
var parent = id.substring(0,id.lastIndexOf('.'));
adapter.getForeignObject(parent, function (err, obj)
{
if (obj && obj.native && obj.native.sceneActionUID)
{
adapter.log.debug("Action: " + id + ", eNet Action UID: " + obj.native.sceneActionUID);
eNetServer_executeAction(obj.native.sceneActionUID);
adapter.setState(id,false,true)//true=ACK
}
});
}
}
if (id.indexOf('.value') > -1)
{
if (state && !state.ack)
{
var parent = id.substring(0,id.lastIndexOf('.'));
adapter.getForeignObject(parent, function (err, obj)
{
if (obj && obj.native && obj.native.Input_UID && obj.native.ValueType_ID)
{
adapter.log.debug("State Change ID: " + id + ", eNet Input UID: " + obj.native.Input_UID + " Value Type ID:" +obj.native.ValueType_ID + ", Value: " + state.val + ", Value type: " + typeof(state.val));
eNetServer_SetState(obj.native.Input_UID, obj.native.ValueType_ID, state.val);
}
});
}
}
}
},
unload: function (callback)
{
try
{
eNetType = adapter.config.devicetype;
if (eNetType == "Gateway")
{
clearInterval(pollTimerStates);
pollTimerStates = null;
}
else if (eNetType == "Server")
{
clearInterval(pollTimerStates);
pollTimerStates = null;
eNetServer_Logout();
}
adapter.setState("info.connection", false, true);
callback();
}
catch (e)
{
callback();
}
},
ready: function ()
{
ConnectionType_SSL = adapter.config.connection_type_ssl;
Connection_Port = adapter.config.connection_port;
eNetType = adapter.config.devicetype;
if (eNetType == "Gateway")
{
adapter.log.info("Running eNet Adapter Version " + adapter.version + ", Configured eNet Gateway: " + adapter.config.ip);
}
else if (eNetType == "Server")
{
if (ConnectionType_SSL)
{
adapter.log.info("Running eNet Adapter Version " + adapter.version + ", Configured eNet Server: " + adapter.config.ip + " (SSL/HTTPS), Username: " + adapter.config.username + " on port " + Connection_Port);
}
else
{
adapter.log.info("Running eNet Adapter Version " + adapter.version + ", Configured eNet Server: " + adapter.config.ip + ", Username: " + adapter.config.username + " on port " + Connection_Port);
}
}
init();
main();
}
});
adapter = new utils.Adapter(options);
return adapter;
}
function init()
{
if (adapter.config.ip)
{
eNetType = adapter.config.devicetype;
if (eNetType == "Gateway")
{
getGatewayDevices(adapter.config.ip)
}
else if (eNetType == "Server")
{
init_server(); // NUR EINMAL laufen!!!
eNetServer_Login();
}
}
}
function init_server()
{
adapter.log.debug('INIT SERVER Routine....')
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (!state)
{
adapter.setObjectNotExists("info.SessionID", {_id : adapter.namespace + "info.SessionID", type: "state", common: {name: "eNet Server Session ID", type: "string", role: "value", read: true, write: true},native: {}});
adapter.setState('info.SessionID', "", true);
}
});
var tempCounterID = adapter.getState("info.CounterID", function (err, state)
{
if (!state)
{
adapter.setObjectNotExists("info.CounterID", {_id : adapter.namespace + "info.CounterID", type: "state", common: {name: "eNet Server Counter ID", type: "string", role: "value", read: true, write: true}, native: {}});
adapter.setState('info.CounterID', "0", true);
}
});
/* var tempRE = adapter.getState("info.requestEvents", function (err, state)
{
if (!state)
{
adapter.setObjectNotExists("info.requestEvents", {_id : adapter.namespace + "info.requestEvents", type: "state", common: {name: "eNet requestEvents", type: "string", role: "value", read: true, write: true},native: {}});
adapter.setState('info.requestEvents', true, {unit: ''});
}
});
*/
}
function main()
{
adapter.subscribeStates("*");
if (parseInt(adapter.config.interval, 10))
{
eNetType = adapter.config.devicetype;
if (eNetType == "Gateway")
{
pollTimerStates = setInterval(getGatewayStates, parseInt(adapter.config.interval, 10));
}
else if (eNetType == "Server")
{
// nicht mehr notwendig, wegen RequestEvents
//pollTimerStates = setInterval(eNetServer_GetCurrentValues, parseInt(adapter.config.interval, 10));
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// //
/// BEGIN ENET SERVER ROUTINES //
/// //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GenerateRandom(len)
{
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabzdefghijklmnopqrstuvwxyz0123456789';
var token = '';
for (var i = 0; i < len; i++)
{
var randNum = Math.round(Math.random() * characters.length);
token += characters.substr(randNum, 1);
}
return token;
}
function Traverse(o)
{
for (var i in o)
{
if (o[i] !== null && typeof(o[i])=="object")
Traverse(o[i]);
}
}
function eNetServer_CalculateLoginDigest(challengeParams)
{
var ha1 = crypto.createHash('sha1').update(adapter.config.username+':Insta-NetBox:'+adapter.config.password).digest('hex');
var ha1u=ha1.toUpperCase();
var ha2 = crypto.createHash('sha1').update('POST:/jsonrpc//management' ).digest('hex');
var ha2u=ha2.toUpperCase();
var nc=('00000000' + ncd).slice(-8);
var cnonce=GenerateRandom(40);
var ha3 = crypto.createHash('sha1').update(ha1u + ':' + challengeParams.result.nonce + ':'+nc+':'+cnonce+':auth:' + ha2u).digest('hex');
var response=ha3.toUpperCase();
var authRequestParams = {username : adapter.config.username, realm : challengeParams.result.realm, nonce : challengeParams.result.nonce, uri : challengeParams.result.uri, qop : challengeParams.result.qop, opaque : challengeParams.result.opaque, response : response, nc : nc , cnonce: cnonce};
var user_login_digest='{"jsonrpc":"2.0", "method":"userLoginDigest", "params":{"userName":"'+adapter.config.username+'", "uri":"/jsonrpc//management", "qop":"auth", "cnonce":"'+authRequestParams.cnonce+'", "nc":"'+authRequestParams.nc+'", "response":"'+response+'", "realm":"Insta-NetBox", "nonce":"'+authRequestParams.nonce+'", "algorithm":"sha", "opaque":"'+authRequestParams.opaque+'"}, "id":"$$id$$"}';
return user_login_digest;
}
function eNetServer_SetClientRole()
{
var options =
{
host: adapter.config.ip,
port: Connection_Port,
rejectUnauthorized: false,
path: '/jsonrpc/management',
method:'POST',
headers: {'Content-Type': 'application/json'}
};
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
options.headers={'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
var tempZaehler = adapter.getState("info.CounterID", function (err, state)
{
if (state)
{
//Zaehler = state.val;
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in=set_client_role.replace('$$id$$',Zaehler.toString());
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (body)
{
try
{
adapter.log.debug('SetClientRole Body: ' + body);
var obj=JSON.parse(body);
if (obj.hasOwnProperty('error'))
{
adapter.log.error('SetClientRole Error: ' + obj.error.message)
}
}
catch(e)
{
adapter.log.error('Return from eNet Server: "' + e + '". Please try to restart the eNet server, change the connection type (HTTP/HTTPS) and check username/password!');
adapter.stop();
}
});
req.on('error', function(e)
{
adapter.log.error('Error with request: ' + e.message);
});
});
req.write(body_in);
req.end();
}
});
}
});
}
function eNetServer_SendLoginDigest(body)
{
var options = {host: adapter.config.ip,
port: Connection_Port,
rejectUnauthorized: false,
path: '/jsonrpc/management',
method:'POST',
headers: {'Content-Type': 'application/json'}
};
options.headers={'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (body)
{
adapter.log.debug('SendLoginDigest, Body: ' + body);
});
res.on('end', function () {
console.log('Body: ' + body);
eNetServer_SetClientRole();
});
req.on('error', function(e) {
adapter.log.error('Error with request SendLoginDigest: ' + e.message);
});
});
req.write(body);
req.end();
}
function eNetServer_delTree(projekt)
{
adapter.getStates(adapter.namespace + "."+projekt+".*", function (err, states)
{
var toDelete = [];
for (var id in states)
{
//toDelete.push(id);
//var id = states.pop();
//adapter.log.debug('Lösche Objekt: '+id)
//adapter.log.debug('Lösche State: '+id)
adapter.delObject(id, function (err)
{
adapter.log.debug('Lösche Objekt: '+id)
adapter.delState(id, function (err)
{
adapter.log.debug('Lösche State: '+id)
});
});
}
});
}
function eNetServer_Login()
{
adapter.log.info("Starting Login into eNet Server");
var options = {
host: adapter.config.ip,
port: Connection_Port,
rejectUnauthorized: false,
path: '/jsonrpc/management',
method:'POST',
headers: {'Content-Type': 'application/json'}
};
options.headers={'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
var tempZaehler = adapter.getState("info.CounterID", function (err, state)
{
if (state)
{
try
{
//Zaehler = state.val;
var body = get_login_digest.replace('$$id$$', Zaehler.toString());
var body_out='';
var req = HTTPRequest().request(options, function(res)
{
try
{
SessionID = res.headers['x-clientcredentials-sessionid'].toString();
adapter.setState('info.SessionID', SessionID, false);
res.setEncoding('utf8');
res.on('data', function (data)
{
body_out += data;
});
res.on('end', function ()
{
adapter.log.debug('Login Body: ' + body_out);
var challengeParams = JSON.parse(body_out);
var login_digest= eNetServer_CalculateLoginDigest(challengeParams);
Zaehler++;
login_digest = login_digest.replace("$$id$$",Zaehler.toString());
adapter.log.debug('Login Digest Login: ' + login_digest);
adapter.setState('info.CounterID', Zaehler.toString(), true);
eNetServer_SendLoginDigest(login_digest);
adapter.setState("info.connection", true, true);
adapter.setState("info.requestEvents", true, true);
//eNetServer_getProject();
//eNetServer_getScenes('','')
eNetServer_GetLocations();
eNetServer_RegisterSceneAction('registerEventSceneActionCreated')
eNetServer_RegisterSceneAction('registerEventSceneActionDeleted')
eNetServer_RegisterSceneAction('registerEventSceneActionChanged')
eNetServer_RegisterDeviceFunction('registerEventDeviceBatteryStateChanged','null')
});
req.on('error', function(e)
{
adapter.log.error('Error with request Login: ' + e.message);
adapter.setState("info.connection", false, true);
});
}
catch(e)
{
adapter.log.error('Error on connecting or logging in to eNet server: ' + e.message + '. Maybe you can try HTTP or non-HTTPS connection?');
adapter.stop();
}
});
req.write(body);
req.end();
}
catch(e)
{
adapter.log.error('Error on connecting or logging in to eNet server: ' + e.message + '. Maybe you can try HTTP or non-HTTPS connection?');
adapter.stop();
}
}
});
}
/*function eNetServer_getInputFTypfromOutputFTyp(pfad,InputTyp2InputID,typeID)
{
var options = {host: adapter.config.ip, port: Connection_Port, rejectUnauthorized: false, path: '/jsonrpc/visualization', method:'POST', headers: {'Content-Type': 'application/json'}};
var reqstring='{"jsonrpc":"2.0", "method": "getInputDeviceFunctionTypeIDCorrespondingToOutputDeviceFunctionType","params":{ "outputDeviceFunctionTypeID": "$$FTyp$$"},"id":"$$id$$"}'
var body_out = ''
//adapter.log.info("Laenge::"+JSON.stringify(InputTyp2InputID))
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
var tempCounterID = adapter.getState("info.CounterID", function (err, state)
{
if (state)
{
CounterID = state.val;
options.headers = {'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
//Zaehler = CounterID
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in = reqstring.replace('$$id$$',Zaehler.toString());
var body_in = body_in.replace('$$FTyp$$',typeID);
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (data)
{
body_out += data;
});
res.on('end', function ()
{
//adapter.log.debug('OTyp2ITyp Body_out: ' + body_out);
// hier setzen
var obj=JSON.parse(body_out);
if (obj['result']['inputDeviceFunctionTypeID'] != null)
{
// adapter.log.debug('INPUT-TYP:'+obj['result']['inputDeviceFunctionTypeID'])
var itypID=obj['result']['inputDeviceFunctionTypeID']
adapter.log.debug('setze inputUID:'+InputTyp2InputID[itypID]+'fuer Pfad:'+pfad)
//adapter.setObjectNotExists(pfad, {_id : adapter.namespace + pfad, type: "state", common: {name: pfad, type: "mixed", role: "value"}});
adapter.getObject(pfad, function(err,obj)
{
if (err) log('Cannot read object: ' + err);
//adapter.log.debug('OBJ-Name:'+obj.common.name)
obj.native.Input_UID=InputTyp2InputID[itypID]
adapter.extendObject(pfad,obj,function(err){
if (err) log('Cannot write object (InputValue_UID: ' + err);
})
})
} else {
//adapter.log.debug('Cannot set Input_UID for:'+pfad)
}
});
req.on('error', function(e)
{
adapter.log.error("eNet Server OTyp2Ityp " + e.message);
});
});
req.write(body_in);
//adapter.log.debug('getINputfromOutput Pfad:'+pfad)
//adapter.log.debug('getINputfromOutput BODY:'+body_in)
req.end();
}
});
}
});
}
*/
function eNetServer_getifUIDfromofUID(pfad,oftUID)
{
var options = {host: adapter.config.ip, port: Connection_Port, rejectUnauthorized: false, path: '/jsonrpc/visualization', method:'POST', headers: {'Content-Type': 'application/json'}};
var reqstring='{"jsonrpc":"2.0", "method": "getInputDeviceFunctionUIDCorrespondingToOutputDeviceFunction","params":{ "deviceFunctionUID": "$$typeID$$"},"id":"$$id$$"}'
var body_out = ''
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
var tempCounterID = adapter.getState("info.CounterID", function (err, state)
{
if (state)
{
CounterID = state.val;
options.headers = {'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
//Zaehler = CounterID
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in = reqstring.replace('$$id$$',Zaehler.toString());
var body_in = body_in.replace('$$typeID$$',oftUID);
//adapter.log.debug("suche NameandBody:"+typeID)
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (data)
{
body_out += data;
});
res.on('end', function ()
{
//adapter.log.debug('NameandValue Body_out: ' + body_out);
// hier setzen
var hobj=JSON.parse(body_out);
if (hobj.hasOwnProperty('error')) // kommt bei Sensor vor, sollte eigentlich lt. Doku null kommen
{
//adapter.log.debug('kein IF für OF: '+pfad+' Error: ' + hobj.error.message)
} else
{
if (hobj['result']['deviceFunctionUID'] != null)
{
//adapter.log.debug('Name aendern: '+hobj['result']['name'])
//adapter.log.debug("PFAD:"+pfad)
var idfUID=hobj['result']['deviceFunctionUID']
adapter.getObject(pfad, function(err,obj)
{
if (err) log('Cannot read object: ' + err);
//adapter.log.debug('OBJ-Name:'+obj.common.name)
obj.native.Input_UID=idfUID
adapter.extendObject(pfad,obj,function(err){
if (err) log('Cannot write object: ' + err);
})
})
}
}
});
req.on('error', function(e)
{
adapter.log.error("eNet Server OTyp2Ityp " + e.message);
});
});
req.write(body_in);
//adapter.log.debug('NameandValue Pfad:'+pfad)
//adapter.log.debug('NameandValue BODY:'+body_in)
req.end();
}
});
}
});
}
function eNetServer_getNameAndValueTypeIDsFromDeviceFunctionType(pfad,typeID)
{
var options = {host: adapter.config.ip, port: Connection_Port, rejectUnauthorized: false, path: '/jsonrpc/visualization', method:'POST', headers: {'Content-Type': 'application/json'}};
var reqstring='{"jsonrpc":"2.0", "method": "getNameAndValueTypeIDsFromDeviceFunctionType","params":{ "deviceFunctionTypeID": "$$typeID$$"},"id":"$$id$$"}'
var body_out = ''
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
var tempCounterID = adapter.getState("info.CounterID", function (err, state)
{
if (state)
{
CounterID = state.val;
options.headers = {'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
//Zaehler = CounterID
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in = reqstring.replace('$$id$$',Zaehler.toString());
var body_in = body_in.replace('$$typeID$$',typeID);
//adapter.log.debug("suche NameandBody:"+typeID)
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (data)
{
body_out += data;
});
res.on('end', function ()
{
//adapter.log.debug('NameandValue Body_out: ' + body_out);
// hier setzen
var hobj=JSON.parse(body_out);
if (hobj['result']['name'] != null)
{
//adapter.log.debug('Name aendern: '+hobj['result']['name'])
//adapter.log.debug("PFAD:"+pfad)
var name=hobj['result']['name']
var valueTypeID=hobj['result']['valueTypeIDs'][0]
adapter.getObject(pfad, function(err,obj)
{
if (err) log('Cannot read object: ' + err);
//adapter.log.debug('OBJ-Name:'+obj.common.name)
obj.common.name=name;
obj.native.ValueType_ID=valueTypeID
adapter.extendObject(pfad,obj,function(err){
if (err) log('Cannot write object: ' + err);
})
})
}
});
req.on('error', function(e)
{
adapter.log.error("eNet Server OTyp2Ityp " + e.message);
});
});
req.write(body_in);
//adapter.log.debug('NameandValue Pfad:'+pfad)
//adapter.log.debug('NameandValue BODY:'+body_in)
req.end();
}
});
}
});
}
function eNetServer_getScenes(projekt,uids)
{
var options =
{
host: adapter.config.ip,
port: Connection_Port,
rejectUnauthorized: false,
path: '/jsonrpc/visualization/app_scene',
method:'POST',
headers: {'Content-Type': 'application/json'}
};
var reqstring='{"jsonrpc":"2.0", "method":"getSceneActions", "params": {"sceneActionUIDs":[$$uids$$]}, "id":"$$id$$"}'
var body_out = ''
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
options.headers = {'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
//Zaehler = CounterID
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in = reqstring.replace('$$id$$',Zaehler.toString());
var body_in = body_in.replace('$$uids$$',uids);
adapter.log.debug("suche Szenen............fuer:"+projekt)
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (data)
{
body_out += data;
});
res.on('end', function ()
{
var sobj=JSON.parse(body_out);
//adapter.log.debug("Szene:::::"+body_out)
var anzScene=sobj['result']['sceneActions'].length
for (var i=0;i<anzScene;i++)
{
var scUID=sobj['result']['sceneActions'][i]['uid']
var scName=sobj['result']['sceneActions'][i]['name']
var scstatus=sobj['result']['sceneActions'][i]['statusValue']['value']
//adapter.log.debug("SzeneName:"+scName)
if (scName.indexOf(']')> 0) // nicht vom System angelegt
{
var end=scName.indexOf(']')+1
if ( end > 0 ) {scName=scName.substr(end,scName.length)}
adapter.log.debug("Szene:"+scName)
var pfad='Scenes.'+scName
adapter.setObjectNotExists(pfad, {_id : adapter.namespace + pfad, type: "folder", common: {name: pfad, read: true, write: true},native: {sceneActionUID:scUID,sceneActionName:scName}});
adapter.setObjectNotExists(pfad+'.action', {_id : adapter.namespace + pfad+'.action', type: "state", common: {name: scName, type: "string", role: "value", read: true, write: true},native: {sceneUID: scUID}});
adapter.setState(pfad+'.action', 'false', true);
adapter.setObjectNotExists(pfad+'.status', {_id : adapter.namespace + pfad+'.status', type: "state", common: {name: scName, type: "string", role: "value", read: true, write: true},native: {sceneUID: scUID}});
adapter.setState(pfad+'.status', scstatus, true);
sceneActionPathArray[scUID]=pfad;
//eNetServer_RegisterSceneAction('registerEventSceneActionChanged')
}
}
});
req.on('error', function(e)
{
adapter.log.error("eNet Szene " + e.message);
});
})
req.write(body_in);
//adapter.log.debug('NameandValue Pfad:'+pfad)
adapter.log.debug('Scene BODY:'+body_in)
req.end();
}
})
}
function eNetServer_getProject()
{
var options =
{
host: adapter.config.ip,
port: Connection_Port,
rejectUnauthorized: false,
path: '/jsonrpc/visualization',
method:'POST',
headers: {'Content-Type': 'application/json'}
};
var reqstring='{"jsonrpc":"2.0", "method":"getCurrentProject", "params": null, "id":"$$id$$"}'
var body_out = ''
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
options.headers = {'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
//Zaehler = CounterID
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in = reqstring.replace('$$id$$',Zaehler.toString());
//adapter.log.debug("lese Projet")
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (data)
{
body_out += data;
});
res.on('end', function ()
{
var sobj=JSON.parse(body_out);
var projekt=sobj[result][projectName]
projekt =projekt.replace('. ','_').replace('.','_').replace(' ','_');
adapter.log.debug("... jetzt noch Szenen suchen....für "+projekt);
eNetServer_getScenes(projekt);
});
req.on('error', function(e)
{
adapter.log.error("eNet Server Projekt" + e.message);
});
req.write(body_in);
//adapter.log.debug('NameandValue Pfad:'+pfad)
adapter.log.debug('getProjet BODY_in:'+body_in)
req.end();
})
}
});
}
function normierung(form,wert) {
if (form.indexOf("VOLT") > 0 )
{
return (parseFloat(wert)/1000.).toFixed(1);
}
else if (form.indexOf("LUX") > 0 )
{
return parseFloat(wert).toFixed(0);
}
else if (form.indexOf("CURR") > 0 )
{
return (parseFloat(wert)/1000.).toFixed(1);
}else {
return wert;
}
}
function eNetServer_RequestEvents()
{
var options =
{
host: adapter.config.ip,
port: Connection_Port,
rejectUnauthorized: false,
path: '/jsonrpc/visualization',
method:'POST',
headers: {'Content-Type': 'application/json'}
};
var body='';
var tempSessionID = adapter.getState("info.SessionID", function (err, state)
{
if (state)
{
SessionID = state.val;
options.headers={'Content-Type':'application/json; charset=utf-8','Cookie':'uEhaA=true; pbAudioFalg=ON; VideoFormatAVN=ActiveX; INSTASESSIONID='+SessionID+'; downloadFinished=true; rememberMe=true'};
var tempZaehler = adapter.getState("info.CounterID", function (err, state)
{
if (state)
{
//Zaehler = state.val;
Zaehler++;
adapter.setState('info.CounterID', Zaehler.toString(), true);
var body_in=request_events.replace('$$id$$',Zaehler.toString());
var req = HTTPRequest().request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (data) {
body += data;
});
res.on('end', function ()
{
try
{
//adapter.log.debug('RequestEvents Body: ' + body);
var obj=JSON.parse(body);
if (obj.hasOwnProperty('error'))
{
if (obj.error.code != -29999 ) {
adapter.log.debug('Request_events Error: '+obj.error.message+' '+obj.error.code)
} else {
// DEBUG console.log ( "TimeOut-> kein change device....")
//request_events(); // Neustart, -29999 = TIMEOUT, also keine events
}
}
else
{
//adapter.log.debug(body);
var i =obj['result']['events'].length
for (var y=0;y<i;y++)
{
adapter.log.debug('EVENT: '+obj['result']['events'][y]['event'])// valueChanged und deviceFunctionCalled
var event =obj['result']['events'][y]['event']
switch (event)
{
case "deviceBatteryStateChanged":
{
var deviceUID=obj['result']['events'][y]['eventData']['deviceUID']
var batteryState=obj['result']['events'][y]['eventData']['batteryState']
//adapter.log.debug(valueUID+' '+value)
adapter.log.info('Change:'+batteryPathArray[deviceUID]+' setze auf:'+batteryState);
adapter.setState(batteryPathArray[deviceUID],batteryState,true)//true=ACK
break;
}
case "valueChanged":
{
var valueUID=obj['result']['events'][y]['eventData']['valueUID']
var value=obj['result']['events'][y]['eventData']['value']
//adapter.log.debug(valuePathArray[valueUID]+'.value')
if (valuePathArray[valueUID] !== 'undefined')
{
adapter.getObject (valuePathArray[valueUID]+'.value',function (err,obj){
if (obj === null)
{
adapter.log.debug('ERROR value Changed: '+valueUID+' ->Object noch nicht vorhanden')
} else {
//var obj = adapter.getObject(valuePathArray[valueUID]+'.value')
//adapter.log.debug(JSON.stringify(obj))
var form=obj.common.name
//adapter.log.debug(form) })
//adapter.log.debug('Form:'+form)
var wert=normierung(form,value)
adapter.log.info('Change:'+valuePathArray[valueUID]+'.value setze auf:'+wert);
adapter.setState(valuePathArray[valueUID]+'.value',wert.toString(),true)//true=ACK
}
});
}
break;
}
case "sceneActionChanged":
{
var sceneActionUID=obj['result']['events'][y]['eventData']['sceneActionUID']
//adapter.log.debug('SzenenÄnderung für:'+sceneActionPathArray[sceneActionUID]);
adapter.getStates(sceneActionPathArray[sceneActionUID] + ".*", function (err, states)
{
//var toDelete = [];
for (var id in states)
{
//toDelete.push(id);
//var id = states.pop();
adapter.delObject(id, function (err)
{
adapter.delState(id, function (err)
{
});
});
}
adapter.delObject(sceneActionPathArray[sceneActionUID], function (err){})
eNetServer_getScenes('','"'+sceneActionUID+'"')
});
break;
}
case "sceneActionDeleted":
{
var sceneActionUID=obj['result']['events'][y]['eventData']['sceneActionUID']
adapter.log.debug('Szene Löschen für:'+sceneActionPathArray[sceneActionUID]);
adapter.getStates(sceneActionPathArray[sceneActionUID] + ".*", function (err, states)
{
var toDelete = [];
for (var id in states)
{
//adapter.log.debug('ID in States:'+id)
toDelete.push(id);
//var id = states.pop();
adapter.delObject(id, function (err)
{
adapter.delState(id, function (err)
{
});
});
}
adapter.delObject(sceneActionPathArray[sceneActionUID], function (err){})
});
break;
}
case "sceneActionCreated":
{
var sceneActionUID=obj['result']['events'][y]['eventData']['sceneActionUID']
adapter.log.debug('Szene NEU für:'+sceneActionUID);
eNetServer_getScenes('','"'+sceneActionUID+'"')
break;
}
}
}
}
var tempreqevent =adapter.getState("info.requestEvents", function (err, state)
{
if (state.val){
//adapter.log.debug("requestEvents ReStart....")
eNetServer_RequestEvents()
} else {
adapter.log.debug("requestEvents gestoppt....")
}
});
}
catch(e)
{
adapter.log.error('Return from eNet Server: "' + e + '". Please try to restart the eNet server, change the connection type (HTTP/HTTPS) and check username/password!');
adapter.stop();