-
Notifications
You must be signed in to change notification settings - Fork 86
/
main.js
executable file
·12528 lines (10664 loc) · 393 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global $, ThreeDeeTouch, Windows, MSApp, navigator, chrome, FastClick */
/* global StatusBar, networkinterface, links, SunCalc, md5, sjcl, Camera */
/* OpenSprinkler App
* Copyright (C) 2015 - present, Samer Albahra. All rights reserved.
*
* This file is part of the OpenSprinkler project <https://opensprinkler.com>.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3 as
* published by the Free Software Foundation.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
var DEFAULT_WEATHER_SERVER_URL = "https://weather.opensprinkler.com";
var WEATHER_SERVER_URL = DEFAULT_WEATHER_SERVER_URL;
// Initialize global variables
var isIEMobile = /IEMobile/.test( navigator.userAgent ),
isAndroid = /Android|\bSilk\b/.test( navigator.userAgent ),
isiOS = /iP(ad|hone|od)/.test( navigator.userAgent ),
isFireFox = /Firefox/.test( navigator.userAgent ),
isWinApp = /MSAppHost/.test( navigator.userAgent ),
isOSXApp = window.cordova && window.cordova.platformId === "osx",
isChromeApp = typeof chrome === "object" && typeof chrome.storage === "object",
isFileCapable = !isiOS && !isAndroid && !isIEMobile && !isOSXApp &&
!isWinApp && window.FileReader,
isTouchCapable = "ontouchstart" in window || "onmsgesturechange" in window,
isMetric = ( [ "US", "BM", "PW" ].indexOf( navigator.languages[ 0 ].split( "-" )[ 1 ] ) === -1 ),
// Small wrapper to handle Chrome vs localStorage usage
storage = {
get: function( query, callback ) {
callback = callback || function() {};
if ( isChromeApp ) {
chrome.storage.local.get( query, callback );
} else {
var data = {},
i;
if ( typeof query === "string" ) {
query = [ query ];
}
for ( i in query ) {
if ( query.hasOwnProperty( i ) ) {
data[ query[ i ] ] = localStorage.getItem( query[ i ] );
}
}
callback( data );
}
},
set: function( query, callback ) {
callback = callback || function() {};
if ( isChromeApp ) {
chrome.storage.local.set( query, callback );
} else {
var i;
if ( typeof query === "object" ) {
for ( i in query ) {
if ( query.hasOwnProperty( i ) ) {
localStorage.setItem( i, query[ i ] );
}
}
}
callback( true );
}
},
remove: function( query, callback ) {
callback = callback || function() {};
if ( isChromeApp ) {
chrome.storage.local.remove( query, callback );
} else {
var i;
if ( typeof query === "string" ) {
query = [ query ];
}
for ( i in query ) {
if ( query.hasOwnProperty( i ) ) {
localStorage.removeItem( query[ i ] );
}
}
callback( true );
}
}
},
// Define general regex patterns
regex = {
gps: /^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/
},
// Define the status bar color(s) and use a darker color for Android
statusBarPrimary = isAndroid ? "#121212" : "#1D1D1D",
statusBarOverlay = isAndroid ? "#151515" : "#202020",
// Define the amount of times the app will retry an HTTP request before marking it failed
retryCount = 2,
// Initialize controller array which will store JSON data
controller = {},
switching = false,
currentCoordinates = [ 0, 0 ],
// Initialize variables to keep track of current page count
pageHistoryCount = -1,
goingBack = false,
// Define the mapping between options and JSON keys
keyIndex = {
"tz":1, "ntp":2, "dhcp":3, "ip1":4, "ip2":5, "ip3":6, "ip4":7, "gw1":8, "gw2":9, "gw3":10, "gw4":11,
"hp0":12, "hp1":13, "ar":14, "ext":15, "seq":16, "sdt":17, "mas":18, "mton":19, "mtof":20, "urs":21, "rso":22,
"wl":23, "den":24, "ipas":25, "devid":26, "con":27, "lit":28, "dim":29, "bst":30, "uwt":31, "ntp1":32, "ntp2":33,
"ntp3":34, "ntp4":35, "lg":36, "mas2":37, "mton2":38, "mtof2":39, "fpr0":41, "fpr1":42, "re":43, "dns1": 44,
"dns2":45, "dns3":46, "dns4":47, "sar":48, "ife":49, "sn1t":50, "sn1o":51, "sn2t":52, "sn2o":53, "sn1on":54,
"sn1of":55, "sn2on":56, "sn2of":57, "subn1":58, "subn2":59, "subn3":60, "subn4":61
},
// Array to hold all notifications currently displayed within the app
notifications = [],
timers = {},
curr183, currIp, currPrefix, currAuth, currPass, currAuthUser,
currAuthPass, currLocal, currLang, language, deviceip, errorTimeout, weather, openPanel;
// Prevent errors from bubbling up on Windows
if ( isWinApp ) {
$( window ).on( "error", function( msg, url, line ) {
window.console.log( msg, url, line );
return true;
} );
}
// Redirect jQuery Mobile DOM manipulation to prevent error
if ( window.MSApp ) {
if ( window.Windows && Windows.UI && Windows.UI.ApplicationSettings && Windows.UI.ApplicationSettings.SettingsPane ) {
// Add link to privacy statement
var settingsPane = Windows.UI.ApplicationSettings.SettingsPane.getForCurrentView();
// Bind the privacy policy to the settings panel
settingsPane.addEventListener( "commandsrequested", function( eventArgs ) {
var applicationCommands = eventArgs.request.applicationCommands;
var privacyCommand = new Windows.UI.ApplicationSettings.SettingsCommand(
"privacy", "Privacy Policy", function() {
window.open( "https://albahra.com/journal/privacy-policy" );
}
);
applicationCommands.append( privacyCommand );
} );
}
if ( MSApp.execUnsafeLocalFunction ) {
// Cache the old domManip function.
$.fn.oldDomManIp = $.fn.domManip;
// Override the domManip function with a call to the cached
// domManip function wrapped in a MSapp.execUnsafeLocalFunction call.
$.fn.domManip = function( args, callback, allowIntersection ) {
var that = this;
return MSApp.execUnsafeLocalFunction( function() {
return that.oldDomManIp( args, callback, allowIntersection );
} );
};
}
}
$( document )
.one( "deviceready", function() {
/** Replace window.open with InAppBrowser if available */
if ( window.cordova && window.cordova.InAppBrowser ) {
window.open = window.cordova.InAppBrowser.open;
}
try {
//Change the status bar to match the headers
StatusBar.overlaysWebView( false );
StatusBar.styleLightContent();
StatusBar.backgroundColorByHexString( statusBarPrimary );
$.mobile.window.on( "statusTap", function() {
$( "body, html" ).animate( {
scrollTop: 0
}, 700 );
} );
} catch ( err ) {}
// Hide the splash screen
setTimeout( function() {
try {
navigator.splashscreen.hide();
} catch ( err ) {}
}, 500 );
// For Android and Windows Phone devices catch the back button and redirect it
$.mobile.document.on( "backbutton", function() {
if ( isIEMobile && $.mobile.document.data( "iabOpen" ) ) {
return false;
}
checkChangesBeforeBack();
return false;
} );
updateDeviceIP();
// Check if 3D touch is available and add menu when possible
if ( isiOS ) {
ThreeDeeTouch.isAvailable( function( available ) {
if ( available ) {
// Enable quick preview on web links
ThreeDeeTouch.enableLinkPreview();
// Configure menu actions
ThreeDeeTouch.configureQuickActions( [
{
type: "sites",
title: _( "Manage Sites" ),
iconType: "Location"
},
{
type: "addprogram",
title: _( "Add Program" ),
iconType: "Add"
},
{
type: "stopall",
title: _( "Stop All Stations" ),
iconType: "Pause"
}
] );
ThreeDeeTouch.onHomeIconPressed = function( payload ) {
if ( payload.type === "sites" ) {
changePage( "#site-control" );
} else if ( payload.type === "addprogram" ) {
changePage( "#addprogram" );
} else if ( payload.type === "stopall" ) {
stopAllStations();
}
};
}
} );
}
} )
.one( "mobileinit", function() {
//Change history method for Chrome Packaged Apps
if ( isChromeApp || window.location.protocol === "file:" ) {
$.mobile.hashListeningEnabled = false;
}
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
loadUnitSetting();
} )
.on( "pagebeforechange", function( e, data ) {
var page = data.toPage,
currPage = $( ".ui-page-active" ),
hash;
// Pagebeforechange event triggers twice (before and after)
// and this check ensures we get the before state
if ( typeof data.toPage !== "string" ) {
return;
}
// Grabs the new page hash
hash = $.mobile.path.parseUrl( page ).hash;
if ( currPage.length > 0 && hash === "#" + currPage.attr( "id" ) ) {
return;
}
// Animations are patchy if the page isn't scrolled to the top.
// This scrolls the page before the animation fires off.
if ( data.options.role !== "popup" && !$( ".ui-popup-active" ).length ) {
$.mobile.silentScroll( 0 );
}
// Cycle through page possibilities and call their init functions
if ( hash === "#programs" ) {
getPrograms( data.options.programToExpand );
} else if ( hash === "#addprogram" ) {
addProgram( data.options.copyID );
} else if ( hash === "#manual" ) {
getManual();
} else if ( hash === "#about" ) {
showAbout();
} else if ( hash === "#runonce" ) {
getRunonce();
} else if ( hash === "#os-options" ) {
showOptions( data.options.expandItem );
} else if ( hash === "#preview" ) {
getPreview();
} else if ( hash === "#logs" ) {
getLogs();
} else if ( hash === "#forecast" ) {
showForecast();
} else if ( hash === "#loadingPage" ) {
checkConfigured( true );
} else if ( hash === "#start" ) {
showStart();
} else if ( hash === "#site-control" ) {
showSites();
} else if ( hash === "#sprinklers" ) {
if ( $( hash ).length === 0 ) {
showHome( data.options.firstLoad );
} else {
$( hash ).one( "pageshow", function() { refreshStatus(); } );
}
}
} )
// Handle OS resume event triggered by PhoneGap
.on( "resume", function() {
// If we don't have a current device IP set, there is nothing else to update
if ( currIp === undefined ) {
return;
}
// If cloud token is available then sync sites
cloudSync();
// Indicate the weather and device status are being updated
showLoading( "#weather,#footer-running" );
updateController( updateWeather, networkFail );
} )
.on( "pause", function() {
// Handle application being paused/closed
} )
.on( "pagebeforeshow", function( e ) {
var newpage = "#" + e.target.id;
// Modify the header and footer visibility before page show event
if ( newpage === "#start" || newpage === "#loadingPage" ) {
// Hide the header, footer and menu button on the start page
$( "#header,#footer,#footer-menu" ).hide();
} else {
// Show header, footer and menu button on all other pages
$( "#header,#footer,#footer-menu" ).show();
}
storage.get( "showDisabled", function( data ) {
if ( data.showDisabled && data.showDisabled === "true" ) {
$( newpage ).addClass( "show-hidden" ).find( ".station-hidden" ).show();
} else {
$( newpage ).removeClass( "show-hidden" ).find( ".station-hidden" ).hide();
}
} );
} )
.on( "pageshow", function( e ) {
var newpage = "#" + e.target.id,
$newpage = $( newpage );
if ( goingBack ) {
goingBack = false;
} else {
pageHistoryCount++;
}
// Fix issues between jQuery Mobile and FastClick
fixInputClick( $newpage );
if ( isControllerConnected() && newpage !== "#site-control" && newpage !== "#start" && newpage !== "#loadingPage" ) {
// Update the controller status every 5 seconds and the program and station data every 30 seconds
var refreshStatusInterval = setInterval( function() { refreshStatus(); }, 5000 ),
refreshDataInterval;
if ( !checkOSVersion( 216 ) ) {
refreshDataInterval = setInterval( refreshData, 20000 );
}
$newpage.one( "pagehide", function() {
clearInterval( refreshStatusInterval );
clearInterval( refreshDataInterval );
} );
}
} )
.on( "popupafteropen", function() {
// When a popup opens that has an overlay, update the status bar background color to match
if ( $( ".ui-overlay-b:not(.ui-screen-hidden)" ).length ) {
try {
StatusBar.backgroundColorByHexString( statusBarOverlay );
} catch ( err ) {}
}
} )
.on( "popupafterclose", function() {
$( ".ui-page-active" ).children().add( "#sprinklers-settings" ).removeClass( "blur-filter" );
// When a popup is closed, change the header back to the default color
try {
StatusBar.backgroundColorByHexString( statusBarPrimary );
} catch ( err ) {}
} )
.on( "popupbeforeposition", function() {
$( ".ui-page-active" ).children().add( "#sprinklers-settings" ).addClass( "blur-filter" );
} )
.on( "popupbeforeposition", "#localization", checkCurrLang )
.one( "pagebeforeshow", "#loadingPage", initApp );
function initApp() {
//Update the language on the page using the browser's locale
updateLang();
//Set AJAX timeout
if ( !currLocal ) {
$.ajaxSetup( {
timeout: 10000
} );
}
// Fix CSS for IE Mobile (Windows Phone 8)
if ( isIEMobile ) {
insertStyle( ".ui-toolbar-back-btn{display:none!important}ul{list-style:none!important;}" );
}
// Fix CSS for Chrome Web Store apps
if ( isChromeApp ) {
insertStyle( "html,body{overflow-y:scroll}" );
}
// Prevent caching of AJAX requests on Android and Windows Phone devices
if ( isAndroid ) {
// Hide the back button for Android (all devices have back button)
insertStyle( ".ui-toolbar-back-btn{display:none!important}" );
$( this ).ajaxStart( function() {
try {
navigator.app.clearCache();
} catch ( err ) {}
} );
} else if ( isFireFox ) {
// Allow cross domain AJAX requests in FireFox OS
$.ajaxSetup( {
xhr: function() {
return new window.XMLHttpRequest( {
mozSystem: true
} );
}
} );
} else {
$.ajaxSetup( {
"cache": false
} );
}
//After jQuery mobile is loaded set initial configuration
$.mobile.defaultPageTransition =
( isAndroid || isIEMobile ) ? "fade" : "slide";
$.mobile.hoverDelay = 0;
$.mobile.activeBtnClass = "activeButton";
// Handle In-App browser requests (marked with iab class)
$.mobile.document.on( "click", ".iab", function() {
var target = isOSXApp ? "_system" : "_blank";
var button = $( this ),
iab = window.open( this.href, target, "location=" + ( isAndroid ? "yes" : "no" ) +
",enableViewportScale=" + ( button.hasClass( "iabNoScale" ) ? "no" : "yes" ) +
",toolbar=yes,toolbarposition=top,toolbarcolor=" + statusBarPrimary +
",closebuttoncaption=" +
( button.hasClass( "iabNoScale" ) ? _( "Back" ) : _( "Done" ) )
);
if ( isIEMobile ) {
// For Windows Mobile, save state of In-App browser to allow back button to close it
$.mobile.document.data( "iabOpen", true );
iab.addEventListener( "exit", function() {
$.mobile.document.removeData( "iabOpen" );
} );
}
setTimeout( function() {
button.removeClass( "ui-btn-active" );
}, 100 );
return false;
} );
// Correctly handle popup events and prevent history navigation on custom selectmenu popup
$.mobile.document.on( "click", ".ui-select .ui-btn", function() {
var button = $( this ),
id = button.attr( "id" ).replace( "-button", "-listbox" ),
popup = $( "#" + id );
popup.popup( "destroy" ).detach().addClass( "ui-page-theme-a" );
$.mobile.pageContainer.append( popup );
popup.popup( {
history: false,
"positionTo": button,
overlayTheme: "b"
} ).popup( "open" );
button.off( "click" ).on( "click", function() {
popup.popup( "open" );
} );
return false;
} );
// Bind event handler to open panel when swiping right
$.mobile.document.on( "swiperight swipeleft", ".ui-page", function( e ) {
var page = $( ".ui-page-active" );
if ( e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA" && page.jqmData( "panel" ) !== "open" && !page.find( ".ui-popup-active" ).length ) {
if ( e.type === "swiperight" ) {
openPanel();
} else {
showNotifications();
}
}
} );
// Extend collapsible widget with event before change
$.widget( "mobile.collapsible", $.mobile.collapsible, {
_handleExpandCollapse: function( isCollapse ) {
if ( this._trigger( "before" + ( isCollapse ? "collapse" : "expand" ) ) ) {
this._superApply( arguments );
}
}
} );
//Update site based on selector
$( "#site-selector" ).on( "change", function() {
updateSite( $( this ).val() );
} );
// Bind footer menu button
$( "#footer-menu" ).on( "click", function() {
showHomeMenu( this );
} );
// Initialize the app header
$( "#header,#footer" ).toolbar();
//Attach FastClick handler
FastClick.attach( document.body );
// Start interval loop which will update timers/clocks
updateTimers();
// Handle keybinds
$.mobile.document.on( "keydown", function( e ) {
var tag = $( e.target ).prop( "tagName" );
if ( tag === "INPUT" || tag === "TEXTAREA" ) {
return;
}
var code = e.keyCode,
altDown = e.altKey,
menuOpen = $( "#mainMenu-popup" ).hasClass( "ui-popup-active" );
if ( code === 77 ) {
var menu = $( "#mainMenu" );
if ( menu.length > 0 ) {
$( "#mainMenu" ).popup( "close" );
} else {
showHomeMenu();
}
} else if ( ( menuOpen || altDown ) && code === 80 ) {
e.preventDefault();
changePage( "#programs" );
} else if ( ( menuOpen || altDown ) && code === 79 ) {
e.preventDefault();
changePage( "#os-options" );
} else if ( ( menuOpen || altDown ) && code === 86 ) {
e.preventDefault();
changePage( "#preview" );
} else if ( ( menuOpen || altDown ) && code === 76 ) {
e.preventDefault();
changePage( "#logs" );
} else if ( ( menuOpen || altDown ) && code === 82 ) {
e.preventDefault();
changePage( "#runonce" );
} else if ( ( menuOpen || altDown ) && code === 68 ) {
e.preventDefault();
showRainDelay();
}
} );
// Initialize external panel
bindPanel();
// Update the IP address of the device running the app
if ( !currLocal && typeof window.cordova === "undefined" ) {
updateDeviceIP();
}
// If cloud token is available then sync sites
cloudSync();
//On initial load check if a valid site exists for auto connect
setTimeout( function() {
checkConfigured( true );
}, 200 );
}
// Handle main switches for manual mode
function flipSwitched() {
if ( switching ) {
return;
}
//Find out what the switch was changed to
var flip = $( this ),
id = flip.attr( "id" ),
changedTo = flip.is( ":checked" ),
method = ( id === "mmm" ) ? "mm" : id,
defer;
if ( changedTo ) {
defer = sendToOS( "/cv?pw=&" + method + "=1" );
} else {
defer = sendToOS( "/cv?pw=&" + method + "=0" );
}
$.when( defer ).then( function() {
refreshStatus();
if ( id === "mmm" ) {
$( "#mm_list .green" ).removeClass( "green" );
}
checkStatus();
},
function() {
switching = true;
setTimeout( function() {
switching = false;
}, 200 );
flip.prop( "checked", !changedTo ).flipswitch( "refresh" );
} );
}
// Wrapper function to communicate with OpenSprinkler
function sendToOS( dest, type ) {
// Inject password into the request
dest = dest.replace( "pw=", "pw=" + encodeURIComponent( currPass ) );
type = type || "text";
// Designate AJAX queue based on command type
var isChange = /\/(?:cv|cs|cr|cp|uwa|dp|co|cl|cu|up|cm)/.exec( dest ),
queue = isChange ? "change" : "default",
// Use POST when sending data to the controller (requires firmware 2.1.8 or newer)
usePOST = ( isChange && checkOSVersion( 300 ) ),
obj = {
url: currPrefix + currIp + ( usePOST ? dest.split( "?" )[ 0 ] : dest ),
type: usePOST ? "POST" : "GET",
data: usePOST ? getUrlVars( dest ) : null,
dataType: type,
shouldRetry: function( xhr, current ) {
if ( xhr.status === 0 && xhr.statusText === "abort" || retryCount < current ) {
$.ajaxq.abort( queue );
return false;
}
return true;
}
},
defer;
if ( currAuth ) {
$.extend( obj, {
beforeSend: function( xhr ) {
xhr.setRequestHeader(
"Authorization", "Basic " + btoa( currAuthUser + ":" + currAuthPass )
);
}
} );
}
if ( curr183 ) {
// Firmware 1.8.3 has a bug handling the time stamp in the GET request
$.extend( obj, {
cache: "true"
} );
}
defer = $.ajaxq( queue, obj ).then(
function( data ) {
// In case the data type was incorrect, attempt to fix.
// If fix not possible, return string
if ( typeof data === "string" ) {
try {
data = $.parseJSON( data );
} catch ( e ) {
return data;
}
}
// Don't need to handle this situation for OSPi or firmware below 2.1.0
if ( typeof data !== "object" || typeof data.result !== "number" ) {
return data;
}
// Return as successful
if ( data.result === 1 ) {
return data;
// Handle incorrect password
} else if ( data.result === 2 ) {
if ( /\/(?:cv|cs|cr|cp|uwa|dp|co|cl|cu|up|cm)/.exec( dest ) ) {
showerror( _( "Check device password and try again." ) );
}
// Tell subsequent handlers this request has failed (use 401 to prevent retry)
return $.Deferred().reject( { "status":401 } );
// Handle page not found by triggering fail
} else if ( data.result === 32 ) {
return $.Deferred().reject( { "status":404 } );
}
// Only show error messages on setting change requests
if ( /\/(?:cv|cs|cr|cp|uwa|dp|co|cl|cu|up|cm)/.exec( dest ) ) {
if ( data.result === 48 ) {
showerror(
_( "The selected station is already running or is scheduled to run." )
);
} else {
showerror( _( "Please check input and try again." ) );
}
// Tell subsequent handlers this request has failed
return $.Deferred().reject( data );
}
},
function( e ) {
if ( ( e.statusText === "timeout" || e.status === 0 ) && /\/(?:cv|cs|cr|cp|uwa|dp|co|cl|cu|cm)/.exec( dest ) ) {
// Handle the connection timing out but only show error on setting change
showerror( _( "Connection timed-out. Please try again." ) );
} else if ( e.status === 401 ) {
//Handle unauthorized requests
showerror( _( "Check device password and try again." ) );
}
return;
}
);
return defer;
}
function networkFail() {
changeStatus( 0, "red", "<p class='running-text center'>" + _( "Network Error" ) + "</p>",
function() {
showLoading( "#weather,#footer-running" );
refreshStatus();
updateWeather();
}
);
}
// Gather new controller information and load home page
function newLoad() {
// Get the current site name from the site select drop down
var name = $( "#site-selector" ).val(),
loading = "<div class='logo'></div>" +
"<h1 style='padding-top:5px'>" + _( "Connecting to" ) + " " + name + "</h1>" +
"<p class='cancel tight center inline-icon'>" +
"<span class='btn-no-border ui-btn ui-icon-delete ui-btn-icon-notext'></span>" +
"Cancel" +
"</p>";
$.mobile.loading( "show", {
html: currLocal ? "<h1>" + _( "Loading" ) + "</h1>" : loading,
textVisible: true,
theme: "b"
} );
$( ".ui-loader" ).css( {
"box-shadow": "none",
"margin-top": "-4em"
} ).find( ".cancel" ).one( "click", function() {
$.ajaxq.abort( "default" );
changePage( "#site-control", {
transition: "none"
} );
} );
//Empty object which will store device data
controller = {};
//Empty notifications
clearNotifications();
//Empty timers object
timers = {};
//Clear the current queued AJAX requests (used for previous controller connection)
$.ajaxq.abort( "default" );
updateController(
function() {
var weatherAdjust = $( ".weatherAdjust" ),
changePassword = $( ".changePassword" );
$.mobile.loading( "hide" );
checkURLandUpdateWeather();
if ( checkOSVersion( 210 ) ) {
weatherAdjust.css( "display", "" );
} else {
weatherAdjust.hide();
}
// Hide change password feature for unsupported devices
if ( isOSPi() || checkOSVersion( 208 ) ) {
changePassword.css( "display", "" );
} else {
changePassword.hide();
}
// Show site name instead of default Information bar
if ( !currLocal ) {
$( "#info-list" ).find( "li[data-role='list-divider']" ).text( name );
document.title = "OpenSprinkler - " + name;
} else {
$( "#info-list" ).find( "li[data-role='list-divider']" ).text( _( "Information" ) );
}
// Check if a firmware update is available
checkFirmwareUpdate();
// Check for unused expansion boards
detectUnusedExpansionBoards();
// Check if password is plain text (older method) and hash the password, if needed
if ( checkOSVersion( 213 ) && controller.options.hwv !== 255 ) {
fixPasswordHash( name );
}
// Check if the OpenSprinkler can be accessed from the public IP
if ( !currLocal && typeof controller.settings.eip === "number" ) {
checkPublicAccess( controller.settings.eip );
}
// Check if a cloud token is available and if so show logout button otherwise show login
updateLoginButtons();
if ( isOSPi() ) {
// Show notification of unified firmware availability
showUnifiedFirmwareNotification();
}
if ( controller.options.firstRun ) {
showGuidedSetup();
} else {
goHome( true );
}
},
function( error ) {
$.ajaxq.abort( "default" );
controller = {};
$.mobile.loading( "hide" );
var fail = function() {
if ( !currLocal ) {
if ( $( ".ui-page-active" ).attr( "id" ) === "site-control" ) {
showFail();
} else {
$.mobile.document.one( "pageshow", showFail );
changePage( "#site-control", {
transition: "none"
} );
}
} else {
storage.remove( [ "sites" ], function() {
window.location.reload();
} );
}
},
showFail = function() {
showerror( _( "Unable to connect to" ) + " " + name, 3500 );
};
if ( typeof error === "object" && error.status === 401 ) {
$( ".ui-popup-active" ).find( "[data-role='popup']" ).popup( "close" );
changePassword( {
fixIncorrect: true,
name: name,
callback: newLoad,
cancel: fail
} );
} else {
fail();
}
}
);
}
// Update controller information
function updateController( callback, fail ) {
callback = callback || function() {};
fail = fail || function() {};
var finish = function() {
$( "html" ).trigger( "datarefresh" );
checkStatus();
callback();
};
if ( isControllerConnected() && checkOSVersion( 216 ) ) {
sendToOS( "/ja?pw=", "json" ).then( function( data ) {
if ( typeof data === "undefined" || $.isEmptyObject( data ) ) {
fail();
return;
}
// The /ja call does not contain special station data, so let's cache it
var special = controller.special;
controller = data;
// Restore the station cache to the object
controller.special = special;
// Fix the station status array
controller.status = controller.status.sn;
finish();
}, fail );
} else {
$.when(
updateControllerPrograms(),
updateControllerStations(),
updateControllerOptions(),
updateControllerStatus(),
updateControllerSettings()
).then( finish, fail );
}
}
function updateControllerPrograms( callback ) {
callback = callback || function() {};
if ( curr183 === true ) {
// If the controller is using firmware 1.8.3, then parse the script tag for variables
return sendToOS( "/gp?d=0" ).done( function( programs ) {
var vars = programs.match( /(nprogs|nboards|mnp)=[\w|\d|.\"]+/g ),
progs = /pd=\[\];(.*);/.exec( programs ),
newdata = {}, tmp, prog;
for ( var i = 0; i < vars.length; i++ ) {
if ( vars[ i ] === "" ) {
continue;
}
tmp = vars[ i ].split( "=" );
newdata[ tmp[ 0 ] ] = parseInt( tmp[ 1 ] );
}
newdata.pd = [];
if ( progs !== null ) {
progs = progs[ 1 ].split( ";" );
for ( i = 0; i < progs.length; i++ ) {
prog = progs[ i ].split( "=" );
prog = prog[ 1 ].replace( "[", "" );
prog = prog.replace( "]", "" );
newdata.pd[ i ] = parseIntArray( prog.split( "," ) );
}
}
controller.programs = newdata;
callback();