-
Notifications
You must be signed in to change notification settings - Fork 50
/
housepanel.js
3027 lines (2709 loc) · 123 KB
/
housepanel.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
/* javascript file for HousePanel
*
* Developed by Ken Washington @kewashi
* Designed for use only with HousePanel for Hubitat and SmartThings
* (c) Ken Washington 2017 - 2020
*
* 01/02/2020 - updated to fix z-index bug so things show up on top properly
*
*/
// globals array used everywhere now
var cm_Globals = {};
cm_Globals.thingindex = null;
cm_Globals.thingidx = null;
cm_Globals.allthings = null;
cm_Globals.options = null;
cm_Globals.returnURL = "housepanel.php";
cm_Globals.hubId = "all";
var modalStatus = 0;
var modalWindows = [];
var priorOpmode = "Operate";
var dragZindex = 1;
var pagename = "main";
// set a global socket variable to manage two-way handshake
var wsSocket = null;
var webSocketUrl = null;
var wsinterval = null;
var nodejsUrl = null;
var reordered = false;
// set this global variable to true to disable actions
// I use this for testing the look and feel on a public hosting location
// this way the app can be installed but won't control my home
// end-users are welcome to use this but it is intended for development only
// use the timers options to turn off polling
var disablepub = false;
var disablebtn = false;
var LOGWEBSOCKET = true;
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
function setCookie(cname, cvalue, exdays) {
if ( !exdays ) exdays = 30;
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function getAllthings(modalwindow, reload) {
var swattr = reload ? "reload" : "none";
// alert("swattr= " + swattr + " returnURL= " + cm_Globals.returnURL);
$.post(cm_Globals.returnURL,
{useajax: "getthings", id: "none", type: "none", attr: swattr},
function (presult, pstatus) {
if (pstatus==="success" && typeof presult === "object" ) {
var keys = Object.keys(presult);
cm_Globals.allthings = presult;
console.log("getAllthings returned: " + keys.length + " things (reload: " + swattr + ")");
if ( ! cm_Globals.options ) {
getOptions();
}
// setup customize dialog box if it is open
if ( cm_Globals.thingindex && cm_Globals.thingidx ) {
try {
getDefaultSubids();
var idx = cm_Globals.thingidx;
var allthings = cm_Globals.allthings;
var thing = allthings[idx];
$("#cm_subheader").html(thing.name);
initCustomActions();
handleBuiltin(cm_Globals.defaultclick);
} catch (e) { }
}
} else {
console.log("Error: failure obtaining things from HousePanel: ", presult);
cm_Globals.allthings = null;
// try again but this time forcing a reload
if ( modalwindow===false && reload===false ) {
getAllthings(false, true);
}
if ( modalwindow ) {
closeModal(modalwindow);
}
// closeModal("modalcustom");
}
}, "json"
);
}
// obtain options using an ajax api call
// could probably read Options file instead
// but doing it this way ensure we get what main app sees
function getOptions() {
$.post(cm_Globals.returnURL,
{useajax: "getoptions", id: "none", type: "none"},
function (presult, pstatus) {
if (pstatus==="success" && typeof presult === "object" && presult.index ) {
cm_Globals.options = presult;
var indexkeys = Object.keys(presult.index);
console.log("getOptions returned: " + indexkeys.length + " things");
if ( pagename==="main" ) {
setupUserOpts();
}
} else {
cm_Globals.options = null;
console.log("error - failure reading your hmoptions.cfg file");
}
}, "json"
);
}
$(document).ready(function() {
// set the global return URL value
var returnURL;
try {
returnURL = $("input[name='returnURL']").val();
} catch(e) {
returnURL = "housepanel.php";
}
cm_Globals.returnURL = returnURL;
try {
pagename = $("input[name='pagename']").val();
} catch(e) {
pagename = "main";
}
// show tabs and hide skin
if ( pagename==="main" ) {
$("#tabs").tabs();
var tabcount = $("li.ui-tabs-tab").length;
// hide tabs if there is only one room
if ( tabcount === 1 ) {
toggleTabs();
}
// get default tab from cookie and go to that tab
var defaultTab = getCookie( 'defaultTab' );
if ( defaultTab && tabcount > 1 ) {
try {
$("#"+defaultTab).click();
} catch (e) {
defaultTab = $("#roomtabs").children().first().attr("aria-labelledby");
setCookie('defaultTab', defaultTab, 30);
try {
$("#"+defaultTab).click();
} catch (f) {
console.log(f);
}
}
}
}
// first try to load fast, if failed do slow
// this is caused by json_encode hanging in main routine
// getOptions();
if ( pagename==="main" || pagename==="options" ) {
getAllthings(false, false);
// setTimeout(function() {
// if ( !cm_Globals.allthings ) {
// getAllthings(false, true);
// }
// }, 3000);
}
// disable return key
$("body").off("keypress");
$("body").on("keypress", function(e) {
if ( e.keyCode===13 ){
return false;
}
});
setupButtons();
setupSaveButton();
if (pagename==="options") {
setupCustomCount();
setupFilters();
}
if ( pagename==="main" ) {
setupSliders();
setupTabclick();
setupColors();
cancelDraggable();
cancelSortable();
cancelPagemove();
}
// finally we wait a few seconds then setup page clicks
setTimeout(function() {
if ( pagename==="main" && !disablepub ) {
setupPage();
dragZindex = getMaxZindex("");
}
}, 2000);
});
function setupUserOpts() {
// get hub info from options array
var options = cm_Globals.options;
if ( !options || !options.config ) {
console.log("error - valid options file not found.");
return;
} else {
console.log("options config: ", options.config);
}
var config = options.config;
// we could disable this timer loop
// we also grab timer from each hub setting now
// becuase we now do on-demand updates via webSockets
// but for now we keep it just as a backup to keep things updated
try {
var hubs = config["hubs"];
} catch(err) {
console.log ("Couldn't retrieve hubs. err: ", err);
hubs = null;
}
if ( hubs && typeof hubs === "object" ) {
// loop through every hub
$.each(hubs, function (num, hub) {
// var hubType = hub.hubType;
var timerval;
var hubId = hub.hubId;
if ( hub.hubTimer ) {
timerval = parseInt(hub.hubTimer, 10);
} else {
timerval = 300000;
}
if ( timerval && timerval >= 1000 ) {
setupTimer(timerval, "all", hubId);
}
});
}
// try to get timers
try {
var fast_timer = config.fast_timer;
fast_timer = parseInt(fast_timer, 10);
var slow_timer = config.slow_timer;
slow_timer = parseInt(slow_timer, 10);
} catch(err) {
console.log ("Couldn't retrieve timers; using defaults. err: ", err);
fast_timer = 0;
slow_timer = 3600000;
}
// this can be disabled by setting anything less than 1000
if ( fast_timer && fast_timer >= 1000 ) {
setupTimer(fast_timer, "fast", -1);
}
if ( slow_timer && slow_timer >= 1000 ) {
setupTimer(slow_timer, "slow", -1);
}
// get the webSocket info and the timers
try {
webSocketUrl = $("input[name='webSocketUrl']").val();
nodejsUrl = $("input[name='nodejsUrl']").val();
} catch(err) {
console.log("Error attempting to retrieve webSocket URL. err: ", err);
webSocketUrl = null;
nodejsUrl = null;
}
var tzoffset;
try {
tzoffset = $("input[name='tzoffset']").val();
tzoffset = parseInt(tzoffset, 10);
} catch(err) {
console.log("Error attempting to retrieve timezone offset. err: ", err);
tzoffset = 0;
}
clockUpdater(tzoffset);
// periodically check for socket open and if not open reopen
if ( webSocketUrl ) {
wsSocketCheck();
wsinterval = setInterval(wsSocketCheck, 300000);
}
}
// check to make sure we always have a websocket
function wsSocketCheck() {
if ( webSocketUrl && ( wsSocket === null || wsSocket.readyState===3 ) ) {
setupWebsocket();
}
if ( !webSocketUrl && wsinterval ) {
cancelInterval(wsinterval);
}
}
// send a message over to our web socket
// usually to tell it to update the elements since dashboard has changed
// but in theory this could be any message for future use
function wsSocketSend(msg) {
if ( webSocketUrl && wsSocket && wsSocket.readyState===1 ) {
wsSocket.send(msg);
}
}
// new routine to set up and handle websockets
// only need to do this once - I have no clue why it was done the other way before
function setupWebsocket()
{
try {
console.log("Creating webSocket for: ", webSocketUrl);
wsSocket = new WebSocket(webSocketUrl);
} catch(err) {
console.log("Error attempting to create webSocket for: ", webSocketUrl," error: ", err);
return;
}
// upon opening a new socket notify user and do nothing else
wsSocket.onopen = function(){
console.log("webSocket connection opened for: ", webSocketUrl);
};
wsSocket.onerror = function(evt) {
console.error("webSocket error observed: ", evt);
};
// received a message from housepanel-push
// this contains a single device object
wsSocket.onmessage = function (evt) {
var reservedcap = ["name", "DeviceWatch-DeviceStatus", "DeviceWatch-Enroll", "checkInterval", "healthStatus"];
try {
var presult = JSON.parse(evt.data);
var pvalue = presult.value;
// grab name and trigger for console log
var pname = pvalue["name"] ? pvalue["name"] : "";
var trigger = presult.trigger;
// remove reserved fields
$.each(reservedcap, function(index, val) {
if ( pvalue[val] ) {
delete pvalue[val];
}
});
var bid = presult.id;
var thetype = presult.type;
var client = presult.client;
var clientcount = presult.clientcount;
if ( LOGWEBSOCKET ) {
console.log("webSocket message from: ", webSocketUrl," bid= ",bid," name:",pname," client:",client," of:",clientcount," type= ",thetype," trigger= ",trigger," value= ",pvalue);
}
} catch (err) {
console.log("Error interpreting webSocket message. err: ", err);
return;
}
if ( thetype==="music" ) {
// remove any existing image since it could be old
if ( pvalue["trackImage"] ) {
delete( pvalue["trackImage"] );
}
// skip music track descriptions that start with grouped to avoid
// overwriting more useful variant also typically sent previously
// var desc = pvalue["trackDescription"];
// if ( desc && desc.startsWith("Grouped with") ) {
// delete( pvalue["trackDescription"] );
// }
if ( pvalue["status"] === "stopped" ) {
pvalue["trackDescription"] = "None";
}
}
// check if we have valid info for this update item
if ( bid!==null && thetype && pvalue && typeof pvalue==="object" ) {
// remove color for now until we get it fixed
if ( pvalue["color"] ) {
delete( pvalue["color"] );
}
// update all the tiles that match this type and id
// this now works even if tile isn't on the panel because
// now we read the options file and grab the tile number
// this is done in the processRules function below
$('div.panel div.thing[bid="'+bid+'"][type="'+thetype+'"]').each(function() {
try {
var aid = $(this).attr("id").substring(2);
updateTile(aid, pvalue);
} catch (e) {
console.log("Error updating tile of type: "+ thetype + " and id: " + bid + " with value: ", pvalue);
}
});
}
// handle rules and link triggers but only for the last client
// since we only need one of the clients to execute rules
// rules and link triggers do not update the screen
// so you must have the node pusher app installed to keep things synced
if ( cm_Globals.options && client===clientcount ) {
if ( cm_Globals.options["rules"]==="true" || cm_Globals.options["rules"]===true ) {
processRules(pname, bid, thetype, trigger, pvalue);
processLinks(pname, bid, thetype, trigger, pvalue);
}
}
};
// if this socket connection closes then try to reconnect
wsSocket.onclose = function(){
console.log("webSocket connection closed for: ", webSocketUrl);
wsSocket = null;
};
}
function processRules(pname, bid, thetype, trigger, pvalue) {
// go through all tiles with a new rule type
var idx = thetype + "|" + bid;
try {
var index = cm_Globals.options["index"];
var tileid = index[idx].toString();
} catch (e) {
console.log("webSocket RULE error: ", pname, " id: ", bid, " type: ", thetype, " trigger: ", trigger, " error: ", e);
return;
}
// rule structure
// if: tile=num[= or < or > or !]value, tile=num=value[=attr], tile=num=attr=[attr]...
// num is the tile number and value is the comparison text or value string
// the symbol between num and value determines if this is an equal, less, greater, or not equal test
// the attr variable is optional but if provided will be sent to the api
//
// construct the if phrase for the trigger
var regpattern = /if\s*[:| ]\s*(\d*)\s*=\s*([\w\s-]*)(=|<|>|!)\s*(.*)/;
var itempattern = /(\d*)\s*=\s*([\w\s-]*)\s*=\s*(.*)/;
var itempattern2 = /(\d*)\s*=\s*([\w\s-]*)\s*=\s*(.*)=(.*)/;
var regsplit = /[,;]/;
var ifvalue = pvalue[trigger];
// print some debug info
if ( LOGWEBSOCKET ) {
console.log("webSocket RULE - name: ", pname, " id: ", bid, " type: ", thetype, " trigger: ", trigger, " tileid: ", tileid);
}
// process all tiles that subscribe to this trigger
$('div.user_hidden[command="RULE"]').each(function() {
var linkval = $(this).attr("linkval");
// split the commands into trigger and other commands
var testcommands = linkval.split(regsplit);
var triggercom = testcommands[0].trim();
var res = triggercom.match(regpattern);
var ismatch = false;
if ( testcommands.length > 1 && res ) {
var matchtile = res[1].trim();
var matchsubid = res[2].trim();
var matchop = res[3];
var matchval = res[4].trim();
// check to see if this custom tile matches the rule specification
// to match the tile number and the subid must match the trigger
// and the rule operand must be either =, <, >, or !
if ( matchtile===tileid && matchsubid===trigger ) {
ismatch = (
matchop==="=" && matchval===ifvalue ||
matchop==="!" && matchval!==ifvalue ||
matchop==="<" && matchval < ifvalue ||
matchop===">" && matchval > ifvalue
);
}
}
// console.log("ismatch: ", ismatch, " tileid: ", tileid, " linkval: ", linkval, " res: ", res, " testcommands: ", testcommands);
// process all the actions requested if the if conditions are met
// this loops through all the actions specified after the trigger test
// the triggering tile must exist on the panel for this to work
if ( ismatch ) {
var i;
for ( i= 1; i < testcommands.length; i++ ) {
var itemaction = testcommands[i].trim();
var items = itemaction.match(itempattern);
var items2 = itemaction.match(itempattern2);
if ( items ) {
// get the tile info for this rule item
// this pulls the items from the regular expression variables
var tilenum = items[1].trim();
var subidtrigger = items[2].trim();
var ontrigger;
var theattr;
// get the first tile on the panel that matches this tile number
var tile = $('div.panel div.thing[tile="'+tilenum+'"]').first();
if ( tile ) {
var aid = tile.attr("id").substring(2);
var trbid = tile.attr("bid");
if ( items2 ) {
ontrigger = items2[3].trim();
theattr = items2[4].trim();
} else {
ontrigger = items[3];
// theattr = $("a-"+aid+"-"+subidtrigger).attr("class");
theattr = "";
}
var hubnum = tile.attr("hub");
var trtype = tile.attr("type");
// invoke the command for the subscribed tile if it will make a difference
// var currentvalue = $("#a-"+aid+"-"+subidtrigger).html();
console.log("Rule trigger for tile: ", tilenum, " type: ", trtype, " id: ", trbid, "subid: ", subidtrigger, " value: ", ontrigger, " attr: ", theattr);
var ajaxcall = "doaction";
$.post(cm_Globals.returnURL,
{useajax: ajaxcall, id: trbid, tile: tilenum, type: trtype, value: ontrigger, attr: theattr, hubid: hubnum, subid: subidtrigger},
function (presult, pstatus) {
if (pstatus==="success" ) {
console.log( ajaxcall + ": POST returned: ", presult );
// if ( presult["name"] ) { delete presult["name"]; }
// if ( presult["password"] ) { delete presult["password"]; }
// updateTile(aid, presult);
}
}, "json"
);
}
}
}
}
});
}
function processLinks(pname, bid, thetype, trigger, pvalue) {
// go through all tiles with a new rule type
var idx = thetype + "|" + bid;
try {
var index = cm_Globals.options["index"];
var tileid = index[idx];
} catch (e) {
console.log("webSocket LINK error: ", pname, " id: ", bid, " type: ", thetype, " trigger: ", trigger, " error: ", e);
return;
}
// process linked auto-on auto-off lights
$('div.user_hidden[command="LINK"][linkval="' + tileid + '"]').each(function() {
var ontrigger = "";
var subidtrigger = "switch";
var tile = $(this).parents("div.thing").last();
var tilenum = tile.attr("tile");
var trbid = tile.attr("bid");
var aid = tile.attr("id").substring(2);
var theattr = tile.attr("class");
var hubnum = tile.attr("hub");
var trtype = tile.attr("type");
// handle case where changed tile is linked to this one
if ( trtype === "switch" || trtype === "switchlevel" ||
trtype==="bulb" || trtype==="light" )
{
if ( trigger==="motion" && pvalue.motion ==="active" ) {
ontrigger = "on";
} else if ( trigger==="motion" && pvalue.motion ==="inactive" ) {
ontrigger = "off";
} else if ( trigger==="contact" && pvalue.contact ==="open" ) {
ontrigger = "on";
} else if ( trigger==="contact" && pvalue.contact ==="closed" ) {
ontrigger = "off";
} else if ( trigger==="switch" && pvalue.switch ==="on" ) {
ontrigger = "on";
} else if ( trigger==="switch" && pvalue.switch ==="off" ) {
ontrigger = "off";
}
// invoke the command for the subscribed tile
var currentvalue = $("#a-"+aid+"-"+subidtrigger).html();
if ( ontrigger && ontrigger !== currentvalue ) {
var ajaxcall = "doaction";
console.log("LINK trigger for tile: ", tilenum, "trigger: ", trigger, " type: ", trtype, " bid: ", trbid, "subid: ", subidtrigger, " current: ",currentvalue," ontrigger: ", ontrigger);
$.post(cm_Globals.returnURL,
{useajax: ajaxcall, id: trbid, type: trtype, value: ontrigger, attr: theattr, hubid: hubnum, subid: subidtrigger},
function (presult, pstatus) {
if (pstatus==="success" ) {
console.log( ajaxcall + ": POST returned: ", presult );
if ( presult["name"] ) { delete presult["name"]; }
if ( presult["password"] ) { delete presult["password"]; }
updateTile(aid, presult);
}
}, "json"
);
}
}
});
}
function rgb2hsv(r, g, b) {
//remove spaces from input RGB values, convert to int
var r = parseInt( (''+r).replace(/\s/g,''),10 );
var g = parseInt( (''+g).replace(/\s/g,''),10 );
var b = parseInt( (''+b).replace(/\s/g,''),10 );
if ( r===null || g===null || b===null ||
isNaN(r) || isNaN(g)|| isNaN(b) ) {
return {"hue": 0, "saturation": 0, "level": 0};
}
if (r<0 || g<0 || b<0 || r>255 || g>255 || b>255) {
return {"hue": 0, "saturation": 0, "level": 0};
}
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max === 0 ? 0 : d / max;
if (max === min) {
h = 0; // achromatic
} else {
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
h = Math.floor(h * 100);
s = Math.floor(s * 100);
v = Math.floor(v * 100);
return {"hue": h, "saturation": s, "level": v};
}
function getMaxZindex(panel) {
var zmax = 2;
var target = "div.panel";
if ( panel ) {
target = target + "-" + panel;
}
$(target+" div.thing").each( function() {
var zindex = $(this).css("z-index");
if ( zindex ) {
zindex = parseInt(zindex, 10);
if ( zindex && zindex > zmax ) { zmax = zindex; }
}
});
if ( zmax >= 999 ) {
zmax = 2;
}
return zmax;
}
function convertToModal(modalcontent, addok) {
if ( typeof addok === "string" )
{
modalcontent = modalcontent + '<div class="modalbuttons"><button name="okay" id="modalokay" class="dialogbtn okay">' + addok + '</button></div>';
} else {
modalcontent = modalcontent + '<div class="modalbuttons"><button name="okay" id="modalokay" class="dialogbtn okay">Okay</button>';
modalcontent = modalcontent + '<button name="cancel" id="modalcancel" class="dialogbtn cancel">Cancel</button></div>';
}
return modalcontent;
}
function createModal(modalid, modalcontent, modaltag, addok, pos, responsefunction, loadfunction) {
// var modalid = "modalid";
// skip if this modal window is already up...
if ( typeof modalWindows["modalcustom"]!=="undefined" && modalWindows[modalid]>0 ) { return; }
modalWindows[modalid] = 1;
modalStatus = modalStatus + 1;
var modaldata = modalcontent;
var modalhook;
var postype;
if ( modaltag && typeof modaltag === "object" ) {
modalhook = modaltag;
postype = "relative";
} else if ( modaltag && (typeof modaltag === "string") && typeof ($(modaltag)) === "object" ) {
// console.log("modaltag string: ", modaltag);
modalhook = $(modaltag);
if ( modaltag==="body" || modaltag==="document" || modaltag==="window" ) {
postype = "absolute";
} else {
postype = "relative";
}
} else {
// alert("default body");
// console.log("modaltag body: ", modaltag);
modalhook = $("body");
postype = "absolute";
}
var styleinfo = "";
if ( pos ) {
// enable full style specification of specific attributes
if ( pos.style ) {
styleinfo = " style=\"" + pos.style + "\"";
} else {
if ( pos.position ) {
postype = pos.position;
}
styleinfo = " style=\"position: " + postype + ";";
if ( !isNaN(pos.left) && !isNaN(pos.top) ) {
styleinfo += " left: " + pos.left + "px; top: " + pos.top + "px;";
}
if ( pos.width && pos.height ) {
styleinfo += " width: " + pos.width + "px; height: " + pos.height + "px;";
}
if ( pos.border ) {
styleinfo += " border: " + pos.border + ";";
}
if ( pos.background ) {
styleinfo += " background: " + pos.background + ";";
}
if ( pos.color ) {
styleinfo += " color: " + pos.color + ";";
}
if ( pos.zindex ) {
styleinfo += " z-index: " + pos.zindex + ";";
}
styleinfo += "\"";
}
}
modalcontent = "<div id='" + modalid +"' class='modalbox'" + styleinfo + ">" + modalcontent;
if ( addok ) {
modalcontent = convertToModal(modalcontent, addok);
}
modalcontent = modalcontent + "</div>";
modalhook.prepend(modalcontent);
// call post setup function if provided
if ( loadfunction ) {
loadfunction(modalhook, modaldata);
}
// invoke response to click
if ( addok ) {
$("#"+modalid).on("click",".dialogbtn", function(evt) {
if ( responsefunction ) {
responsefunction(this, modaldata);
}
closeModal(modalid);
});
} else {
// body clicks turn of modals unless clicking on box itself
// or if this is a popup window any click will close it
$("body").off("click");
$("body").on("click",function(evt) {
if ( (evt.target.id === modalid && modalid!=="modalpopup") || modalid==="waitbox") {
evt.stopPropagation();
return;
} else {
if ( responsefunction ) {
responsefunction(evt.target, modaldata);
}
closeModal(modalid);
$("body").off("click");
}
});
}
}
function closeModal(modalid) {
$("#"+modalid).remove();
modalWindows[modalid] = 0;
modalStatus = modalStatus - 1;
if ( modalStatus < 0 ) { modalStatus = 0; }
}
function setupColors() {
$("div.overlay.color >div.color").each( function() {
var that = $(this);
$(this).minicolors({
position: "bottom left",
defaultValue: that.html(),
theme: 'default',
change: function(hex) {
try {
that.html(hex);
var aid = that.attr("aid");
that.css({"background-color": hex});
var huetag = $("#a-"+aid+"-hue");
var sattag = $("#a-"+aid+"-saturation");
if ( huetag.length ) { huetag.css({"background-color": hex}); }
if ( sattag.length ) { sattag.css({"background-color": hex}); }
} catch(e) {}
},
hide: function() {
var newcolor = $(this).minicolors("rgbObject");
var hsl = rgb2hsv( newcolor.r, newcolor.g, newcolor.b );
var hslstr = "hsl("+hsl.hue.pad(3)+","+hsl.saturation.pad(3)+","+hsl.level.pad(3)+")";
var aid = that.attr("aid");
var tile = '#t-'+aid;
var bid = $(tile).attr("bid");
var hubnum = $(tile).attr("hub");
var bidupd = bid;
var thetype = $(tile).attr("type");
var ajaxcall = "doaction";
console.log(ajaxcall + ": id= "+bid+" type= "+ thetype+ " color= "+ hslstr);
$.post(cm_Globals.returnURL,
{useajax: ajaxcall, id: bid, type: thetype, value: hslstr, attr: "color", hubid: hubnum},
function (presult, pstatus) {
if (pstatus==="success" ) {
console.log(ajaxcall + ": value: ", presult);
if ( presult["name"] ) { delete presult["name"]; }
if ( presult["password"] ) { delete presult["password"]; }
updateTile(aid, presult);
// updAll("color",aid,bidupd,thetype,hubnum,presult);
}
}, "json"
);
}
});
});
}
function setupSliders() {
$("div.overlay.level >div.level, div.overlay.volume >div.volume").slider({
orientation: "horizontal",
min: 0,
max: 100,
step: 5,
stop: function( evt, ui) {
var thing = $(evt.target);
thing.attr("value",ui.value);
var aid = thing.attr("aid");
var tile = '#t-'+aid;
var bid = $(tile).attr("bid");
var hubnum = $(tile).attr("hub");
var bidupd = bid;
var ajaxcall = "doaction";
var subid = thing.attr("subid");
var thevalue = parseInt(ui.value);
var thetype = $(tile).attr("type");
var usertile = thing.siblings(".user_hidden");
var command = "";
var linktype = thetype;
var linkval = "";
if ( usertile && $(usertile).attr("command") ) {
command = $(usertile).attr("command"); // command type
if ( !thevalue ) {
thevalue = $(usertile).attr("value"); // raw user provided val
}
linkval = $(usertile).attr("linkval"); // urlencooded val
linktype = $(usertile).attr("linktype"); // type of tile linked to
}
console.log(ajaxcall + ": id= "+bid+" type= "+linktype+ " value= " + thevalue + " subid= " + subid + " command= " + command + " linkval: ", linkval);
// handle music volume different than lights
if ( thetype != "music") {
$.post(cm_Globals.returnURL,
{useajax: ajaxcall, id: bid, type: linktype, value: thevalue, attr: "level", subid: subid, hubid: hubnum, command: command, linkval: linkval},
function (presult, pstatus) {
if (pstatus==="success" ) {
console.log( ajaxcall + ": POST returned: ", presult );
if ( presult["name"] ) { delete presult["name"]; }
if ( presult["password"] ) { delete presult["password"]; }
updAll(subid,aid,bidupd,thetype,hubnum,presult);
}
}, "json"
);
// for music volume we pause briefly then update
} else {
$.post(cm_Globals.returnURL,
{useajax: ajaxcall, id: bid, type: linktype, value: thevalue, attr: "level", subid: subid, hubid: hubnum, command: command, linkval: linkval},
function (presult, pstatus) {
if (pstatus==="success" ) {
console.log( ajaxcall + ": POST returned: ", presult );
if ( presult["name"] ) { delete presult["name"]; }
if ( presult["password"] ) { delete presult["password"]; }
setTimeout(function() {
updateTile(aid, presult);
}, 1000);
}
}, "json"
);
}
}
});
// set the initial slider values
$("div.overlay.level >div.level, div.overlay.volume >div.volume").each( function(){
var initval = $(this).attr("value");
// alert("setting up slider with value = " + initval);
$(this).slider("value", initval);
});
// now set up all colorTemperature sliders
$("div.overlay.colorTemperature >div.colorTemperature").slider({
orientation: "horizontal",
min: 2000,
max: 7400,
step: 200,
stop: function( evt, ui) {
var thing = $(evt.target);
thing.attr("value",ui.value);
var aid = thing.attr("aid");
var tile = '#t-'+aid;
var bid = $(tile).attr("bid");
var hubnum = $(tile).attr("hub");
var bidupd = bid;
var ajaxcall = "doaction";
var subid = thing.attr("subid");
var thevalue = parseInt(ui.value);
var thetype = $(tile).attr("type");
var usertile = thing.siblings(".user_hidden");
var command = "";
var linktype = thetype;
var linkval = "";
if ( usertile ) {
command = $(usertile).attr("command"); // command type
if ( !thevalue ) {
thevalue = $(usertile).attr("value"); // raw user provided val
}
linkval = $(usertile).attr("linkval"); // urlencooded val
linktype = $(usertile).attr("linktype"); // type of tile linked to
}
console.log(ajaxcall + ": command= " + command + " id= "+bid+" type= "+linktype+ " value= " + thevalue + " subid= " + subid + " command= " + command + " linkval: ", linkval);
$.post(cm_Globals.returnURL,
{useajax: ajaxcall, id: bid, type: thetype, value: parseInt(ui.value), attr: "colorTemperature", hubid: hubnum, command: command, linkval: linkval },
function (presult, pstatus) {
if (pstatus==="success" ) {
console.log( ajaxcall + ": POST returned: ", presult );
if ( presult["name"] ) { delete presult["name"]; }
if ( presult["password"] ) { delete presult["password"]; }
updAll(subid,aid,bidupd,thetype,hubnum,presult);
}
}, "json"
);
}
});
// set the initial slider values
$("div.overlay.colorTemperature >div.colorTemperature").each( function(){
var initval = $(this).attr("value");
// alert("setting up slider with value = " + initval);
$(this).slider("value", initval);
});
}
function cancelDraggable() {
$("div.panel div.thing").each(function(){
if ( $(this).draggable("instance") ) {
$(this).draggable("destroy");
// remove the position so color swatch stays on top