-
Notifications
You must be signed in to change notification settings - Fork 632
Expand file tree
/
Copy pathcustom.js
More file actions
1939 lines (1559 loc) · 55.4 KB
/
Copy pathcustom.js
File metadata and controls
1939 lines (1559 loc) · 55.4 KB
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
var websock;
var password = false;
var maxNetworks;
var maxSchedules;
var messages = [];
var free_size = 0;
var urls = {};
var numChanged = 0;
var numReboot = 0;
var numReconnect = 0;
var numReload = 0;
var useWhite = false;
var useCCT = false;
var now = 0;
var ago = 0;
<!-- removeIf(!rfm69)-->
var packets;
var filters = [];
<!-- endRemoveIf(!rfm69)-->
<!-- removeIf(!sensor)-->
var magnitudes = [];
<!-- endRemoveIf(!sensor)-->
// -----------------------------------------------------------------------------
// Messages
// -----------------------------------------------------------------------------
function initMessages() {
messages[1] = "Remote update started";
messages[2] = "OTA update started";
messages[3] = "Error parsing data!";
messages[4] = "The file does not look like a valid configuration backup or is corrupted";
messages[5] = "Changes saved. Device will now reboot";
messages[7] = "Passwords do not match!";
messages[8] = "Changes saved";
messages[9] = "No changes detected";
messages[10] = "Session expired, please reload page...";
}
<!-- removeIf(!sensor)-->
function sensorName(id) {
var names = [
"DHT", "Dallas", "Emon Analog", "Emon ADC121", "Emon ADS1X15",
"HLW8012", "V9261F", "ECH1560", "Analog", "Digital",
"Events", "PMSX003", "BMX280", "MHZ19", "SI7021",
"SHT3X I2C", "BH1750", "PZEM004T", "AM2320 I2C", "GUVAS12SD",
"TMP3X", "Sonar", "SenseAir", "GeigerTicks", "GeigerCPM",
"NTC", "SDS011", "MICS2710", "MICS5525", "VL53L1X", "VEML6075",
"EZOPH"
];
if (1 <= id && id <= names.length) {
return names[id - 1];
}
return null;
}
function magnitudeType(type) {
var types = [
"Temperature", "Humidity", "Pressure",
"Current", "Voltage", "Active Power", "Apparent Power",
"Reactive Power", "Power Factor", "Energy", "Energy (delta)",
"Analog", "Digital", "Event",
"PM1.0", "PM2.5", "PM10", "CO2", "Lux", "UVA", "UVB", "UV Index", "Distance" , "HCHO",
"Local Dose Rate", "Local Dose Rate",
"Count",
"NO2", "CO", "Resistance", "pH"
];
if (1 <= type && type <= types.length) {
return types[type - 1];
}
return null;
}
function magnitudeError(error) {
var errors = [
"OK", "Out of Range", "Warming Up", "Timeout", "Wrong ID",
"Data Error", "I2C Error", "GPIO Error", "Calibration error"
];
if (0 <= error && error < errors.length) {
return errors[error];
}
return "Error " + error;
}
<!-- endRemoveIf(!sensor)-->
// -----------------------------------------------------------------------------
// Utils
// -----------------------------------------------------------------------------
$.fn.enterKey = function (fnc) {
return this.each(function () {
$(this).keypress(function (ev) {
var keycode = parseInt(ev.keyCode ? ev.keyCode : ev.which, 10);
if (13 === keycode) {
return fnc.call(this, ev);
}
});
});
};
function keepTime() {
$("span[name='ago']").html(ago);
ago++;
if (0 === now) { return; }
var date = new Date(now * 1000);
var text = date.toISOString().substring(0, 19).replace("T", " ");
$("input[name='now']").val(text);
$("span[name='now']").html(text);
now++;
}
function zeroPad(number, positions) {
var zeros = "";
for (var i = 0; i < positions; i++) {
zeros += "0";
}
return (zeros + number).slice(-positions);
}
function loadTimeZones() {
var time_zones = [
-720, -660, -600, -570, -540,
-480, -420, -360, -300, -240,
-210, -180, -120, -60, 0,
60, 120, 180, 210, 240,
270, 300, 330, 345, 360,
390, 420, 480, 510, 525,
540, 570, 600, 630, 660,
720, 765, 780, 840
];
for (var i in time_zones) {
var value = time_zones[i];
var offset = value >= 0 ? value : -value;
var text = "GMT" + (value >= 0 ? "+" : "-") +
zeroPad(parseInt(offset / 60, 10), 2) + ":" +
zeroPad(offset % 60, 2);
$("select[name='ntpOffset']").append(
$("<option></option>").
attr("value",value).
text(text));
}
}
function validatePassword(password) {
// http://www.the-art-of-web.com/javascript/validate-password/
// at least one lowercase and one uppercase letter or number
// at least eight characters (letters, numbers or special characters)
// MUST be 8..63 printable ASCII characters. See:
// https://en.wikipedia.org/wiki/Wi-Fi_Protected_Access#Target_users_(authentication_key_distribution)
// https://github.com/xoseperez/espurna/issues/1151
var re_password = /^(?=.*[A-Z\d])(?=.*[a-z])[\w~!@#$%^&*\(\)<>,.\?;:{}\[\]\\|]{8,63}$/;
return (
(password !== undefined)
&& (typeof password === "string")
&& (password.length > 0)
&& re_password.test(password)
);
}
function validateFormPasswords(form) {
var passwords = $("input[name='adminPass1'],input[name='adminPass2']", form);
var adminPass1 = passwords.first().val(),
adminPass2 = passwords.last().val();
var formValidity = passwords.first()[0].checkValidity();
if (formValidity && (adminPass1.length === 0) && (adminPass2.length === 0)) {
return true;
}
var validPass1 = validatePassword(adminPass1),
validPass2 = validatePassword(adminPass2);
if (formValidity && validPass1 && validPass2) {
return true;
}
if (!formValidity || (adminPass1.length > 0 && !validPass1)) {
alert("The password you have entered is not valid, it must be 8..63 characters and have at least 1 lowercase and 1 uppercase / number!");
}
if (adminPass1 !== adminPass2) {
alert("Passwords are different!");
}
return false;
}
function validateFormHostname(form) {
// RFCs mandate that a hostname's labels may contain only
// the ASCII letters 'a' through 'z' (case-insensitive),
// the digits '0' through '9', and the hyphen.
// Hostname labels cannot begin or end with a hyphen.
// No other symbols, punctuation characters, or blank spaces are permitted.
// Negative lookbehind does not work in Javascript
// var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{1,31}(?<!-)$');
var re_hostname = new RegExp('^(?!-)[A-Za-z0-9-]{0,30}[A-Za-z0-9]$');
var hostname = $("input[name='hostname']", form);
if ("true" !== hostname.attr("hasChanged")) {
return true;
}
if (re_hostname.test(hostname.val())) {
return true;
}
alert("Hostname cannot be empty and may only contain the ASCII letters ('A' through 'Z' and 'a' through 'z'), the digits '0' through '9', and the hyphen ('-')! They can neither start or end with an hyphen.");
return false;
}
function validateForm(form) {
return validateFormPasswords(form) && validateFormHostname(form);
}
function getValue(element) {
if ($(element).attr("type") === "checkbox") {
return $(element).prop("checked") ? 1 : 0;
} else if ($(element).attr("type") === "radio") {
if (!$(element).prop("checked")) {
return null;
}
}
return $(element).val();
}
function addValue(data, name, value) {
// These fields will always be a list of values
var is_group = [
"ssid", "pass", "gw", "mask", "ip", "dns",
"schEnabled", "schSwitch","schAction","schType","schHour","schMinute","schWDs","schUTC",
"relayBoot", "relayPulse", "relayTime",
"mqttGroup", "mqttGroupSync", "relayOnDisc",
"dczRelayIdx", "dczMagnitude",
"tspkRelay", "tspkMagnitude",
"ledMode", "ledRelay",
"adminPass",
"node", "key", "topic"
];
// join both adminPass 1 and 2
if (name.startsWith("adminPass")) {
name = "adminPass";
}
if (name in data) {
if (!Array.isArray(data[name])) {
data[name] = [data[name]];
}
data[name].push(value);
} else if (is_group.indexOf(name) >= 0) {
data[name] = [value];
} else {
data[name] = value;
}
}
function getData(form) {
var data = {};
// Populate data
$("input,select", form).each(function() {
var name = $(this).attr("name");
var value = getValue(this);
if (null !== value) {
addValue(data, name, value);
}
});
// Post process
addValue(data, "schSwitch", 0xFF);
delete data["filename"];
delete data["rfbcode"];
return data;
}
function randomString(length, args) {
if (typeof args === "undefined") {
args = {
lowercase: true,
uppercase: true,
numbers: true,
special: true
}
}
var mask = "";
if (args.lowercase) { mask += "abcdefghijklmnopqrstuvwxyz"; }
if (args.uppercase) { mask += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
if (args.numbers || args.hex) { mask += "0123456789"; }
if (args.hex) { mask += "ABCDEF"; }
if (args.special) { mask += "~`!@#$%^&*()_+-={}[]:\";'<>?,./|\\"; }
var source = new Uint32Array(length);
var result = new Array(length);
window.crypto.getRandomValues(source).forEach(function(value, i) {
result[i] = mask[value % mask.length];
});
return result.join("");
}
function generateAPIKey() {
var apikey = randomString(16, {hex: true});
$("input[name='apiKey']").val(apikey);
return false;
}
function generatePassword() {
var password = "";
do {
password = randomString(10);
} while (!validatePassword(password));
return password;
}
function toggleVisiblePassword() {
var elem = this.previousElementSibling;
if (elem.type === "password") {
elem.type = "text";
} else {
elem.type = "password";
}
return false;
}
function doGeneratePassword() {
$("input", $("#formPassword"))
.val(generatePassword())
.each(function() {
this.type = "text";
});
return false;
}
function getJson(str) {
try {
return JSON.parse(str);
} catch (e) {
return false;
}
}
<!-- removeIf(!thermostat)-->
function checkTempRangeMin() {
var min = parseInt($("#tempRangeMinInput").val(), 10);
var max = parseInt($("#tempRangeMaxInput").val(), 10);
if (min > max - 1) {
$("#tempRangeMinInput").val(max - 1);
}
}
function checkTempRangeMax() {
var min = parseInt($("#tempRangeMinInput").val(), 10);
var max = parseInt($("#tempRangeMaxInput").val(), 10);
if (max < min + 1) {
$("#tempRangeMaxInput").val(min + 1);
}
}
function doResetThermostatCounters(ask) {
var question = (typeof ask === "undefined" || false === ask) ?
null :
"Are you sure you want to reset burning counters?";
return doAction(question, "thermostat_reset_counters");
}
<!-- endRemoveIf(!thermostat)-->
function initGPIO(node, name, key, value) {
var template = $("#gpioConfigTemplate").children();
var line = $(template).clone();
$("span.id", line).html(value);
$("select", line).attr("name", key);
line.appendTo(node);
}
function initSelectGPIO(select) {
// TODO: cross-check used GPIOs
// TODO: support 9 & 10 with esp8285 variant
var mapping = [
[153, "NONE"],
[0, "0"],
[1, "1 (U0TXD)"],
[2, "2 (U1TXD)"],
[3, "3 (U0RXD)"],
[4, "4"],
[5, "5"],
[12, "12 (MTDI)"],
[13, "13 (MTCK)"],
[14, "14 (MTMS)"],
[15, "15 (MTDO)"],
];
for (n in mapping) {
var elem = $('<option value="' + mapping[n][0] + '">');
elem.html(mapping[n][1]);
elem.appendTo(select);
}
}
// -----------------------------------------------------------------------------
// Actions
// -----------------------------------------------------------------------------
function sendAction(action, data) {
websock.send(JSON.stringify({action: action, data: data}));
}
function sendConfig(data) {
websock.send(JSON.stringify({config: data}));
}
function setOriginalsFromValues(force) {
var force = (true === force);
$("input,select").each(function() {
var initial = (undefined === $(this).attr("original"));
if (force || initial) {
$(this).attr("original", $(this).val());
}
});
}
function resetOriginals() {
setOriginalsFromValues(true);
numReboot = numReconnect = numReload = 0;
}
function doReload(milliseconds) {
setTimeout(function() {
window.location.reload();
}, parseInt(milliseconds, 10));
}
/**
* Check a file object to see if it is a valid firmware image
* The file first byte should be 0xE9
* @param {file} file File object
* @param {Function} callback Function to call back with the result
*/
function checkFirmware(file, callback) {
var reader = new FileReader();
reader.onloadend = function(evt) {
if (FileReader.DONE === evt.target.readyState) {
if (0xE9 !== evt.target.result.charCodeAt(0)) callback(false);
if (0x03 !== evt.target.result.charCodeAt(2)) {
var response = window.confirm("Binary image is not using DOUT flash mode. This might cause resets in some devices. Press OK to continue.");
callback(response);
} else {
callback(true);
}
}
};
var blob = file.slice(0, 3);
reader.readAsBinaryString(blob);
}
function doUpgrade() {
var file = $("input[name='upgrade']")[0].files[0];
if (typeof file === "undefined") {
alert("First you have to select a file from your computer.");
return false;
}
if (file.size > free_size) {
alert("Image it too large to fit in the available space for OTA. Consider doing a two-step update.");
return false;
}
checkFirmware(file, function(ok) {
if (!ok) {
alert("The file does not seem to be a valid firmware image.");
return;
}
var data = new FormData();
data.append("upgrade", file, file.name);
$.ajax({
// Your server script to process the upload
url: urls.upgrade.href,
type: "POST",
// Form data
data: data,
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
success: function(data, text) {
$("#upgrade-progress").hide();
if ("OK" === data) {
alert("Firmware image uploaded, board rebooting. This page will be refreshed in 5 seconds.");
doReload(5000);
} else {
alert("There was an error trying to upload the new image, please try again (" + data + ").");
}
},
// Custom XMLHttpRequest
xhr: function() {
$("#upgrade-progress").show();
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
$("progress").attr({ value: e.loaded, max: e.total });
}
} , false);
}
return myXhr;
}
});
});
return false;
}
function doUpdatePassword() {
var form = $("#formPassword");
if (validateFormPasswords(form)) {
sendConfig(getData(form));
}
return false;
}
function checkChanges() {
if (numChanged > 0) {
var response = window.confirm("Some changes have not been saved yet, do you want to save them first?");
if (response) {
doUpdate();
}
}
}
function doAction(question, action) {
checkChanges();
if (question) {
var response = window.confirm(question);
if (false === response) {
return false;
}
}
sendAction(action, {});
doReload(5000);
return false;
}
function doReboot(ask) {
var question = (typeof ask === "undefined" || false === ask) ?
null :
"Are you sure you want to reboot the device?";
return doAction(question, "reboot");
}
function doReconnect(ask) {
var question = (typeof ask === "undefined" || false === ask) ?
null :
"Are you sure you want to disconnect from the current WIFI network?";
return doAction(question, "reconnect");
}
function doUpdate() {
var forms = $(".form-settings");
if (validateForm(forms)) {
// Get data
sendConfig(getData(forms));
// Empty special fields
$(".pwrExpected").val(0);
$("input[name='snsResetCalibration']").prop("checked", false);
$("input[name='pwrResetCalibration']").prop("checked", false);
$("input[name='pwrResetE']").prop("checked", false);
// Change handling
numChanged = 0;
setTimeout(function() {
var response;
if (numReboot > 0) {
response = window.confirm("You have to reboot the board for the changes to take effect, do you want to do it now?");
if (response) { doReboot(false); }
} else if (numReconnect > 0) {
response = window.confirm("You have to reconnect to the WiFi for the changes to take effect, do you want to do it now?");
if (response) { doReconnect(false); }
} else if (numReload > 0) {
response = window.confirm("You have to reload the page to see the latest changes, do you want to do it now?");
if (response) { doReload(0); }
}
resetOriginals();
}, 1000);
}
return false;
}
function doBackup() {
document.getElementById("downloader").src = urls.config.href;
return false;
}
function onFileUpload(event) {
var inputFiles = this.files;
if (typeof inputFiles === "undefined" || inputFiles.length === 0) {
return false;
}
var inputFile = inputFiles[0];
this.value = "";
var response = window.confirm("Previous settings will be overwritten. Are you sure you want to restore this settings?");
if (!response) {
return false;
}
var reader = new FileReader();
reader.onload = function(e) {
var data = getJson(e.target.result);
if (data) {
sendAction("restore", data);
} else {
window.alert(messages[4]);
}
};
reader.readAsText(inputFile);
return false;
}
function doRestore() {
if (typeof window.FileReader !== "function") {
alert("The file API isn't supported on this browser yet.");
} else {
$("#uploader").click();
}
return false;
}
function doFactoryReset() {
var response = window.confirm("Are you sure you want to restore to factory settings?");
if (response === false) {
return false;
}
sendAction("factory_reset", {});
doReload(5000);
return false;
}
function doToggle(id, value) {
sendAction("relay", {id: id, status: value ? 1 : 0 });
return false;
}
function doScan() {
$("#scanResult").html("");
$("div.scan.loading").show();
sendAction("scan", {});
return false;
}
function doHAConfig() {
$("#haConfig")
.text("")
.height(0)
.show();
sendAction("haconfig", {});
return false;
}
function doDebugCommand() {
var el = $("input[name='dbgcmd']");
var command = el.val();
el.val("");
sendAction("dbgcmd", {command: command});
return false;
}
function doDebugClear() {
$("#weblog").text("");
return false;
}
<!-- removeIf(!rfm69)-->
function doClearCounts() {
sendAction("clear-counts", {});
return false;
}
function doClearMessages() {
packets.clear().draw(false);
return false;
}
function doFilter(e) {
var index = packets.cell(this).index();
if (index == 'undefined') return;
var c = index.column;
var column = packets.column(c);
if (filters[c]) {
filters[c] = false;
column.search("");
$(column.header()).removeClass("filtered");
} else {
filters[c] = true;
var data = packets.row(this).data();
if (e.which == 1) {
column.search('^' + data[c] + '$', true, false );
} else {
column.search('^((?!(' + data[c] + ')).)*$', true, false );
}
$(column.header()).addClass("filtered");
}
column.draw();
return false;
}
function doClearFilters() {
for (var i = 0; i < packets.columns()[0].length; i++) {
if (filters[i]) {
filters[i] = false;
var column = packets.column(i);
column.search("");
$(column.header()).removeClass("filtered");
column.draw();
}
}
return false;
}
<!-- endRemoveIf(!rfm69)-->
// -----------------------------------------------------------------------------
// Visualization
// -----------------------------------------------------------------------------
function toggleMenu() {
$("#layout").toggleClass("active");
$("#menu").toggleClass("active");
$("#menuLink").toggleClass("active");
}
function showPanel() {
$(".panel").hide();
if ($("#layout").hasClass("active")) { toggleMenu(); }
$("#" + $(this).attr("data")).show();
}
// -----------------------------------------------------------------------------
// Relays & magnitudes mapping
// -----------------------------------------------------------------------------
function createRelayList(data, container, template_name) {
var current = $("#" + container + " > div").length;
if (current > 0) { return; }
var template = $("#" + template_name + " .pure-g")[0];
for (var i in data) {
var line = $(template).clone();
$("label", line).html("Switch #" + i);
$("input", line).attr("tabindex", 40 + i).val(data[i]);
line.appendTo("#" + container);
}
}
<!-- removeIf(!sensor)-->
function createMagnitudeList(data, container, template_name) {
var current = $("#" + container + " > div").length;
if (current > 0) { return; }
var template = $("#" + template_name + " .pure-g")[0];
var size = data.size;
for (var i=0; i<size; ++i) {
var line = $(template).clone();
$("label", line).html(magnitudeType(data.type[i]) + " #" + parseInt(data.index[i], 10));
$("div.hint", line).html(magnitudes[i].description);
$("input", line).attr("tabindex", 40 + i).val(data.idx[i]);
line.appendTo("#" + container);
}
}
<!-- endRemoveIf(!sensor)-->
// -----------------------------------------------------------------------------
// RFM69
// -----------------------------------------------------------------------------
<!-- removeIf(!rfm69)-->
function addMapping() {
var template = $("#nodeTemplate .pure-g")[0];
var line = $(template).clone();
var tabindex = $("#mapping > div").length * 3 + 50;
$(line).find("input").each(function() {
$(this).attr("tabindex", tabindex++);
});
$(line).find("button").on('click', delMapping);
line.appendTo("#mapping");
}
function delMapping() {
var parent = $(this).parent().parent();
$(parent).remove();
}
<!-- endRemoveIf(!rfm69)-->
// -----------------------------------------------------------------------------
// Wifi
// -----------------------------------------------------------------------------
function delNetwork() {
var parent = $(this).parents(".pure-g");
$(parent).remove();
}
function moreNetwork() {
var parent = $(this).parents(".pure-g");
$(".more", parent).toggle();
}
function addNetwork() {
var numNetworks = $("#networks > div").length;
if (numNetworks >= maxNetworks) {
alert("Max number of networks reached");
return null;
}
var tabindex = 200 + numNetworks * 10;
var template = $("#networkTemplate").children();
var line = $(template).clone();
$(line).find("input").each(function() {
$(this).attr("tabindex", tabindex);
tabindex++;
});
$(".password-reveal", line).on("click", toggleVisiblePassword);
$(line).find(".button-del-network").on("click", delNetwork);
$(line).find(".button-more-network").on("click", moreNetwork);
line.appendTo("#networks");
return line;
}
// -----------------------------------------------------------------------------
// Relays scheduler
// -----------------------------------------------------------------------------
function delSchedule() {
var parent = $(this).parents(".pure-g");
$(parent).remove();
}
function moreSchedule() {
var parent = $(this).parents(".pure-g");
$("div.more", parent).toggle();
}
function addSchedule(event) {
var numSchedules = $("#schedules > div").length;
if (numSchedules >= maxSchedules) {
alert("Max number of schedules reached");
return null;
}
var tabindex = 200 + numSchedules * 10;
var template = $("#scheduleTemplate").children();
var line = $(template).clone();
var type = (1 === event.data.schType) ? "switch" : "light";
template = $("#" + type + "ActionTemplate").children();
var actionLine = template.clone();
$(line).find("#schActionDiv").append(actionLine);
$(line).find("input").each(function() {
$(this).attr("tabindex", tabindex);
tabindex++;
});
$(line).find(".button-del-schedule").on("click", delSchedule);
$(line).find(".button-more-schedule").on("click", moreSchedule);
$(line).find("input[name='schUTC']").prop("id", "schUTC" + (numSchedules + 1))
.next().prop("for", "schUTC" + (numSchedules + 1));
$(line).find("input[name='schEnabled']").prop("id", "schEnabled" + (numSchedules + 1))
.next().prop("for", "schEnabled" + (numSchedules + 1));
line.appendTo("#schedules");
$(line).find("input[type='checkbox']").prop("checked", false);
return line;
}
// -----------------------------------------------------------------------------
// Relays
// -----------------------------------------------------------------------------
function initRelays(data) {
var current = $("#relays > div").length;
if (current > 0) { return; }
var template = $("#relayTemplate .pure-g")[0];
for (var i=0; i<data.length; i++) {
// Add relay fields
var line = $(template).clone();
$(".id", line).html(i);
$(":checkbox", line).prop('checked', data[i]).attr("data", i)
.prop("id", "relay" + i)
.on("change", function (event) {
var id = parseInt($(event.target).attr("data"), 10);
var status = $(event.target).prop("checked");
doToggle(id, status);
});
$("label.toggle", line).prop("for", "relay" + i)
line.appendTo("#relays");
// Populate the relay SELECTs
$("select.isrelay").append(
$("<option></option>").attr("value",i).text("Switch #" + i));
}
}
function updateRelays(data) {
var size = data.size;
for (var i=0; i<size; ++i) {
var elem = $("input[name='relay'][data='" + i + "']");
elem.prop("checked", data.status[i]);
elem.prop("disabled", data.lock[i] < 2); // RELAY_LOCK_DISABLED=2
}
}
function createCheckboxes() {