-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathToonbotApp.qml
1367 lines (1102 loc) · 49.8 KB
/
ToonbotApp.qml
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
import QtQuick 2.1
import qb.components 1.0
import qb.base 1.0
import FileIO 1.0
import BxtClient 1.0
App {
id: toonbotApp
property url tileUrl : "ToonbotTile.qml"
property url thumbnailIcon: "qrc:/tsc/toonbotSmallNoBG.png"
property url toonbotScreenUrl : "ToonbotScreen.qml"
property url toonbotConfigurationScreenUrl : "ToonbotConfigurationScreen.qml"
property url toonbotSecurityScreenUrl : "ToonbotSecurityScreen.qml"
property url trayUrl : "ToonbotTray.qml"
property ToonbotConfigurationScreen toonbotConfigurationScreen
property ToonbotSecurityScreen toonbotSecurityScreen
property ToonbotScreen toonbotScreen
// for Tile
property string tileStatus : "Wachten op data....."
property string tileLastcmd : ""
property string tileBotName : ""
property variant telegramData
property variant getMeData
property variant thermostatInfoData
property variant currentUsageData
property variant todayGasUsageData
property variant todayElectLTUsageData
property variant todayElectNTUsageData
property string lastUpdateId // id from last receivede telegram message, so last message will not be retrieved again
property string chatId // used to send message to right chat
// settings
property string toonbotTelegramToken : "" // Telegram Bot token
property int toonbotRefreshIntervalSeconds : 60 // interval to retrieve telegram messages
property bool enableSystray : false
property bool enableRefresh : false // enable retrieving Telegram messages
property bool enableSecurity : false // enable security (check chatid's)
property string toonbotAlarmChatId : "" // ChatId for alarms
property bool enableSmokeAlarm : false // enable smoke alarm
// user settings from config file
property variant toonbotSettingsJson
property string toonbotLastUpdateTime
property string toonbotLastResponseStatus : "N/A"
property bool refreshGetMeDone : false // GetMe succesvol received
property int numberMessagesOnScreen : (isNxt ? 15 : 12)
property bool debugOutput : false // Show console messages. Turn on in settings file !
property variant usersNames : [] // array of allowed user or group names
property variant usersChatIds : [] // array of allowed corresponding chatid
// signal, used to update the listview
signal toonbotUpdated()
QtObject {
id: p
property string eventmgrUuid
property string lastNotifyUuid
property string lastNotifyTime
}
property variant linkedSmokedetectors: []
FileIO {
id: toonbotSettingsFile
source: "file:///mnt/data/tsc/toonbot.userSettings.json"
}
FileIO {
id: toonbotLastUpdateIdFile
source: "file:///tmp/toonbot-lastUpdateId.txt"
}
Component.onCompleted: {
// read user settings
try {
toonbotSettingsJson = JSON.parse(toonbotSettingsFile.read());
if (toonbotSettingsJson['TrayIcon'] == "Yes") {
enableSystray = true
} else {
enableSystray = false
}
if (toonbotSettingsJson['RefreshOn'] == "Yes") {
enableRefresh = true
} else {
enableRefresh = false
}
toonbotTelegramToken = toonbotSettingsJson['Token'];
toonbotRefreshIntervalSeconds = toonbotSettingsJson['RefreshIntervalSeconds'];
if (toonbotSettingsJson['DebugOn'] == "Yes") {
debugOutput = true
} else {
debugOutput = false
}
if (toonbotSettingsJson['Security'] == "Yes") {
enableSecurity = true
} else {
enableSecurity = false
}
var tmpusersNames = [];
var tmpusersChatIds = [];
for (var i = 0; i < toonbotSettingsJson['Users'].length; i++) {
var tmp = toonbotSettingsJson['Users'][i].split("@");
tmpusersNames.push(tmp[0]);
tmpusersChatIds.push(tmp[1]);
}
usersNames = tmpusersNames;
usersChatIds = tmpusersChatIds;
toonbotAlarmChatId = toonbotSettingsJson['AlarmChatId'];
if (toonbotSettingsJson['SmokeAlarm'] == "Yes") {
enableSmokeAlarm = true
} else {
enableSmokeAlarm = false
}
} catch(e) {
}
startGetTelegramUpdatesTimer();
// Only when a Telegram token is there
if ( toonbotTelegramToken.length > 0 ) {
readLastUpdateId();
} else {
enableRefresh = false;
tileStatus = "Token mist, zie instellingen";
}
}
function init() {
registry.registerWidget("tile", tileUrl, this, null, {thumbLabel: "ToonBot", thumbIcon: thumbnailIcon, thumbCategory: "general", thumbWeight: 30, baseTileWeight: 10, thumbIconVAlignment: "center"});
registry.registerWidget("screen", toonbotScreenUrl, this, "toonbotScreen");
registry.registerWidget("screen", toonbotConfigurationScreenUrl, this, "toonbotConfigurationScreen");
registry.registerWidget("screen", toonbotSecurityScreenUrl, this, "toonbotSecurityScreen");
registry.registerWidget("systrayIcon", trayUrl, this, "toonbotTray");
}
function saveSettings() {
// save user settings
if (debugOutput) console.log("********* ToonBot saveSettings");
var tmpTrayIcon = "";
var tmpRefreshOn = "";
var tmpDebugOn = "";
var tmpSecurity = "";
var tmpSmokeAlarm = "";
if (enableSystray == true) {
tmpTrayIcon = "Yes";
} else {
tmpTrayIcon = "No";
}
if (enableRefresh == true) {
tmpRefreshOn = "Yes";
} else {
tmpRefreshOn = "No";
}
if (debugOutput == true) {
tmpDebugOn = "Yes";
} else {
tmpDebugOn = "No";
}
if (enableSecurity == true) {
tmpSecurity = "Yes";
} else {
tmpSecurity = "No";
}
var tmpUsers = [];
for (var i = 0; i < usersNames.length; i++) {
tmpUsers.push(usersNames[i] + "@" + usersChatIds[i]);
}
if (enableSmokeAlarm == true) {
tmpSmokeAlarm = "Yes";
} else {
tmpSmokeAlarm = "No";
}
var tmpUserSettingsJson = {
"Token" : toonbotTelegramToken,
"RefreshIntervalSeconds" : toonbotRefreshIntervalSeconds,
"TrayIcon" : tmpTrayIcon,
"RefreshOn" : tmpRefreshOn,
"DebugOn" : tmpDebugOn,
"Security" : tmpSecurity,
"Users" : tmpUsers,
"AlarmChatId" : toonbotAlarmChatId,
"SmokeAlarm" : tmpSmokeAlarm
}
toonbotSettingsFile.write(JSON.stringify(tmpUserSettingsJson ));
}
// Remove a user or group from the list of allowed users
function deleteUsers(itemIndex) {
if (debugOutput) console.log("********* ToonBot deleteUsers");
// delete the item at index itemIndex from both arrays
var tmpUsers = [];
var tmpChatIds = [];
for (var i = 0; i < usersNames.length; i++) {
if (i !== itemIndex) { // skip the item to be deleted
tmpUsers.push(usersNames[i]);
tmpChatIds.push(usersChatIds[i]);
}
}
usersNames = tmpUsers;
usersChatIds = tmpChatIds;
if (debugOutput) console.log("********* ToonBot deleteUsers left: " + usersNames.length );
}
// Is chat id in the list of allowed users/groups?
function inUsersChatIdsList(chat_id) {
if (debugOutput) console.log("********* ToonBot inUsersChatIdsList");
for (var i = 0; i < usersChatIds.length; i++) {
if (usersChatIds[i] == chat_id ) {
return true;
}
}
return false;
}
// return number of users in list of allowed users/groups
function numberOfUsersInList() {
if (debugOutput) console.log("********* ToonBot numberOfUsersInList: " + usersNames.length );
return usersNames.length;
}
// get some information about Bot and test Token
function refreshGetMe() {
if (debugOutput) console.log("********* ToonBot refreshGetMe");
// clear Tile
tileStatus = "Ophalen GetMe.....";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://api.telegram.org/bot"+toonbotTelegramToken+"/getMe", true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) if (debugOutput) console.log("********* ToonBot refreshGetMe readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
// save response
var doc = new XMLHttpRequest();
doc.open("PUT", "file:///tmp/toonbot-response1.json");
doc.send(xmlhttp.responseText);
if (xmlhttp.status == 200) {
var response = xmlhttp.responseText;
if (debugOutput) if (debugOutput) console.log("********* ToonBot refreshGetMe response" + response );
// if no json but html received
try {
getMeData = JSON.parse(xmlhttp.responseText);
if (getMeData['ok']) {
if (debugOutput) console.log("********* ToonBot refreshGetMe telegramData data found");
tileBotName = getMeData['result']['first_name'];
// username is optional
try {
tileBotName = tileBotName + "@" + getMeData['result']['username'];
}
catch(e) {}
refreshGetMeDone = true;
getTelegramUpdates();
} else {
tileStatus = "Ophalen GetMe mislukt.....";
refreshGetMeTimer.start(); // try again
if (debugOutput) console.log("********* ToonBot refreshGetMe failed, not ok received. try again");
}
}
catch(e) {
tileStatus = "Ophalen GetMe mislukt.....";
refreshGetMeTimer.start(); // try again
if (debugOutput) console.log("********* ToonBot refreshGetMe failed, no JSON received. try again");
}
} else {
tileStatus = "Ophalen GetMe mislukt.....";
refreshGetMeTimer.start(); // try again
if (debugOutput) console.log("********* ToonBot refreshGetMe failed, no http status 200. try again");
}
}
}
xmlhttp.send();
}
// get the Telegram messages after lastUpdateId
function getTelegramUpdates() {
var url;
if (debugOutput) console.log("********* ToonBot getTelegramUpdates");
if ( toonbotTelegramToken.length == 0 ) {
tileStatus = "Token mist, zie instellingen"
return;
}
tileStatus = "Ophalen messages.....";
var xmlhttp = new XMLHttpRequest();
if (lastUpdateId.length > 0) {
var updId = parseInt(lastUpdateId) + 1;
if (debugOutput) console.log("********* ToonBot getTelegramUpdates use lastUpdateId: " + updId);
url = "https://api.telegram.org/bot"+toonbotTelegramToken+"/getUpdates?allowed_updates=[\"message\"]&offset=" + updId;
} else {
url = "https://api.telegram.org/bot"+toonbotTelegramToken+"/getUpdates?allowed_updates=[\"message\"]&offset=-1";
if (debugOutput) console.log("********* ToonBot getTelegramUpdates use offset=-1: " );
}
// Important: allowed_updates= will be remembered, even if it is removed again. Reset with allowed_updates=[] (empty array)
if (debugOutput) console.log("********* ToonBot getTelegramUpdates url: " + url);
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot getTelegramUpdates readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
toonbotLastResponseStatus = xmlhttp.status;
// save response
var doc = new XMLHttpRequest();
doc.open("PUT", "file:///tmp/toonbot-response2.json");
doc.send(xmlhttp.responseText);
var now = new Date();
toonbotLastUpdateTime = now.toLocaleString('nl-NL');
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot getTelegramUpdates response " + xmlhttp.responseText );
telegramData = JSON.parse(xmlhttp.responseText);
if (telegramData['ok'] && telegramData['result'].length > 0) {
if (debugOutput) console.log("********* ToonBot getTelegramUpdates telegramData data found");
tileStatus = "Verwerken messages.....";
processTelegramUpdates();
} else {
if (debugOutput) console.log("********* ToonBot getTelegramUpdates telegramData data found but empty");
tileStatus = "Gereed";
}
} else {
if (debugOutput) console.log("********* ToonBot getTelegramUpdates fout opgetreden.");
tileStatus = "Ophalen messages mislukt.....";
}
}
}
xmlhttp.send();
}
function getSecondsBetweenDates(endDate, startDate) {
var diff = endDate.getTime() - startDate.getTime();
if (debugOutput) console.log("********* ToonBot getSecondsBetweenDates diff: " + (diff/1000));
return (diff / 1000);
}
function processTelegramUpdates(){
var i;
var messageDate;
var update_id = lastUpdateId;
var timediff;
var fromName;
if (debugOutput) console.log("********* ToonBot processTelegramUpdates results: " + telegramData['result'].length);
var now = new Date();
for (i = 0; i <telegramData['result'].length; i++) {
update_id = telegramData['result'][i]['update_id'];
if (debugOutput) console.log("********* ToonBot processTelegramUpdates update_id:" + update_id );
if( !telegramData['result'][i].hasOwnProperty('message')){
if (debugOutput) console.log("********* ToonBot processTelegramUpdates object message not found. Skip this one.");
continue;
}
if( !telegramData['result'][i]['message'].hasOwnProperty('text')){
if (debugOutput) console.log("********* ToonBot processTelegramUpdates object text not found. Skip this one.");
continue;
}
fromName = "";
// get current chatid. can be different when using a group
chatId = telegramData['result'][i]['message']['chat']['id']
if (debugOutput) console.log("********* ToonBot processTelegramUpdates chatId:" + chatId );
var date = telegramData['result'][i]['message']['date'];
var text = telegramData['result'][i]['message']['text'];
// when using the bot in a group then @<botusername> will be added to the text. Remove it.
text = text.split('@')[0];
try {
if (telegramData['result'][i]['message']['chat']['type'] == "private") {
fromName = telegramData['result'][i]['message']['chat']['first_name'];
fromName = fromName + " " + telegramData['result'][i]['message']['chat']['last_name'];
} else if (telegramData['result'][i]['message']['chat']['type'] == "group") {
fromName = telegramData['result'][i]['message']['chat']['title']; // group name
} else { // do not know if this is possible. Just in case
fromName = telegramData['result'][i]['message']['from']['first_name'];
fromName = fromName + " " + telegramData['result'][i]['message']['from']['last_name'];
}
}
catch(e) {}
if (debugOutput) console.log("********* ToonBot processTelegramUpdates i:" + i );
if (debugOutput) console.log("********* ToonBot processTelegramUpdates date:" + date );
if (debugOutput) console.log("********* ToonBot processTelegramUpdates text:" + text );
if (debugOutput) console.log("********* ToonBot processTelegramUpdates fromName:" + fromName );
messageDate = new Date(date*1000);
timediff = getSecondsBetweenDates(now,messageDate);
// do not process too old messages
if ( timediff > (toonbotRefreshIntervalSeconds * 10)) {
// discard message, too old
if (debugOutput) console.log("********* ToonBot processTelegramUpdates discard message");
continue;
}
addCommandToList(text, update_id, fromName, chatId);
processCommand(text,update_id, chatId);
}
if (update_id != lastUpdateId ) {
lastUpdateId = update_id;
saveLastUpdateId(lastUpdateId) // save id which can be used it Toon is restarted
}
tileStatus = "Gereed";
}
function getThermostatInfo() {
if (debugOutput) console.log("********* ToonBot getThermostatInfo");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/happ_thermstat?action=getThermostatInfo", true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot getThermostatInfo readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot getThermostatInfo response " + xmlhttp.responseText );
thermostatInfoData = JSON.parse(xmlhttp.responseText);
if (thermostatInfoData['result'] === "ok" ) {
if (debugOutput) console.log("********* ToonBot getThermostatInfo thermostatInfoData data found");
processThermostatInfo();
} else {
if (debugOutput) console.log("********* ToonBot getThermostatInfo thermostatInfoData data found but status not ok");
}
} else {
if (debugOutput) console.log("********* ToonBot getThermostatInfo fout opgetreden.");
tileStatus = "Ophalen gegevens mislukt.....";
}
}
}
xmlhttp.send();
}
function getCurrentUsage() {
if (debugOutput) console.log("********* ToonBot getCurrentUsage");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/happ_pwrusage?action=GetCurrentUsage", true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot getCurrentUsage readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot getCurrentUsage response " + xmlhttp.responseText );
currentUsageData = JSON.parse(xmlhttp.responseText);
if (currentUsageData['result'] === "ok" ) {
if (debugOutput) console.log("********* ToonBot getCurrentUsage currentUsageData data found");
getTodayGasUsage();
} else {
if (debugOutput) console.log("********* ToonBot getCurrentUsage currentUsageData data found but status not ok");
}
} else {
if (debugOutput) console.log("********* ToonBot getCurrentUsage fout opgetreden.");
tileStatus = "Ophalen gegevens mislukt.....";
}
}
}
xmlhttp.send();
}
function getTodayGasUsage() {
if (debugOutput) console.log("********* ToonBot getTodayGasUsage");
var xmlhttp = new XMLHttpRequest();
var d = new Date();
d.setHours(-1,0,0,0)
var today = d.valueOf() / 1000;
if (debugOutput) console.log("********* ToonBot getTodayGasUsage today " + today );
xmlhttp.open("GET", "http://localhost/hcb_rrd?action=getRrdData&loggerName=gas_quantity&rra=5yrhours&readableTime=0&nullForNaN=1&from=" + today , true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot getTodayGasUsage readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot getTodayGasUsage response " + xmlhttp.responseText );
todayGasUsageData = JSON.parse(xmlhttp.responseText);
if (debugOutput) console.log("********* ToonBot getTodayGasUsage first element" + Object.keys(todayGasUsageData).sort()[0]);
if (debugOutput) console.log("********* ToonBot getTodayGasUsage last element" + Object.keys(todayGasUsageData).sort().reverse()[0]);
if (debugOutput) console.log("********* ToonBot getTodayGasUsage aantal elementen " + Object.keys(todayGasUsageData).length);
if (Object.keys(todayGasUsageData).length > 1 ) {
if (debugOutput) console.log("********* ToonBot getTodayGasUsage todayGasUsageData data found");
} else {
if (debugOutput) console.log("********* ToonBot getTodayGasUsage todayGasUsageData data found but status not ok");
}
} else {
if (debugOutput) console.log("********* ToonBot getTodayGasUsage fout opgetreden.");
// tileStatus = "Ophalen gegevens mislukt.....";
}
getTodayElectLTUsage();
}
}
xmlhttp.send();
}
function getTodayElectLTUsage() {
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage");
var xmlhttp = new XMLHttpRequest();
var d = new Date();
d.setHours(-1,0,0,0)
var today = d.valueOf() / 1000;
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage today " + today );
xmlhttp.open("GET", "http://localhost/hcb_rrd?action=getRrdData&loggerName=elec_quantity_lt&rra=5yrhours&readableTime=0&nullForNaN=1&from=" + today , true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage response " + xmlhttp.responseText );
todayElectLTUsageData = JSON.parse(xmlhttp.responseText);
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage first element" + Object.keys(todayElectLTUsageData).sort()[0]);
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage last element" + Object.keys(todayElectLTUsageData).sort().reverse()[0]);
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage aantal elementen " + Object.keys(todayElectLTUsageData).length);
if (Object.keys(todayElectLTUsageData).length > 1 ) {
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage todayElectLTUsageData data found");
} else {
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage todayElectLTUsageData data found but status not ok");
}
} else {
if (debugOutput) console.log("********* ToonBot getTodayElectLTUsage fout opgetreden.");
// tileStatus = "Ophalen gegevens mislukt.....";
}
getTodayElectNTUsage();
}
}
xmlhttp.send();
}
function getTodayElectNTUsage() {
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage");
var xmlhttp = new XMLHttpRequest();
var d = new Date();
d.setHours(-1,0,0,0)
var today = d.valueOf() /1000;
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage today " + today );
xmlhttp.open("GET", "http://localhost/hcb_rrd?action=getRrdData&loggerName=elec_quantity_nt&rra=5yrhours&readableTime=0&nullForNaN=1&from=" + today , true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage response " + xmlhttp.responseText );
todayElectNTUsageData = JSON.parse(xmlhttp.responseText);
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage first element" + Object.keys(todayElectNTUsageData).sort()[0]);
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage last element" + Object.keys(todayElectNTUsageData).sort().reverse()[0]);
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage aantal elementen " + Object.keys(todayElectNTUsageData).length);
if (Object.keys(todayElectNTUsageData).length > 1 ) {
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage todayElectNTUsageData data found");
} else {
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage todayElectNTUsageData data found but status not ok");
}
} else {
if (debugOutput) console.log("********* ToonBot getTodayElectNTUsage fout opgetreden.");
// tileStatus = "Ophalen gegevens mislukt.....";
}
processEnergyUsage();
}
}
xmlhttp.send();
}
function getStateText(state) {
var activeState;
switch(state) {
case "0":
activeState = "Comfort";
break;
case "1":
activeState = "Thuis";
break;
case "2":
activeState = "Slapen";
break;
case "3":
activeState = "Weg";
break;
case "-1":
activeState = "Handmatig";
break;
default:
activeState = "onbekend";
}
return activeState;
}
function getProgramText(program) {
var programState;
switch(program) {
case "0":
programState = "Uit";
break;
case "1":
programState = "Aan";
break;
case "2":
programState = "Tijdelijk";
break;
default:
programState = "onbekend";
}
return programState;
}
function processEnergyUsage() {
var message = "";
var gasUsageToday;
var electTodayUsage;
var powerUsage = currentUsageData['powerUsage']['value'];
var powerProduction = currentUsageData['powerProduction']['value'];
var gasUsage = currentUsageData['gasUsage']['value'];
if (!powerUsage) {
powerUsage = 'N/A';
}
if (powerProduction === null) {
powerProduction = 'N/A';
}
if (gasUsage === null) {
gasUsage = 'N/A';
}
if (debugOutput) console.log("********* ToonBot processEnergyUsage powerUsage:" + powerUsage );
if (debugOutput) console.log("********* ToonBot processEnergyUsage powerProduction:" + powerProduction );
if (debugOutput) console.log("********* ToonBot processEnergyUsage gasUsage:" + gasUsage );
if (todayGasUsageData[Object.keys(todayGasUsageData).sort()[0]] === null) {
gasUsageToday = 'N/A';
} else {
var gasBeginUsageToday = todayGasUsageData[Object.keys(todayGasUsageData).sort()[0]] / 1000;
var gasEndUsageToday = todayGasUsageData[Object.keys(todayGasUsageData).sort().reverse()[0]] / 1000;
gasUsageToday = Math.round((gasEndUsageToday - gasBeginUsageToday)*100)/100;
}
if (debugOutput) console.log("********* ToonBot processEnergyUsage gasUsageToday " + gasUsageToday);
if (todayElectLTUsageData[Object.keys(todayElectLTUsageData).sort()[0]] === null) {
electTodayUsage = 'N/A';
} else {
var electLTBeginUsageToday = todayElectLTUsageData[Object.keys(todayElectLTUsageData).sort()[0]] / 1000;
var electLTEndUsageToday = todayElectLTUsageData[Object.keys(todayElectLTUsageData).sort().reverse()[0]] / 1000;
var electLTUsageToday = electLTEndUsageToday - electLTBeginUsageToday;
if (debugOutput) console.log("********* ToonBot processEnergyUsage electLTUsageToday " + electLTUsageToday);
}
if (todayElectNTUsageData[Object.keys(todayElectNTUsageData).sort()[0]] === null) {
electTodayUsage = 'N/A';
} else {
var electNTBeginUsageToday = todayElectNTUsageData[Object.keys(todayElectNTUsageData).sort()[0]] / 1000;
var electNTEndUsageToday = todayElectNTUsageData[Object.keys(todayElectNTUsageData).sort().reverse()[0]] / 1000;
var electNTUsageToday = electNTEndUsageToday - electNTBeginUsageToday;
if (debugOutput) console.log("********* ToonBot processEnergyUsage electNTUsageToday " + electNTUsageToday);
}
if (electTodayUsage !== 'N/A') {
electTodayUsage = Math.round((electLTUsageToday + electNTUsageToday)*1000) /1000;
}
message = "<b>Status energie verbruik:</b>\n" +
" Stroom huidig verbruik: <b>" + powerUsage + "</b> Watt\n" +
" Stroom huidig teruglevering: <b>" + powerProduction + "</b> Watt\n" +
" Stroom verbruik vandaag: <b>" + electTodayUsage + "</b> kWh\n" +
// " Gas huidig verbruik: <b>" + gasUsage + "</b> liters\n" +
" Gas verbruik vandaag: <b>" + gasUsageToday + "</b> m3\n";
sendTelegramMessage(chatId, message);
}
function processThermostatInfo() {
var message = "";
var programState;
var activeState;
var nextProgram;
var nextState;
var nextTime;
var currentTemp = Math.round(thermostatInfoData['currentTemp'] / 10) /10 ;
var currentSetpoint = Math.round(thermostatInfoData['currentSetpoint'] /10) /10;
programState = getProgramText(thermostatInfoData['programState']);
activeState = getStateText(thermostatInfoData['activeState']);
nextProgram = getProgramText(thermostatInfoData['nextProgram']);
nextState = getStateText(thermostatInfoData['nextState']);
nextTime = new Date (thermostatInfoData['nextTime'] * 1000);
if (debugOutput) console.log("********* ToonBot processThermostatInfo currentTemp:" + currentTemp );
if (debugOutput) console.log("********* ToonBot processThermostatInfo currentSetpoint:" + currentSetpoint );
if (debugOutput) console.log("********* ToonBot processThermostatInfo programState:" + programState );
if (debugOutput) console.log("********* ToonBot processThermostatInfo activeState:" + activeState );
if (debugOutput) console.log("********* ToonBot processThermostatInfo nextProgram:" + nextProgram );
if (debugOutput) console.log("********* ToonBot processThermostatInfo nextState:" + nextState );
if (debugOutput) console.log("********* ToonBot processThermostatInfo nextTime:" + nextTime );
message = "<b>Status Toon:</b>\n" +
" Temperatuur: <b>" + currentTemp + "</b> graden\n" +
" Thermostaat: <b>" + currentSetpoint + "</b> graden\n" +
" Programma: <b>" + activeState + "</b>\n" +
" Auto programma: <b>" + programState + "</b>\n";
if (thermostatInfoData['nextTime'] !== "0") {
message = message + " Om " + nextTime.getHours() + ":" + nextTime.getMinutes() + " op " + nextState + " en auto programma " + nextProgram;
}
sendTelegramMessage(chatId, message);
}
function setProgram(program) {
var responseData;
var state;
if (debugOutput) console.log("********* ToonBot setProgram: " + program);
switch(program.toUpperCase()) {
case "C": // comfort
state = 0;
break;
case "T": // thuis
state = 1;
break;
case "S": // slapen
state = 2;
break;
case "W": // weg
state = 3;
break;
default:
return;
}
if (debugOutput) console.log("********* ToonBot setProgram");
var responseData;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/happ_thermstat?action=changeSchemeState&state=2&temperatureState=" + state, true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot setProgram readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot setProgram response " + xmlhttp.responseText );
responseData = JSON.parse(xmlhttp.responseText);
if (responseData['result'] === "ok" ) {
if (debugOutput) console.log("********* ToonBot setProgram succeeded");
} else {
if (debugOutput) console.log("********* ToonBot setProgram failed");
}
} else {
if (debugOutput) console.log("********* ToonBot setProgram fout opgetreden.");
}
}
}
xmlhttp.send();
}
function setState(state) {
var responseData;
var tmpState;
if (debugOutput) console.log("********* ToonBot setState: " + state);
switch(state.toUpperCase()) {
case "U": // uit
tmpState = "0";
break;
case "A": // aan
tmpState = "1";
break;
default:
return;
}
var xmlhttp = new XMLHttpRequest();
if (debugOutput) console.log("********* ToonBot setState http://localhost/happ_thermstat?action=changeSchemeState&state=" + tmpState);
xmlhttp.open("GET", "http://localhost/happ_thermstat?action=changeSchemeState&state=" + tmpState, true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot setState readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot setState response " + xmlhttp.responseText );
responseData = JSON.parse(xmlhttp.responseText);
if (responseData['result'] === "ok" ) {
if (debugOutput) console.log("********* ToonBot setState succeeded");
} else {
if (debugOutput) console.log("********* ToonBot setState failed");
}
} else {
if (debugOutput) console.log("********* ToonBot setState fout opgetreden.");
}
}
}
xmlhttp.send();
}
function setTemp(temp) {
var responseData;
var tmpTemp = temp * 100;
if (debugOutput) console.log("********* ToonBot setTemp temp: " + temp);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/happ_thermstat?action=setSetpoint&Setpoint=" + tmpTemp, true);
xmlhttp.onreadystatechange = function() {
if (debugOutput) console.log("********* ToonBot setTemp readyState: " + xmlhttp.readyState + " http status: " + xmlhttp.status);
if (xmlhttp.readyState === XMLHttpRequest.DONE ) {
if (xmlhttp.status === 200) {
if (debugOutput) console.log("********* ToonBot setTemp response " + xmlhttp.responseText );
responseData = JSON.parse(xmlhttp.responseText);
if (responseData['result'] === "ok" ) {
if (debugOutput) console.log("********* ToonBot setTemp succeeded");
} else {
if (debugOutput) console.log("********* ToonBot setTemp failed");
}
} else {
if (debugOutput) console.log("********* ToonBot setTemp fout opgetreden.");
}
}
}
xmlhttp.send();
}
function processCommandInfo() {
getThermostatInfo();
}
function processCommandEnergie() {
getCurrentUsage();
}
function processCommandProgram(subcmd) {
setProgram(subcmd);
getThermostatInfo();
}
function processCommandAutoprogram(subcmd) {
setState(subcmd);
getThermostatInfo();
}
function processCommandChangetemp(temp) {
setTemp(temp);
getThermostatInfo();
}
// rond getal af naar .0 of .5
function roundToHalf(value) {
var converted = parseFloat(value); // Make sure we have a number
var decimal = (converted - parseInt(converted, 10));
decimal = Math.round(decimal * 10);
if (decimal == 5) { return (parseInt(converted, 10)+0.5); }
if ( (decimal < 3) || (decimal > 7) ) {
return Math.round(converted);
} else {
return (parseInt(converted, 10)+0.5);
}
}
// Is chat id allowed?
function chatAllowed(chat_id) {
if (debugOutput) console.log("********* ToonBot chatAllowed");
if (!enableSecurity) {
return true;
}
return inUsersChatIdsList(chat_id);
}
function processCommand(text,update_id, chat_id) {
var subcmd;
var cmd;
if (debugOutput) console.log("********* ToonBot processCommand command: " + text );
if (!chatAllowed(chat_id)) {
if (debugOutput) console.log("********* ToonBot processCommand chat not allowed");
setStatus(update_id, "Denied")
return;
}
var command = text.replace(/\s/g,'').split("_",2);
if (debugOutput) console.log("********* ToonBot processCommand command:" + command + " len: " + command.length);
cmd = command[0];
if (command.length === 2) {
subcmd = command[1];
} else {
subcmd = "";
}
if (debugOutput) console.log("********* ToonBot processCommand cmd: " + cmd + " subcmd: " + subcmd );
tileLastcmd = text;
switch(cmd.toUpperCase()) {