-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJ_ReactorSensor_UI7.js
9130 lines (8495 loc) · 349 KB
/
J_ReactorSensor_UI7.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
//# sourceURL=J_ReactorSensor_UI7.js
/**
* J_ReactorSensor_UI7.js
* Configuration interface for ReactorSensor
*
* Copyright 2018-2022 Patrick H. Rigney, All Rights Reserved.
* This file is part of Reactor. Use subject to license; please see
* license details at https://www.toggledbits.com/static/reactor/docs/Installation#license-and-use-restrictions
*
*/
/* globals api,jQuery,ace,MultiBox,ALTUI_revision,Promise,escape,unescape */
/* jshint browser: true, devel: true, multistr: true, laxcomma: true, undef: true, unused: false */
//"use strict"; // fails on UI7, works fine with ALTUI
var ReactorSensor = (function(api, $) {
/* unique identifier for this plugin... */
var uuid = '21b5725a-6dcd-11e8-8342-74d4351650de';
var pluginVersion = "3.11 (22314)";
var _UIVERSION = 22314; /* must coincide with Lua core */
var _CDATAVERSION = 20045; /* must coincide with Lua core */
var DEVINFO_MINSERIAL = 482;
var _DOCURL = "https://www.toggledbits.com/static/reactor/docs/3.9/";
var _FORUMURL = "https://community.getvera.com/c/plugins-and-plugin-development/reactor/178";
var _MIN_ALTUI_VERSION = 2536;
var _MAX_ALTUI_VERSION = 2553;
var myModule = {};
var serviceId = "urn:toggledbits-com:serviceId:ReactorSensor";
var deviceType = "urn:schemas-toggledbits-com:device:ReactorSensor:1";
var moduleReady = false;
var needsRestart = false;
var iData = [];
var roomsByName = false;
var actions = {};
var deviceActionData = {};
var deviceInfo = {};
var userIx = {};
var userNameIx = {};
var configModified = false;
var inStatusPanel = false;
var spyDevice = false;
var lastx = 0;
var isOpenLuup = false;
var isALTUI = false;
var devVeraAlerts = false;
var devVeraTelegram = false;
var dateFormat = "%F"; /* ISO8601 defaults */
var timeFormat = "%T";
var unsafeLua = true;
var onBeforeCpanelClose; /* forward declaration */
var condTypeName = {
"comment": "Comment",
"service": "Device State",
"housemode": "House Mode",
"weekday": "Weekday",
"sun": "Sunrise/Sunset",
"trange": "Date/Time",
"interval": "Interval",
"ishome": "Geofence",
"reload": "Luup Reloaded",
"grpstate": "Group State",
"var": "Expression Value",
"group": "Group"
};
/* Note: default true for the following: hold, pulse, latch */
var condOptions = {
"group": { sequence: true, duration: true, repeat: true },
"service": { sequence: true, duration: true, repeat: true },
"housemode": { sequence: true, duration: true, repeat: true },
"weekday": { },
"sun": { sequence: true },
"trange": { },
"interval": { pulse: false, latch: false },
"ishome": { sequence: true, duration: true },
"reload": { },
"grpstate": { sequence: true, duration: true, repeat: true },
"var": { sequence: true, duration: true, repeat: true }
};
var weekDayName = [ '?', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];
var monthName = [ '?', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ];
var opName = { "bet": "between", "nob": "not between", "after": "after", "before": "before" };
var houseModeName = [ '?', 'Home', 'Away', 'Night', 'Vacation' ];
var inttypes = {
"ui1": { min: 0, max: 255 }, "i1": { min: -128, max: 127 },
"ui2": { min: 0, max: 65535 }, "i2": { min: -32768, max: 32767 },
"ui4": { min: 0, max: 4294967295 }, "i4": { min: -2147483648, max: 2147483647 },
"int": { min: -2147483648, max: 2147483647 }
};
var serviceOps = [
{ op: '=', desc: 'equals', args: 1, optional: 1 },
{ op: '<>', desc: 'not equals', args: 1, optional: 1 },
{ op: '<', desc: '<', args: 1, numeric: 1, },
{ op: '<=', desc: '<=', args: 1, numeric: 1, },
{ op: '>', desc: '>', args: 1, numeric: 1, },
{ op: '>=', desc: '>=', args: 1, numeric: 1, },
{ op: 'bet', desc: 'between', args: 2, numeric: 1, format: "%1 and %2" },
{ op: 'nob', desc: 'not between', args: 2, numeric: 1, format: "%1 and %2" },
{ op: 'starts', desc: 'starts with', args: 1, },
{ op: 'notstarts', desc: 'does not start with', args: 1, },
{ op: 'ends', desc: 'ends with', args: 1, },
{ op: 'notends', desc: 'does not end with', args: 1, },
{ op: 'contains', desc: 'contains', args: 1, },
{ op: 'notcontains', desc: 'does not contain', args: 1, },
{ op: 'in', desc: 'in', args: 1 },
{ op: 'notin', desc: 'not in', args: 1 },
{ op: 'istrue', desc: 'is TRUE', args: 0, nocase: false },
{ op: 'isfalse', desc: 'is FALSE', args: 0, nocase: false },
{ op: 'isnull', desc: 'is NULL', args: 0, nocase: false },
{ op: 'change', desc: 'changes', args: 2, format: "from %1 to %2", optional: 2, blank: "(any)" },
{ op: 'update', desc: 'updates', args: 0, nocase: false }
];
var varRefPattern = /^\{([^}]+)\}\s*$/;
var notifyMethods = [
{ id: "", name: "Vera-native" }
, { id: "SM", name: "SMTP Mail", users: false, extra: [
{ id: "recipient", label: "Recipient(s):", placeholder: "blank=default recipient; comma-separate multiple", optional: true },
{ id: "subject", label: "Subject:", placeholder: "blank=this ReactorSensor's name", optional: true }
], config: { name: "SMTPServer" } }
, { id: "PR", name: "Prowl", users: false, requiresUnsafeLua: true, extra: [
{ id: "priority", label: "Priority:", type: "select", default: "0", values: [ "-2=Very low", "-1=Low", "0=Normal", "1=High", "2=Emergency" ] }
], config: { name: "ProwlAPIKey" } }
, { id: "PO", name: "Pushover", users: false, requiresUnsafeLua: true, extra: [
{ id: "title", label: "Message Title", placeholder: "blank=this ReactorSensor's name", default: "", optional: true },
{ id: "podevice", label: "Device:", placeholder: "optional", default: "", optional: true },
{ id: "priority", label: "Priority:", type: "select", default: "0", values: [ "-2=Very low", "-1=Low", "0=Normal", "1=High" ] }, /* 2=Emergency doesn't seem to work, no alert is received 2020-09-23 */
{ id: "sound", label: "Sound:", Xtype: "select", default: "", optional: true, placeholder: "blank=device default; select from list or enter your own value",
datalist: [
"=(device default)", "none=(none/silent)", "vibrate=(vibrate only)", "pushover=Pushover",
"bike=Bike", "bugle=Bugle", "cashregister=Cash Register", "classical=Classical", "cosmic=Cosmic", "falling=Falling",
"gamelan=Gamelan", "incoming=Incoming", "intermission=Intermission", "magic=Magic", "mechanical=Mechanical",
"pianobar=Piano Bar", "siren=Siren", "spacealarm=Space Alarm", "tugboat=Tug Boat", "alien=Alien Alarm (long)",
"climb=Climb (long)", "persistent=Persistent (long)", "echo=Pushover Echo (long)", "updown=Up Down (long)"
]
},
{ id: "token", label: "Pushover Token:", placeholder: "blank=from Reactor config", default:"", optional: true }
], config: { name: "PushoverUser" } }
, { id: "SD", name: "Syslog", users: false, extra: [
{ id: "hostip", label: "Syslog Server IP:", placeholder: "Host IP4 Address", validpattern: "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$" },
{ id: "facility", label: "Facility:", type: "select", default: "23", values: [ "0=kern","1=user","2=mail","3-daemon","4=auth","5=syslog","6=lp","7=news","8=uucp","9=clock","10=security","11=FTP","12=NTP","13=audit","14=alert","16=local0","17=local1","18=local2","19=local3","20=local4","21=local5","22=local6","23=local7" ] },
{ id: "severity", label: "Severity:", type: "select", default: "5", values: [ "0=emerg","1=alert","2=crit","3=err","4=warn","5=notice","6=info","7=debug" ] }
] }
, { id: "UU", name: "User URL", users: false, requiresUnsafeLua: true, extra: [
{ id: "url", label: "URL:", type: "textarea", placeholder: "URL", validpattern: "^https?://", default: "http://localhost/alert?message={message}", fullwidth: true }
] }
, { id: "VA", name: "VeraAlerts" }
, { id: "VT", name: "VeraTelegram", users: false, extra: [
{ id: "imageurl", label: "Image URL:", type: "textarea", placeholder: "URL", validpattern: "^https?://", default: "", optional: true, fullwidth: true },
{ id: "videourl", label: "Video URL:", type: "textarea", placeholder: "URL", validpattern: "^https?://", default: "", optional: true, fullwidth: true },
{ id: "chatid", label: "Chat ID:", default: "", optional: true },
{ id: "disablenotification", label: "Disable Notification:", type: "select", values: [ "False=No", "True=Yes" ] }
] }
];
var msgUnsavedChanges = "You have unsaved changes! Press OK to save them, or Cancel to discard them.";
var msgGroupIdChange = "Click to change group name";
var msgOptionsShow = "Show condition options";
var msgOptionsHide = "Hide condition options";
var msgRemoteAlert = "You appear to be using remote access for this session. Editing of ReactorSensor configurations via remote access is possible, but not recommended due to the latency and inconsistency of cloud connections and infrastructure. You may experience issues, particularly when saving large configurations. Using local access exclusively is strongly recommended. It is also a good idea to back up your ReactorSensors (using the Backup/Restore tab in the Reactor master device) prior to editing via remote access.";
var NULLCONFIG = { conditions: {} };
/* Insert the header items */
/* Checkboxes, see https://codepen.io/VoodooSV/pen/XoZJme */
function header() {
if ( 0 !== $( 'style#reactor-core-styles' ).length ) return;
/* Load material design icons */
var $head = $( 'head' );
$head.append('<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">');
$head.append( '\
<style id="reactor-core-styles">\
div.reactortab { background-color: white; color: black; } \
div.re-alertbox { border: 3px solid #ff3; border-radius: 8px; padding: 8px 8px; box-shadow: #999 2px 2px; background-color: #fff; color: #000; } \
div.reactortab input.narrow { max-width: 6em; } \
div.reactortab .re-fullwidth { width: 100%; } \
div.reactortab input.tiny { max-width: 4em; text-align: center; } \
div.reactortab label { font-weight: normal; padding: 0 2px; } \
div.reactortab label.re-secondaryinput { margin-left: 0.5em; margin-right: 0.5em; } \
div.reactortab .tbinline { display: inline-block; } \
div.reactortab .tbhidden { display: none !important; } /* workaround for show/hide bug in jquery restoring wrong display mode */ \
div.reactortab .checkbox { padding-left: 20px; } \
div.reactortab .checkbox label { display: inline-block; vertical-align: middle; position: relative; padding-left: 8px; } \
div.reactortab .checkbox label::before { content: ""; display: inline-block; position: absolute; width: 20px; height: 20px; left: 0; margin-left: -20px; border: 1px solid #ccc; border-radius: 3px; background-color: #fff; -webkit-transition: border 0.15s ease-in-out, color 0.15s ease-in-out; -o-transition: border 0.15s ease-in-out, color 0.15s ease-in-out; transition: border 0.15s ease-in-out, color 0.15s ease-in-out; } \
div.reactortab .checkbox label::after { display: inline-block; position: absolute; width: 20px; height: 20px; left: 1px; top: -2px; margin-left: -20px; padding-left: 0; padding-top: 0; font-size: 18px; color: #333; } \
div.reactortab .checkbox input[type="checkbox"],div.reactortab .checkbox input[type="radio"] { opacity: 0; z-index: 1; } \
div.reactortab .checkbox input[type="checkbox"]:focus + label::before { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } \
div.reactortab .checkbox input[type="checkbox"]:checked + label::after { font-family: "Material Icons"; content: "\\e5ca"; } \
div.reactortab .checkbox input[type="checkbox"]:disabled + label { opacity: 0.65; } \
div.reactortab .checkbox input[type="checkbox"]:disabled + label::before { background-color: #eee; cursor: not-allowed; } \
div.reactortab .checkbox.checkbox-inline { margin-top: 0; display: inline-block; } \
div.reactortab .tb-about { margin-top: 24px; } \
div.reactortab .tberror { border: 1px solid red; } \
div.reactortab .tbwarn { border: 1px solid yellow; background-color: yellow; } \
div.reactortab .tbdocslink { margin-left: 4px; } \
div.reactortab .tbdocslink i.material-icons { font-size: 18px; position: relative; top: 4px; } \
div.reactortab button.md-btn:disabled { color: #ccc; cursor: not-allowed; } \
div.reactortab button.md-btn[disabled] { color: #ccc; cursor: not-allowed; } \
div.reactortab button.md-btn { line-height: 1em; cursor: pointer; color: #333; background-color: #fff; padding: 1px 0px 0px 0px; border: 1px solid transparent; border-radius: 4px; box-shadow: #ccc 2px 2px; background-image: linear-gradient( to bottom, #fff, #e6e6e6 ); background-repeat: repeat-x; } \
div.reactortab button.md-btn i { font-size: 16pt; line-height: 1em; } \
div.reactortab optgroup { color: #333; font-weight: bold; } \
div.reactortab .re-dropdown { border: 1px solid black; padding: 4px 4px; background-color: #fff; color: #000;} \
div.reactortab .dropdown-item { display: block; width: 100%; padding: 2px 12px; clear: both; font-weight: normal; color: #000; text-align: inherit; white-space: nowrap; background-color: transparent; border: 0; } \
div.reactortab .dropdown-item:hover { color: #fff; background-color: #66aaff; text-decoration: none; } \
div.reactortab .dropdown-divider { border-top: 1px solid #999; margin: 0.5em 0; } \
div.reactortab .dropdown-header { display: block; width: 100%; padding: 2px 12px; clear: both; font-weight: bold; color: #000; text-align: inherit; background-color: transparent; border: 0; } \
div.reactortab .dropdown-header:hover { text-decoration: none; } \
div#tbcopyright { display: block; margin: 12px 0px; } \
div#tbbegging { display: block; color: #ff6600; margin-top: 12px; } \
div.reactortab .vanotice { font-size: 0.9em; line-height: 1.5em; color: #666; margin-top: 4px; } \
div.reactortab div.re-alertblock { margin: 4px 4px; padding: 8px 8px; border: 2px solid red; color: red; border-radius: 8px; font-size: 0.9em; } \
</style>');
if ( isALTUI ) {
$head.append( '<style id="reactor-platform-styles">/* ALTUI */</style>' );
} else {
/* Vera */
$head.append( '<style id="reactor-platform-styles">/* Vera */\
div.reactortab .form-inline { display: -ms-flexbox; display: flex; -ms-flex-flow: row wrap; flex-flow: row wrap; align-items: center; } \
</style>' );
}
}
/* Return footer */
function footer() {
var html = '';
html += '<div class="clearfix">';
html += '<div id="tbbegging"><em>Find Reactor useful?</em> Please consider a small one-time donation to support this and my other plugins on <a href="https://www.toggledbits.com/donate" target="_blank">my web site</a>. I am grateful for any support you choose to give!</div>';
html += '<div id="tbcopyright">Reactor ver ' + pluginVersion + ' © 2018,2019,2020 <a href="https://www.toggledbits.com/" target="_blank">Patrick H. Rigney</a>,' +
' All Rights Reserved. Please check out the <a href="' + _DOCURL + '" target="_blank">online documentation</a>' +
' and <a href="' + _FORUMURL + '" target="_blank">community forums</a> for support.</div>';
try {
html += '<div id="browserident">' + navigator.userAgent + '</div>';
} catch( e ) {}
return html;
}
function checkRemoteAccess() {
// return !isOpenLuup && null === api.getDataRequestURL().match( /^https?:\/\/(\d+)\.(\d+)\.(\d+)\.(\d+)/ );
return false; /* LATER 3.5 2019-12-02... not yet, let's see how other var changes work out */
}
/* Create an ID that's functionally unique for our purposes. */
function getUID( prefix ) {
/* Not good, but good enough. */
var newx = Date.now() - 1529298000000;
if ( newx <= lastx ) newx = lastx + 1;
lastx = newx;
return ( prefix === undefined ? "" : prefix ) + newx.toString(36);
}
function isEmpty( s ) {
return undefined === s || null === s || "" === s ||
( "string" === typeof( s ) && null !== s.match( /^\s*$/ ) );
}
function quot( s ) {
return JSON.stringify( s );
}
/* Remove special characters that disrupt JSON processing on Vera (dkjson 1.2 in particular */
/* Ref http://dkolf.de/src/dkjson-lua.fsl/home (see 1.2 comments) */
/* Ref https://docs.microsoft.com/en-us/openspecs/ie_standards/ms-es3/def92c0a-e69f-4e5e-8c5e-9f6c9e58e28b */
function purify( s ) {
return "string" !== typeof(s) ? s :
s.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, "");
/* or... s.replace( /[\u007F-\uFFFF]/g, function(ch) { return "\\u" + ("0000"+ch.charCodeAt(0).toString(16)).substr(-4); } ) */
}
function hasAnyProperty( obj ) {
// assert( "object" === typeof( obj );
if ( "object" === typeof( obj ) ) {
for ( var p in obj ) {
if ( obj.hasOwnProperty( p ) ) return true;
}
}
return false;
}
/* Find a value in an array using a function to match; returns value, not index. */
function arrayFindValue( arr, func, start ) {
var l = arr.length;
for ( var k=(start || 0); k<l; ++k ) {
if ( func( arr[k] ) ) return arr[k];
}
return null;
}
function idSelector( id ) {
return String( id ).replace( /([^A-Z0-9_-])/ig, "\\$1" );
}
/* Select current value in menu; if not present, select first item. */
function menuSelectDefaultFirst( $mm, val ) {
var $opt = $( 'option[value=' + quot( coalesce( val, "" ) ) + ']', $mm );
if ( 0 === $opt.length ) {
$opt = $( 'option:first', $mm );
}
val = $opt.val(); /* actual value now */
$mm.val( val );
return val;
}
/** Select current value in menu; insert if not present. The menu txt is
* optional.
*/
function menuSelectDefaultInsert( $mm, val, txt ) {
var $opt = $( 'option[value=' + quot( val ) + ']', $mm );
if ( 0 === $opt.length ) {
$opt = $( '<option></option>' ).val( val ).text( txt || ( val + '? (missing)' ) );
$mm.addClass( "tberror" ).append( $opt );
}
val = $opt.val(); /* actual value now */
$mm.val( val );
return val;
}
/** getWiki - Get (as jQuery) a link to Wiki for topic */
function getWiki( where ) {
var $v = $( '<a></a>', {
"class": "tbdocslink",
"alt": "Link to documentation for topic",
"title": "Link to documentation for topic",
"target": "_blank",
"href": _DOCURL + String(where || "")
} );
$v.append( '<i class="material-icons">help_outline</i>' );
return $v;
}
/* Return value or default if undefined */
function coalesce( v, d ) {
return ( null === v || undefined === v ) ? d : v;
}
/* Evaluate input string as integer, strict (no non-numeric chars allowed other than leading/trailing whitespace, empty string fails). */
function getInteger( s ) {
s = String(s).trim().replace( /^\+/, '' ); /* leading + is fine, ignore */
if ( s.match( /^-?[0-9]+$/ ) ) {
return parseInt( s );
}
return NaN;
}
/* Like getInteger(), but returns dflt if no value provided (blank/all whitespace) */
function getOptionalInteger( s, dflt ) {
if ( /^\s*$/.test( String(s) ) ) {
return dflt;
}
return getInteger( s );
}
function getDeviceFriendlyName( dev, devobj ) {
if ( -1 === dev ) return '(self)';
devobj = devobj || api.getDeviceObject( dev );
if ( ! devobj ) {
console.log( "getDeviceFriendlyName() dev=(" + typeof(dev) + ")" + String(dev) + ", devobj=(" + typeof(devobj) + ")" + String(devobj) + ", returning false" );
return false;
}
return String(devobj.name) + " (#" + String(devobj.id) + ")";
}
/* Get parent state */
function getParentState( varName, myid ) {
var me = api.getDeviceObject( myid || api.getCpanelDeviceId() );
return api.getDeviceState( me.id_parent || me.id, "urn:toggledbits-com:serviceId:Reactor", varName );
}
/* Set parent state */
function setParentState( varName, val, myid ) {
var me = api.getDeviceObject( myid || api.getCpanelDeviceId() );
return api.setDeviceStatePersistent( me.id_parent || me.id, "urn:toggledbits-com:serviceId:Reactor", varName, val );
}
function checkUpdate() {
if ( isOpenLuup ) {
return Promise.resolve( false );
}
return new Promise( function( resolve, reject ) {
$.ajax({
url: api.getDataRequestURL(),
data: {
id: "lr_Reactor",
action: "updateplugin",
r: Math.random()
},
dataType: "json",
timeout: 15000,
cache: false
}).fail( function( /* jqXHR, textStatus, errorThrown */ ) {
reject();
}).done( function( data ) {
if ( !data.status ) {
reject( data.message );
return;
}
var newest = false;
for ( var j=0; j<data.data.length; ++j ) {
var rel = data.data[j];
if ( "master" === rel.target_commitish || "hotfix" === rel.target_commitish ) {
var pubtime = Date.parse( rel.published_at );
if ( pubtime >= 1620345600000 ) { // 2021-05-07T00:00:00Z
rel.published_at = pubtime;
if ( !newest || pubtime > newest.published_at ) {
newest = rel;
}
}
}
}
/* Now see if newest is not current */
if ( newest ) {
var st = getParentState( "grelease", false ) || "";
var r = st.split( /\|/ );
if ( r.length > 0 && r[0] == String(newest.id) ) {
/* Installed version is current version */
newest = false;
}
}
resolve( newest );
});
});
}
/* Get data for this instance */
function getInstanceData( myid ) {
myid = myid || api.getCpanelDeviceId();
iData[ myid ] = iData[ myid ] || {};
return iData[ myid ];
}
/* Generate an inline checkbox. */
function getCheckbox( id, value, label, classes, help ) {
var $div = $( '<div class="checkbox checkbox-inline"></div>' );
if ( isALTUI ) {
$div.removeClass().addClass( 'form-check' );
$('<input>').attr( { type: 'checkbox', id: id } )
.val( value )
.addClass( 'form-check-input' )
.addClass( classes || "" )
.appendTo( $div );
$('<label></label>').attr( 'for', id )
.addClass( 'form-check-label' )
.html( label )
.appendTo( $div );
} else {
$( '<input type="checkbox">' ).attr( 'id', id ).val( value )
.addClass( classes || "" )
.appendTo( $div );
$( '<label></label>' ).attr( 'for', id ).html( label )
.appendTo( $div );
}
if ( help ) {
getWiki( help ).appendTo( $div );
}
return $div;
}
/* Generate an inline radio button */
function getRadio( name, ix, value, label, classes ) {
var $div;
if ( isALTUI ) {
$div = $( '<div></div>' ).addClass( 'form-check' );
$('<input>').attr( { type: 'radio', id: name + ix, name: name } )
.val( value )
.addClass( 'form-check-input' )
.addClass( classes || "" )
.appendTo( $div );
$('<label></label>').attr( 'for', name + ix )
.addClass( 'form-check-label' )
.html( label )
.appendTo( $div );
} else {
$div = $( '<label class="radio"></label>' )
.html( label );
$( '<input type="radio">' )
.attr( { id: name+ix, name: name } )
.val( value )
.addClass( classes || "" )
.prependTo( $div );
}
return $div;
}
/**
* ALTUI: Inconsistencies between versions of UI7, and intra- and inter-ALTUI,
* have to be resolved with some logic.
*/
function hideModal() {
if ( api.hideMessagePopup ) {
api.hideMessagePopup();
} else {
/* Sigh. Do both on ALTUI, in case amg0 fixes his dialogs some day. */
if ( isALTUI ) {
$( 'div#showMessagePopup' ).modal( 'hide' );
}
$( 'div#myModal' ).modal( 'hide' );
}
}
/**
* ALTUI doesn't implement on_cpanel_close event. Use tab behavior.
* Pass any element on the current tab.
*/
function captureControlPanelClose( $el ) {
if ( isALTUI ) {
/** On ALTUI, we break plugin encapsulation by necessity and use
* its tab handler to help us.
*/
var paneId = $el.closest( '.tab-pane' ).attr( 'id' );
$( 'a[href="#' + paneId + '"]' ).off( 'hide.bs.tab.reactor' )
.on( 'hide.bs.tab.reactor', function() {
console.log("captureControlPanelClose() ALTUI module tab hide handler");
onBeforeCpanelClose();
});
$( 'a[href="#altui-toggle-control-panel"]' ).off( 'hide.bs.tab.reactor' )
.on( 'hide.bs.tab.reactor', function() {
console.log("ALTUI control panel hide handler");
onBeforeCpanelClose();
});
} else {
api.registerEventHandler('on_ui_cpanel_before_close', ReactorSensor, 'onBeforeCpanelClose');
}
}
/* Load configuration data. As of 3.5, we do not do any updates here. */
function loadConfigData( myid ) {
var me = api.getDeviceObject( myid );
if ( ! ( me && deviceType === me.device_type ) ) {
throw "Device " + String(myid) + " not found or incorrect type";
}
// PHR??? Dynamic false needs more testing. Save/update of local/lustatus should be sufficient
/* Empty configs are not allowed, but happen when the Vera UI gets wildly out of sync with Vera,
which has happened increasingly since 7.29. */
var s = api.getDeviceState( myid, serviceId, "cdata" /* , { dynamic: false } */ ) || "";
if ( isEmpty( s ) ) {
console.log( "ReactorSensor " + myid + ": EMPTY DATA" );
alert( 'Reactor has detected that the Vera UI may be badly out of sync with the Vera itself. To remedy this, please (1) reload Luup or reboot your Vera, and then (2) do a "hard-refresh" of your browser (refresh with cache flush). Do not edit any devices or do anything else until this issue has been remedied.' );
throw "empty configuration";
} else if ( "###" === s ) {
alert( 'Please go back out to the device list and make sure this ReactorSensor is ENABLED before re-entering configuration.' );
throw "reset configuration";
}
var cdata;
try {
cdata = JSON.parse( s );
/* Old Luup's json library doesn't support __jsontype metadata,
so fix up empty objects, which it renders as empty arrays. */
if ( cdata.variables && Array.isArray( cdata.variables ) && cdata.variables.length == 0 ) {
console.log("Fixing cdata.variables from array to object");
cdata.variables = {};
}
if ( cdata.activities && Array.isArray( cdata.activities ) && cdata.activities.length == 0 ) {
console.log("Fixing cdata.activities from array to object");
cdata.activities = {};
}
} catch (e) {
console.log("Unable to parse cdata: " + String(e));
throw e;
}
/* Special version check */
if ( ( cdata.version || 0 ) > _CDATAVERSION ) {
alert("This ReactorSensor configuration is an unsupported format/version " +
String( cdata.version ) + " for this version of Reactor (" +
pluginVersion + " " + _CDATAVERSION + "). If you've downgraded Reactor from a later " +
"version, you need to restore a backup of this ReactorSensor's configuration made " +
"from the earlier version.");
console.log("The configuration for this ReactorSensor is an unsupported format/version (" +
String( cdata.version ) + "). Upgrade Reactor or restore an older config from backup.");
throw "Incompatible configuration format/version";
}
/* Check for upgrade tasks from prior versions */
delete cdata.undefined;
if ( undefined === cdata.variables ) {
/* Fixup v2 */
cdata.variables = {};
}
if ( undefined === cdata.activities ) {
cdata.activities = {};
}
if ( undefined === cdata.conditions.root ) {
var root = { id: "root", name: api.getDeviceObject( myid ).name, type: "group", operator: "and", conditions: [] };
cdata.conditions = { root: root };
}
/* Update device */
cdata.device = myid;
/* Store config on instance data */
var d = getInstanceData( myid );
d.cdata = cdata;
delete d.ixCond; /* Remove until needed/rebuilt */
configModified = false;
return cdata;
}
/* Get configuration; load if needed */
function getConfiguration( myid, force ) {
myid = myid || api.getCpanelDeviceId();
var d = getInstanceData( myid );
if ( force || ! d.cdata ) {
try {
loadConfigData( myid );
console.log("getConfiguration(): loaded config serial " + String(d.cdata.serial) + ", timestamp " + String(d.cdata.timestamp));
} catch ( e ) {
console.log("getConfiguration(): can't load config for "+myid+": "+String(e));
console.log(e);
return false;
}
} else {
console.log("getConfiguration(): returning cached config serial " + String(d.cdata.serial));
}
return d.cdata;
}
/* Get condition index; build if needed (used by Status and Condition tabs) */
function getConditionIndex( myid ) {
var d = getInstanceData( myid );
if ( undefined === d.ixCond ) {
var cf = getConfiguration( myid );
d.ixCond = {};
var makeix = function( grp, level ) {
d.ixCond[grp.id] = grp;
grp.__depth = level; /* assigned to groups only */
for ( var ix=0; ix<(grp.conditions || []).length; ix++ ) {
grp.conditions[ix].__parent = grp;
grp.conditions[ix].__index = ix;
d.ixCond[grp.conditions[ix].id] = grp.conditions[ix];
if ( "group" === ( grp.conditions[ix].type || "group" ) ) {
makeix( grp.conditions[ix], level+1 );
}
}
};
makeix( cf.conditions.root || {}, 0 );
}
return d.ixCond;
}
function getConditionStates( myid ) {
myid = myid || api.getCpanelDeviceId();
var s = api.getDeviceState( myid, serviceId, "cstate" ) || "";
var cstate = {};
if ( ! isEmpty( s ) ) {
try {
cstate = JSON.parse( s );
return cstate;
} catch (e) {
console.log("cstate cannot be parsed: " + String(e));
}
} else {
console.log("cstate unavailable");
}
/* Return empty cstate structure */
return { vars: {} };
}
/* Generic filter for DOtraverse to return groups only */
function isGroup( node ) {
return "group" === ( node.type || "group" );
}
/* Traverse - pre-order */
function DOtraverse( node, op, args, filter ) {
if ( node ) {
if ( ( !filter ) || filter( node ) ) {
op( node, args );
}
if ( "group" === ( node.type || "group" ) ) {
var l = node.conditions ? node.conditions.length : 0;
for ( var ix=0; ix<l; ix++ ) {
DOtraverse( node.conditions[ix], op, args, filter );
}
}
}
}
/* Return true if the grp (id) is an ancestor of condition (id) */
function isAncestor( groupID, condID, myid ) {
myid = myid || api.getCpanelDeviceId();
var c = getConditionIndex( myid )[condID];
if ( c.__parent.id === groupID ) return true;
if ( "root" === c.__parent.id ) return false; /* Can't go more */
/* Move up tree looking for matching group */
return isAncestor( groupID, c.__parent.id, myid );
}
/* Return true if node (id) is a descendent of group (id) */
function isDescendent( nodeID, groupID, myid ) {
myid = myid || api.getCpanelDeviceId();
var g = getConditionIndex( myid )[groupID];
/* Fast exit if our anchor condition isn't a group (only groups have descendents) */
if ( ! isGroup( g ) ) return false;
var l = g.conditions ? g.conditions.length : 0;
for ( var k=0; k<l; k++ ) {
if ( nodeID === g.conditions[k].id ) return true;
if ( isGroup( g.conditions[k] ) && isDescendent( nodeID, g.conditions[k].id, myid ) ) {
return true;
}
}
return false;
}
/* Clear module's per-device data and cached info */
function clearModule() {
iData = [];
actions = {};
deviceActionData = {};
deviceInfo = {};
userIx = {};
userNameIx = {};
configModified = false;
inStatusPanel = false;
spyDevice = false;
lastx = 0;
moduleReady = false;
needsRestart = false;
}
/* Initialize the module */
function initModule( myid ) {
myid = myid || api.getCpanelDeviceId();
var ud = api.getUserData();
if ( !moduleReady ) {
/* Initialize module data */
console.log("Initializing module data for ReactorSensor_UI7, device " + myid);
try {
console.log("initModule() using jQuery " + String($.fn.jquery) + "; jQuery-UI " + String($.ui.version));
} catch( e ) {
console.log("initModule() error reading jQuery/UI versions: " + String(e));
}
clearModule();
isOpenLuup = false;
isALTUI = "undefined" !== typeof(MultiBox) && null !== document.location.href.match( /id=lr_ALTUI/i );
console.log("isALTUI=",isALTUI);
unsafeLua = true;
devVeraAlerts = false;
devVeraTelegram = false;
/* Try to establish date format */
dateFormat = "%F"; /* ISO8601 default */
timeFormat = "%T";
var cfd = parseInt( getParentState( "ForceISODateTime", myid ) || "0" );
if ( isNaN(cfd) || 0 === cfd ) {
console.log("initModule() configured date format " + String(ud.date_format) + " time " + String(ud.timeFormat));
cfd = ud.date_format;
if ( undefined !== cfd ) {
dateFormat = cfd.replace( /yy/, "%Y" ).replace( /mm/, "%m" ).replace( /dd/, "%d" ).replace( "\\", "" );
timeFormat = ( "12hr" === ud.timeFormat ) ? "%I:%M:%S%p" : "%T";
}
}
/* Take a pass over devices and see what we discover */
var dl = api.getListOfDevices();
dl.forEach( function( devobj ) {
if ( devobj.device_type === "openLuup" && devobj.id_parent == 0 ) {
isOpenLuup = devobj.id;
} else if ( devobj.device_type === "urn:richardgreen:device:VeraAlert:1" && devobj.id_parent == 0 ) {
devVeraAlerts = devobj.id;
} else if ( devobj.device_type === "urn:bochicchio-com:device:VeraTelegram:1" && devobj.id_parent == 0 ) {
devVeraTelegram = devobj.id;
} else if ( devobj.device_type === "urn:schemas-upnp-org:device:altui:1" && devobj.id_parent == 0 &&
null !== document.location.href.match( /id=lr_ALTUI/i ) ) {
isALTUI = devobj.id;
}
});
/* Check UnsafeLua flag; old firmware doesn't have it so default OK (openLuup is always OK) */
unsafeLua = ( false !== isOpenLuup ) || ( 0 !== parseInt( ud.UnsafeLua || "1" ) );
/* User and geofence pre-processing */
var l = ud.users ? ud.users.length : 0;
for ( var ix=0; ix<l; ++ix ) {
userIx[ud.users[ix].id] = { name: ud.users[ix].Name || ud.users[ix].id };
userNameIx[ud.users[ix].Name || ud.users[ix].id] = ud.users[ix].id;
}
try {
$.each( ud.usergeofences || [], function( ix, fobj ) {
/* Logically, there should not be a usergeofences[] entry for a user that
doesn't exist in users[], but Vera says "hold my beer" apparently. */
if ( undefined === userIx[ fobj.iduser ] ) userIx[ fobj.iduser ] = { name: String(fobj.iduser) + '?' };
userIx[ fobj.iduser ].tags = {};
userNameIx[ fobj.iduser ] = fobj.iduser;
$.each( fobj.geotags || [], function( iy, gobj ) {
userIx[ fobj.iduser ].tags[ gobj.id ] = {
id: gobj.id,
ishome: gobj.ishome,
name: gobj.name
};
});
});
}
catch (e) {
console.log("Error applying usergeofences to userIx: " + String(e));
console.log( e );
}
/* Don't do this again. */
moduleReady = true;
}
/* Check agreement of plugin core and UI */
var s = api.getDeviceState( myid, serviceId, "_UIV", { dynamic: false } ) || "0";
console.log("initModule() for device " + myid + " requires UI version " + _UIVERSION + ", seeing " + s);
if ( String(_UIVERSION) != s ) {
api.setCpanelContent( '<div class="reactorwarning" style="border: 4px solid red; padding: 8px;">' +
" ERROR! The Reactor plugin core version and UI version do not agree." +
" This may cause errors or corrupt your ReactorSensor configuration." +
" Please hard-reload your browser and try again " +
' (<a href="https://duckduckgo.com/?q=hard+reload+browser" target="_blank">how?</a>).' +
" If you have installed hotfix patches, you may not have successfully installed all required files." +
" Expected " + String(_UIVERSION) + " got " + String(s) +
".</div>" );
return false;
}
if ( undefined === Promise ) {
alert( "Warning! The browser you are using does not support features required by this interface. The recommended browsers are Firefox, Chrome, Safari, and Edge. If you are using a modern version of one of these browsers and getting this message, please report to rigpapa via the Vera Community forums." );
return false;
}
if ( isALTUI ) {
console.log("initModule() supported ALTUI versions:",_MIN_ALTUI_VERSION,"to",_MAX_ALTUI_VERSION);
var validALTUI = false;
var av;
var av_range = String(_MIN_ALTUI_VERSION) + " to " + String(_MAX_ALTUI_VERSION);
if ( "undefined" !== typeof ALTUI_revision ) {
av = ALTUI_revision.match( /: *(\d+)/ );
if ( null !== av ) {
av = parseInt( av[1] );
console.log("initModule(): ALTUI release",av,"from ALTUI_revision");
if ( !isNaN( av ) && av >= _MIN_ALTUI_VERSION && av <= _MAX_ALTUI_VERSION ) {
validALTUI = true;
}
}
}
if ( !validALTUI ) {
alert("The running version of ALTUI has not been confirmed to be compatible with this version of the Reactor UI and is therefore not supported. Incompatibilities may cause loss of functionality or errors that result in data/configuration loss, and it is recommended that you up/downgrade to a compatible version of ALTUI before continuing.\n\nSupported versions are: " + av_range + ".\nYou are running " + String( ALTUI_revision ));
return false;
}
try {
var jq = String($.fn.jquery).split('.');
jq = parseInt( jq[0] ) * 100 + parseInt( jq[1] );
if ( jq >= 306 ) {
alert("This version of the Reactor UI does not support the version of jQuery you are using on this system. Typically, the jQuery version is determined by the ALTUI version being used, and if that version of ALTUI is supported, its default jQuery is as well. Overriding ALTUI's default to a higher version can result in incompatibilities that could result in configuration corruption.\n\nNot supported: jQuery "+String($.fn.jquery));
return false;
}
} catch( e ) {
console.log("initModule() error checking jQuery version:",e);
}
}
/* Load ACE. */
s = getParentState( "UseACE", myid ) || "1";
if ( "1" === s && ! window.ace ) {
s = getParentState( "ACEURL" ) || "https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js";
$( "head" ).append( '<script src="' + s + '"></script>' );
}
/* Initialize for instance */
console.log("initModule() initializing instance data for " + myid);
iData[myid] = iData[myid] || {};
getConfiguration( myid );
/* Force this false every time, and make the status panel change it. */
inStatusPanel = false;
return true;
}
/**
* Return list of devices sorted alpha by room sorted alpha with "no room"
* forced last. Store this for future returns; deferred effort/memory use.
*/
function getSortedDeviceList() {
if ( roomsByName ) return roomsByName;
var myid = api.getCpanelDeviceId();
var devices = api.cloneObject( api.getListOfDevices() );
var noroom = { "id": 0, "name": "No Room", "devices": [] };
var rooms = [ noroom ];
var roomIx = {};
roomIx[String(noroom.id)] = noroom;
var dd = devices.sort( function( a, b ) {
if ( a.id == myid ) return -1;
if ( b.id == myid ) return 1;
if ( a.name.toLowerCase() === b.name.toLowerCase() ) {
return a.id < b.id ? -1 : 1;
}
return a.name.toLowerCase() < b.name.toLowerCase() ? -1 : 1;
});
var l = dd.length;
for (var i=0; i<l; ++i) {
var devobj = api.cloneObject( dd[i] );
var roomid = devobj.room || 0;
var roomObj = roomIx[String(roomid)];
if ( undefined === roomObj ) {
roomObj = api.cloneObject( api.getRoomObject(roomid) );
roomObj.devices = [];
roomIx[String(roomid)] = roomObj;
rooms.push( roomObj );
}
roomObj.devices.push( devobj );
}
roomsByName = rooms.sort(
/* Special sort for room name -- sorts "No Room" last */
function (a, b) {
if (a.id === 0) return 1;
if (b.id === 0) return -1;
if (a.name.toLowerCase() === b.name.toLowerCase()) return 0;
return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
}
);
return roomsByName;
}
/* zero-fill */
function fill( s, n, p ) {
if ( "string" !== typeof(s) ) {
s = String(s);
}
p = p || "0";
var l = n - s.length;
while ( l-- > 0 ) {
s = p + s;
}
return s;
}
/* Format timestamp to string (models strftime) */
function ftime( t, fmt ) {
var dt = new Date();
dt.setTime( t );
var str = fmt || dateFormat;
str = str.replace( /%(.)/g, function( m, p ) {
switch( p ) {
case 'Y':
return String( dt.getFullYear() );
case 'm':
return fill( dt.getMonth()+1, 2 );
case 'd':
return fill( dt.getDate(), 2 );
case 'H':
return fill( dt.getHours(), 2 );
case 'I':
var i = dt.getHours() % 12;
if ( 0 === i ) i = 12;
return fill( i, 2 );
case 'p':
return dt.getHours() < 12 ? "AM" : "PM";
case 'M':
return fill( dt.getMinutes(), 2 );
case 'S':
return fill( dt.getSeconds(), 2 );
case '%':
return '%';
case 'T':
return ftime( t, "%H:%M:%S" );
case 'F':
return ftime( t, "%Y-%m-%d" );
default:
return m;
}
});
return str;
}
function textDateTime( y, m, d, hh, mm, isEnd ) {
hh = parseInt( hh || "0" );
mm = parseInt( mm || "0" );
var tstr = ( hh < 10 ? '0' : '' ) + hh + ':' + ( mm < 10 ? '0' : '' ) + mm;
/* Possible forms are YMD, MD, D with time, or just time */
if ( isEmpty( m ) ) {
if ( isEmpty( d ) ) {
return tstr;
}
return tstr + " on day " + d + " of each month";
}
m = parseInt( m );
return monthName[m] + ' ' + d + ( isEmpty( y ) ? '' : ' ' + y ) + ' ' + tstr;
}
/**