-
Notifications
You must be signed in to change notification settings - Fork 172
/
script.js
1609 lines (1344 loc) · 55.3 KB
/
script.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
var wsOutputQueue = [];
var wsBusy = false;
var wsOutputQueueTimer = null;
var StatusRequestTimer = null;
var FseqFileListRequestTimer = null;
var ws = null; // Web Socket
// global data
var AdminInfo = null;
var Output_Config = null; // Output Manager configuration record
var Input_Config = null; // Input Manager configuration record
var Device_Config = null;
var Network_Config = null;
var Fseq_File_List = null;
var selector = [];
var target = null;
var SdCardIsInstalled = false;
var FseqFileTransferStartTime = new Date();
// Drawing canvas - move to diagnostics
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "20px Arial";
ctx.textAlign = "center";
// Default modal properties
$.fn.modal.Constructor.DEFAULTS.backdrop = 'static';
$.fn.modal.Constructor.DEFAULTS.keyboard = false;
// lets get started
wsConnect();
wsEnqueue(JSON.stringify({ 'cmd': { 'get': 'device' } })); // Get general config
// jQuery doc ready
$(function ()
{
// Menu navigation for single page layout
$('ul.navbar-nav li a').click(function ()
{
// Highlight proper navbar item
$('.nav li').removeClass('active');
$(this).parent().addClass('active');
// Show the proper menu div
$('.mdiv').addClass('hidden');
$($(this).attr('href')).removeClass('hidden');
ProcessWindowChange($($(this))[0].hash);
// Collapse the menu on smaller screens
$('#navbar').removeClass('in').attr('aria-expanded', 'false');
$('.navbar-toggle').attr('aria-expanded', 'false');
// Firmware selection and upload
$('#efu').change(function ()
{
let file = _('efu').files[0];
let formdata = new FormData();
formdata.append("file", file);
let FileXfer = new XMLHttpRequest();
FileXfer.upload.addEventListener("progress", progressHandler, false);
FileXfer.addEventListener("load", completeHandler, false);
FileXfer.addEventListener("error", errorHandler, false);
FileXfer.addEventListener("abort", abortHandler, false);
FileXfer.open("POST", "http://" + target + "/updatefw");
FileXfer.send(formdata);
$("#EfuProgressBar").removeClass("hidden");
function _(el) {
return document.getElementById(el);
}
function progressHandler(event) {
let percent = (event.loaded / event.total) * 100;
_("EfuProgressBar").value = Math.round(percent);
}
function completeHandler(event) {
// _("status").innerHTML = event.target.responseText;
_("EfuProgressBar").value = 0; //will clear progress bar after successful upload
showReboot();
}
function errorHandler(event) {
console.error("Transfer Error");
// _("status").innerHTML = "Upload Failed";
}
function abortHandler(event) {
console.error("Transfer Abort");
// _("status").innerHTML = "Upload Aborted";
}
});
});
// DHCP field toggles
$('#network #dhcp').change(function () {
if ($(this).is(':checked')) {
$('.dhcp').removeClass('hidden');
$('.dhcp').addClass('hidden');
}
else {
$('.dhcp').removeClass('hidden');
}
$('#btn_wifi').prop("disabled", ValidateConfigFields($("#network input")));
});
$('#network').on("input", (function () {
$('#btn_wifi').prop("disabled", ValidateConfigFields($("#network input")));
}));
$('#config').on("input", (function () {
$('#DeviceConfigSave').prop("disabled", ValidateConfigFields($('#config input')));
}));
$('#DeviceConfigSave').click(function ()
{
submitDeviceConfig();
});
$('#btn_wifi').click(function () {
submitWiFiConfig();
});
$('#viewStyle').change(function () {
clearStream();
});
$('#v_columns').on('input', function () {
clearStream();
});
$('#backupconfig').click(function ()
{
ExtractNetworkConfigFromHtmlPage();
ExtractChannelConfigFromHtmlPage(Input_Config.channels, "input");
ExtractChannelConfigFromHtmlPage(Output_Config.channels, "output");
Device_Config.id = $('#config #device #id').val();
Device_Config.blanktime = $('#config #device #blanktime').val();
let TotalConfig = JSON.stringify({ 'device': Device_Config, 'network': Network_Config, 'input': Input_Config, 'output': Output_Config });
let blob = new Blob([TotalConfig], { type: "text/json;charset=utf-8" });
let FileName = Device_Config.id.replace(".", "-").replace(" ", "-").replace(",", "-") + "-" + AdminInfo.flashchipid;
saveAs(blob, FileName + ".json"); // Filesaver.js
});
$('#restoreconfig').change(function ()
{
if (this.files.length !== 0)
{
const reader = new FileReader();
reader.onload = function fileReadCompleted()
{
// when the reader is done, the content is in reader.result.
ProcessLocalConfig(reader.result);
};
reader.readAsText(this.files[0]);
}
});
$('#adminReboot').click(function () {
reboot();
});
$('#adminFactoryReset').click(function () {
factoryReset();
});
$('#AdvancedOptions').change(function () {
UpdateAdvancedOptionsMode();
});
let finalUrl = "http://" + target + "/upload";
// console.log(finalUrl);
const uploader = new Dropzone('#filemanagementupload',
{
url: finalUrl,
paramName: 'file',
maxFilesize: 1000, // MB
maxFiles: 1,
parallelUploads: 1,
clickable: true,
uploadMultiple: false,
createImageThumbnails: false,
dictDefaultMessage: 'Drag an image here to upload, or click to select one',
acceptedFiles: '.fseq,.pl',
timeout: 99999999, /*milliseconds*/
init: function ()
{
this.on('success', function (file, resp) {
// console.log("Success");
// console.log(file);
// console.log(resp);
Dropzone.forElement('#filemanagementupload').removeAllFiles(true)
RequestListOfFiles();
});
this.on('complete', function (file, resp) {
// console.log("complete");
// console.log(file);
// console.log(resp);
$('#fseqprogress_fg').addClass("hidden");
let DeltaTime = (new Date().getTime() - FseqFileTransferStartTime.getTime()) / 1000;
let rate = Math.floor((file.size / DeltaTime) / 1000);
console.debug("Final Transfer Rate: " + rate + "KBps");
});
this.on('addedfile', function (file, resp)
{
// console.log("addedfile");
// console.log(file);
// console.log(resp);
FseqFileTransferStartTime = new Date();
});
this.on('uploadprogress', function (file, percentProgress, bytesSent) {
// console.log("percentProgress: " + percentProgress);
// console.log("bytesSent: " + bytesSent);
$('#fseqprogress_fg').removeClass("hidden");
$('#fseqprogressbytes').html(bytesSent);
let now = new Date().getTime();
let DeltaTime = (now - FseqFileTransferStartTime.getTime()) / 1000;
let rate = Math.floor((bytesSent / DeltaTime)/1000);
$('#fseqprogressrate').html(rate + "KBps");
});
},
accept: function (file, done)
{
// console.log("accept");
// console.log(file);
return done(); // triggers a send
}
});
$("#filemanagementupload").addClass("dropzone");
$('#FileDeleteButton').click(function ()
{
RequestFileDeletion();
});
// Autoload tab based on URL hash
let hash = window.location.hash;
hash && $('ul.navbar-nav li a[href="' + hash + '"]').click();
// triggers menu update
RequestListOfFiles();
});
function ProcessLocalConfig(data)
{
// console.info(data);
let ParsedLocalConfig = JSON.parse(data);
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'device' : ParsedLocalConfig.device, 'network': ParsedLocalConfig.network } } }));
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'input' : { 'input_config' : ParsedLocalConfig.input } } } }));
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'output' : { 'output_config': ParsedLocalConfig.output } } } }));
} // ProcessLocalConfig
function UpdateAdvancedOptionsMode()
{
// console.info("UpdateAdvancedOptionsMode");
let am = $('#AdvancedOptions');
let AdvancedModeState = am.prop("checked");
$(".AdvancedMode").each(function ()
{
if (true === AdvancedModeState)
{
$(this).removeClass("hidden");
}
else
{
$(this).addClass("hidden");
}
});
} // UpdateAdvancedOptionsMode
function ProcessWindowChange(NextWindow) {
if (NextWindow === "#diag") {
wsEnqueue('V1');
}
else if (NextWindow === "#admin") {
wsEnqueue('XA');
}
else if ((NextWindow === "#wifi") || (NextWindow === "#home")) {
wsEnqueue(JSON.stringify({ 'cmd': { 'get': 'device' } })); // Get general config
}
else if (NextWindow === "#config") {
wsEnqueue(JSON.stringify({ 'cmd': { 'get': 'device' } })); // Get general config
wsEnqueue(JSON.stringify({ 'cmd': { 'get': 'output' } })); // Get output config
wsEnqueue(JSON.stringify({ 'cmd': { 'get': 'input' } })); // Get input config
}
else if (NextWindow === "#filemanagement") {
RequestListOfFiles();
}
UpdateAdvancedOptionsMode();
} // ProcessWindowChange
function RequestStatusUpdate()
{
// is the timer running?
if (null === StatusRequestTimer)
{
// timer runs forever
StatusRequestTimer = setTimeout(function ()
{
clearTimeout(StatusRequestTimer);
StatusRequestTimer = null;
RequestStatusUpdate();
}, 1000);
} // end timer was not running
if ($('#home').is(':visible'))
{
// ask for a status update from the server
wsEnqueue('XJ');
} // end home (aka status) is visible
} // RequestStatusUpdate
function RequestListOfFiles()
{
// is the timer running?
if (null === FseqFileListRequestTimer)
{
// timer runs until we get a response
FseqFileListRequestTimer = setTimeout(function ()
{
clearTimeout(FseqFileListRequestTimer);
FseqFileListRequestTimer = null;
RequestListOfFiles();
}, 1000);
} // end timer was not running
// ask for a file list from the server
wsEnqueue(JSON.stringify({ 'cmd': { 'get': 'files' } })); // Get File List
} // RequestListOfFiles
function ProcessGetFileListResponse(JsonConfigData)
{
// console.info("ProcessGetFileListResponse");
SdCardIsInstalled = JsonConfigData.SdCardPresent;
$("#li-filemanagement").removeClass("hidden");
if (false === SdCardIsInstalled)
{
$("#li-filemanagement").addClass("hidden");
}
Fseq_File_List = JsonConfigData;
clearTimeout(FseqFileListRequestTimer);
FseqFileListRequestTimer = null;
// console.info("$('#FileManagementTable > tr').length " + $('#FileManagementTable > tr').length);
while (1 < $('#FileManagementTable > tr').length)
{
// console.info("Deleting $('#FileManagementTable tr').length " + $('#FileManagementTable tr').length);
$('#FileManagementTable tr').last().remove();
// console.log("After Delete: $('#FileManagementTable tr').length " + $('#FileManagementTable tr').length);
}
let CurrentRowId = 0;
JsonConfigData.files.forEach(function (file)
{
let SelectedPattern = '<td><input type="checkbox" id="FileSelected_' + (CurrentRowId) + '"></td>';
let NamePattern = '<td><output type="text" id="FileName_' + (CurrentRowId) + '"></td>';
let DatePattern = '<td><output type="text" id="FileDate_' + (CurrentRowId) + '"></td>';
let SizePattern = '<td><output type="text" id="FileSize_' + (CurrentRowId) + '"></td>';
let rowPattern = '<tr>' + SelectedPattern + NamePattern + DatePattern + SizePattern + '</tr>';
$('#FileManagementTable tr:last').after(rowPattern);
$('#FileName_' + (CurrentRowId)).val(file.name);
$('#FileDate_' + (CurrentRowId)).val(new Date(file.date * 1000).toISOString());
$('#FileSize_' + (CurrentRowId)).val(file.length);
CurrentRowId++;
});
} // ProcessGetFileListResponse
function RequestFileDeletion()
{
let files = [];
$('#FileManagementTable > tr').each(function (CurRowId)
{
if (true === $('#FileSelected_' + CurRowId).prop("checked"))
{
let FileEntry = {};
FileEntry["name"] = $('#FileName_' + CurRowId).val().toString();
files.push(FileEntry);
}
});
wsEnqueue(JSON.stringify({ 'cmd': { 'delete': { 'files': files } } }));
RequestListOfFiles();
} // RequestFileDeletion
function ParseParameter(name)
{
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
function ProcessModeConfigurationDatafppremote(channelConfig)
{
let jqSelector = "#fseqfilename";
// remove the existing options
$(jqSelector).empty();
$(jqSelector).append('<option value="...">Play Remote Sequence</option>');
// for each file in the list
Fseq_File_List.files.forEach(function (listEntry) {
// add in a new entry
$(jqSelector).append('<option value="' + listEntry.name + '">' + listEntry.name + '</option>');
});
// set the current selector value
$(jqSelector).val(channelConfig.fseqfilename);
} // ProcessModeConfigurationDatafppremote
function ProcessModeConfigurationDataEffects(channelConfig)
{
let jqSelector = "#currenteffect";
// remove the existing options
$(jqSelector).empty();
// for each option in the list
channelConfig.effects.forEach(function (listEntry) {
// add in a new entry
$(jqSelector).append('<option value="' + listEntry.name + '">' + listEntry.name + '</option>');
});
// set the current selector value
$(jqSelector).val(channelConfig.currenteffect);
} // ProcessModeConfigurationDataEffects
function ProcessModeConfigurationDataRelay(RelayConfig)
{
// console.log("relaychannelconfigurationtable.rows.length = " + $('#relaychannelconfigurationtable tr').length);
let ChannelConfigs = RelayConfig.channels;
// add as many rows as we need
for (let CurrentRowId = 1; CurrentRowId <= ChannelConfigs.length; CurrentRowId++)
{
// console.log("CurrentRowId = " + CurrentRowId);
let ChanIdPattern = '<td id="chanId_' + (CurrentRowId) + '">a</td>';
let EnabledPattern = '<td><input type="checkbox" id="Enabled_' + (CurrentRowId) + '"></td>';
let InvertedPattern = '<td><input type="checkbox" id="Inverted_' + (CurrentRowId) + '"></td>';
let gpioPattern = '<td><input type="number" id="gpioId_' + (CurrentRowId) + '"step="1" min="0" max="24" value="30" class="form-control is-valid"></td>';
let threshholdPattern = '<td><input type="number" id="threshhold_' + (CurrentRowId) + '"step="1" min="0" max="255" value="300" class="form-control is-valid"></td>';
let rowPattern = '<tr>' + ChanIdPattern + EnabledPattern + InvertedPattern + gpioPattern + threshholdPattern + '</tr>';
$('#relaychannelconfigurationtable tr:last').after(rowPattern);
$('#chanId_' + CurrentRowId).attr('style', $('#chanId_hr').attr('style'));
$('#Enabled_' + CurrentRowId).attr('style', $('#Enabled_hr').attr('style'));
$('#Inverted_' + CurrentRowId).attr('style', $('#Inverted_hr').attr('style'));
$('#gpioId_' + CurrentRowId).attr('style', $('#gpioId_hr').attr('style'));
$('#threshhold_' + CurrentRowId).attr('style', $('#threshhold_hr').attr('style'));
}
$.each(ChannelConfigs, function (i, CurrentChannelConfig)
{
// console.log("Current Channel Id = " + CurrentChannelConfig.id);
let currentChannelRowId = CurrentChannelConfig.id + 1;
$('#chanId_' + (currentChannelRowId)).html(currentChannelRowId);
$('#Enabled_' + (currentChannelRowId)).prop("checked", CurrentChannelConfig.en);
$('#Inverted_' + (currentChannelRowId)).prop("checked", CurrentChannelConfig.inv);
$('#gpioId_' + (currentChannelRowId)).val(CurrentChannelConfig.gid);
$('#threshhold_' + (currentChannelRowId)).val(CurrentChannelConfig.trig);
});
} // ProcessModeConfigurationDataRelay
function ProcessModeConfigurationDataServoPCA9685(ServoConfig)
{
// console.log("Servochannelconfigurationtable.rows.length = " + $('#servo_pca9685channelconfigurationtable tr').length);
let ChannelConfigs = ServoConfig.channels;
// add as many rows as we need
for (let CurrentRowId = 1; CurrentRowId <= ChannelConfigs.length; CurrentRowId++) {
// console.log("CurrentRowId = " + CurrentRowId);
let ChanIdPattern = '<td id="ServoChanId_' + (CurrentRowId) + '">a</td>';
let EnabledPattern = '<td><input type="checkbox" id="ServoEnabled_' + (CurrentRowId) + '"></td>';
let MinLevelPattern = '<td><input type="number" id="ServoMinLevel_' + (CurrentRowId) + '"step="1" min="10" max="4095" value="0" class="form-control is-valid"></td>';
let MaxLevelPattern = '<td><input type="number" id="ServoMaxLevel_' + (CurrentRowId) + '"step="1" min="10" max="4095" value="0" class="form-control is-valid"></td>';
let DataType = '<td><select class="form-control is-valid" id="ServoDataType_' + (CurrentRowId) + '" title="Effect to generate"></select></td>';
let rowPattern = '<tr>' + ChanIdPattern + EnabledPattern + MinLevelPattern + MaxLevelPattern + DataType + '</tr>';
$('#servo_pca9685channelconfigurationtable tr:last').after(rowPattern);
$('#ServoChanId_' + CurrentRowId).attr('style', $('#ServoChanId_hr').attr('style'));
$('#ServoEnabled_' + CurrentRowId).attr('style', $('#ServoEnabled_hr').attr('style'));
$('#ServoMinLevel_' + CurrentRowId).attr('style', $('#ServoMinLevel_hr').attr('style'));
$('#ServoMaxLevel_' + CurrentRowId).attr('style', $('#ServoMaxLevel_hr').attr('style'));
$('#ServoDataType_' + CurrentRowId).attr('style', $('#ServoDataType_hr').attr('style'));
}
$.each(ChannelConfigs, function (i, CurrentChannelConfig) {
// console.log("Current Channel Id = " + CurrentChannelConfig.id);
let currentChannelRowId = CurrentChannelConfig.id + 1;
$('#ServoChanId_' + (currentChannelRowId)).html(currentChannelRowId);
$('#ServoEnabled_' + (currentChannelRowId)).prop("checked", CurrentChannelConfig.en);
$('#ServoMinLevel_' + (currentChannelRowId)).val(CurrentChannelConfig.Min);
$('#ServoMaxLevel_' + (currentChannelRowId)).val(CurrentChannelConfig.Max);
let jqSelector = "#ServoDataType_" + (currentChannelRowId);
// remove the existing options
$(jqSelector).empty();
$(jqSelector).append('<option value=0> 8 Bit Absolute</option>');
$(jqSelector).append('<option value=1> 8 Bit Absolute Reversed</option>');
$(jqSelector).append('<option value=2> 8 Bit Scaled</option>');
$(jqSelector).append('<option value=3> 8 Bit Scaled - Reversed</option>');
$(jqSelector).append('<option value=4>16 Bit Absolute</option>');
$(jqSelector).append('<option value=5>16 Bit Absolute - Reversed</option>');
$(jqSelector).append('<option value=6>16 Bit Scaled</option>');
$(jqSelector).append('<option value=7>16 Bit Scaled - Reversed</option>');
// set the current selector value
$(jqSelector).val((CurrentChannelConfig.rev << 0) +
(CurrentChannelConfig.sca << 1) +
(CurrentChannelConfig.b16 << 2) );
});
} // ProcessModeConfigurationDataServoPCA9685
function ProcessInputConfig()
{
$("#ecb_enable").prop("checked", Input_Config.ecb.enabled);
$("#ecb_gpioid").val(Input_Config.ecb.id);
$("#ecb_polarity").val(Input_Config.ecb.polarity);
} // ProcessInputConfig
function ProcessModeConfigurationData(channelId, ChannelType, JsonConfig )
{
// console.info("ProcessModeConfigurationData: Start");
// determine the type of in/output that has been selected and populate the form
let TypeOfChannelId = parseInt($('#' + ChannelType + channelId + " option:selected").val(), 10);
let channelConfigSet = JsonConfig.channels[channelId];
if (isNaN(TypeOfChannelId))
{
// use the value we got from the controller
TypeOfChannelId = channelConfigSet.type;
}
let channelConfig = channelConfigSet[TypeOfChannelId];
let ChannelTypeName = channelConfig.type.toLowerCase();
ChannelTypeName = ChannelTypeName.replace(".", "_");
ChannelTypeName = ChannelTypeName.replace(" ", "_");
// console.info("ChannelTypeName: " + ChannelTypeName);
let elementids = [];
let modeControlName = '#' + ChannelType + 'mode' + channelId;
// console.info("modeControlName: " + modeControlName);
// modify page title
//TODO: Dirty hack to clean-up input names
if (ChannelType !== 'input') {
let ModeDisplayName = GenerateInputOutputControlLabel(ChannelType, channelId) + " - " + $(modeControlName + ' #Title')[0].innerHTML;
// console.info("ModeDisplayName: " + ModeDisplayName);
$(modeControlName + ' #Title')[0].innerHTML = ModeDisplayName;
}
//document.getElementById("blahblah").innerHTML="NewText".
elementids = $(modeControlName + ' *[id]').filter(":input").map(function ()
{
return $(this).attr('id');
}).get();
elementids.forEach(function (elementid)
{
let SelectedElement = modeControlName + ' #' + elementid;
if ($(SelectedElement).is(':checkbox'))
{
$(SelectedElement).prop('checked', channelConfig[elementid]);
}
else
{
$(SelectedElement).val(channelConfig[elementid]);
}
});
if ("fpp_remote" === ChannelTypeName)
{
if (null !== Fseq_File_List)
{
ProcessModeConfigurationDatafppremote(channelConfig);
}
}
else if ("effects" === ChannelTypeName)
{
ProcessModeConfigurationDataEffects(channelConfig);
}
else if ("relay" === ChannelTypeName)
{
// console.info("ProcessModeConfigurationData: relay");
ProcessModeConfigurationDataRelay(channelConfig);
}
else if ("servo_pca9685" === ChannelTypeName)
{
// console.info("ProcessModeConfigurationData: servo");
ProcessModeConfigurationDataServoPCA9685(channelConfig);
}
UpdateAdvancedOptionsMode();
// console.info("ProcessModeConfigurationData: End");
} // ProcessModeConfigurationData
function ProcessReceivedJsonConfigMessage(JsonConfigData)
{
// console.info("ProcessReceivedJsonConfigMessage: Start");
// is this an output config?
if ({}.hasOwnProperty.call(JsonConfigData, "output_config"))
{
// save the config for later use.
Output_Config = JsonConfigData.output_config;
CreateOptionsFromConfig("output", Output_Config);
}
// is this an input config?
else if ({}.hasOwnProperty.call(JsonConfigData, "input_config"))
{
// save the config for later use.
Input_Config = JsonConfigData.input_config;
CreateOptionsFromConfig("input", Input_Config);
}
// is this a device config?
else if ({}.hasOwnProperty.call(JsonConfigData, "device"))
{
// console.info("Got Device Config");
Device_Config = JsonConfigData.device;
updateFromJSON(JsonConfigData);
// is this a network config?
if ({}.hasOwnProperty.call(JsonConfigData, "network")) {
Network_Config = JsonConfigData.network;
updateFromJSON(JsonConfigData);
}
}
// is this a file list?
else if ({}.hasOwnProperty.call(JsonConfigData, "files"))
{
ProcessGetFileListResponse(JsonConfigData);
}
// is this an ACK response?
else if ({}.hasOwnProperty.call(JsonConfigData, "OK"))
{
// console.info("Received Acknowledgement to config set command.")
}
else
{
console.error("unknown configuration record type has been ignored.")
}
// console.info("ProcessReceivedJsonConfigMessage: Done");
} // ProcessReceivedJsonConfigMessage
// Builds jQuery selectors from JSON data and updates the web interface
function updateFromJSON(obj)
{
for (let k in obj)
{
selector.push('#' + k);
if (typeof obj[k] === 'object' && obj[k] !== null)
{
updateFromJSON(obj[k]);
}
else
{
let jqSelector = selector.join(' ');
if (typeof obj[k] === 'boolean')
{
$(jqSelector).prop('checked', obj[k]);
}
else
{
$(jqSelector).val(obj[k]);
}
// Trigger keyup / change events
$(jqSelector).trigger('keyup');
$(jqSelector).trigger('change');
}
selector.pop();
}
// Update Device ID in footer
$('#device-id').text($('#config #id').val());
}
function GenerateInputOutputControlLabel(OptionListName, DisplayedChannelId)
{
let Id = parseInt(DisplayedChannelId) + 1;
let NewName = '';
//TODO: Dirty Hack to clean-up Input lables
if (OptionListName === `input`) {
NewName = (Id === 1) ? 'Primary Input' : 'Secondary Input'
} else {
NewName = OptionListName.charAt(0).toUpperCase() + OptionListName.slice(1) + " " + Id;
}
// console.log(`IO Label: ${NewName}`)
return NewName;
} // GenerateInputOutputControlLabel
function LoadDeviceSetupSelectedOption(OptionListName, DisplayedChannelId )
{
// console.info("OptionListName: " + OptionListName);
// console.info("DisplayedChannelId: " + DisplayedChannelId);
let HtmlLoadFileName = $('#' + OptionListName + DisplayedChannelId + ' option:selected').text().toLowerCase();
// console.info("Base HtmlLoadFileName: " + HtmlLoadFileName);
HtmlLoadFileName = HtmlLoadFileName.replace(".", "_");
HtmlLoadFileName = HtmlLoadFileName.replace(" ", "_");
HtmlLoadFileName = HtmlLoadFileName + ".html";
// console.info("Adjusted HtmlLoadFileName: " + HtmlLoadFileName);
//TODO: Detect modules that don't require configuration - DDP, Alexa, ?
if ("disabled.html" === HtmlLoadFileName)
{
$('#' + OptionListName + 'mode' + DisplayedChannelId).empty();
}
else
{
// try to load the field definition file for this channel type
$('#' + OptionListName + 'mode' + DisplayedChannelId).load(HtmlLoadFileName, function ()
{
if ("input" === OptionListName)
{
ProcessInputConfig();
ProcessModeConfigurationData(DisplayedChannelId, OptionListName, Input_Config);
}
else if ("output" === OptionListName)
{
ProcessModeConfigurationData(DisplayedChannelId, OptionListName, Output_Config);
}
});
}
} // LoadDeviceSetupSelectedOption
function CreateOptionsFromConfig(OptionListName, Config)
{
// console.info("CreateOptionsFromConfig");
// Set selection column width based on arch which equates to number of outputs for now
let col = (AdminInfo.arch === 'ESP8266') ? '4' : '2';
let Channels = Config.channels;
if ("input" === OptionListName)
{
$('#ecpin').val(Config.ecpin);
}
// for each field we need to populate (input vs output)
Object.keys(Channels).forEach(function (ChannelId)
{
// OptionListName is 'input' or 'output'
// console.info("ChannelId: " + ChannelId);
let CurrentChannel = Channels[ChannelId];
// does the selection box we need already exist?
if (!$('#' + OptionListName + 'mode' + ChannelId).length)
{
// console.log(`OptionListName: ${OptionListName}`)
// create the selection box
$(`#fg_${OptionListName}`).append(`<label class="control-label col-sm-2" for="${OptionListName}${ChannelId}">${GenerateInputOutputControlLabel(OptionListName, ChannelId)}</label>`);
$(`#fg_${OptionListName}`).append(`<div class="col-sm-${col}"><select class="form-control wsopt" id="${OptionListName}${ChannelId}"></select></div>`);
$(`#fg_${OptionListName}_mode`).append(`<fieldset id="${OptionListName}mode${ChannelId}"></fieldset>`);
}
let jqSelector = "#" + OptionListName + ChannelId;
// remove the existing options
$(jqSelector).empty();
// for each Channel type in the list
Object.keys(CurrentChannel).forEach(function (SelectionTypeId)
{
// console.info("SelectionId: " + SelectionTypeId);
if ("type" === SelectionTypeId)
{
// console.info("Set the selector type to: " + CurrentChannel.type);
$(jqSelector).val(CurrentChannel.type);
LoadDeviceSetupSelectedOption(OptionListName, ChannelId);
$(jqSelector).change(function ()
{
// console.info("Set the selector type to: " + CurrentChannel.type);
LoadDeviceSetupSelectedOption(OptionListName, ChannelId);
});
}
else
{
let CurrentSection = CurrentChannel[SelectionTypeId];
// console.info("Add '" + CurrentSection.type + "' to selector");
$(jqSelector).append('<option value="' + SelectionTypeId + '">' + CurrentSection.type + '</option>');
}
}); // end for each selection type
}); // end for each channel
} // CreateOptionsFromConfig
// Builds JSON config submission for "WiFi" tab
function ExtractNetworkConfigFromHtmlPage()
{
Network_Config.ssid = $('#ssid').val();
Network_Config.passphrase = $('#passphrase').val();
Network_Config.hostname = $('#hostname').val();
Network_Config.sta_timeout = $('#sta_timeout').val();
Network_Config.ip = $('#ip').val();
Network_Config.netmask = $('#netmask').val();
Network_Config.gateway = $('#gateway').val();
Network_Config.dhcp = $('#dhcp').prop('checked');
Network_Config.ap_fallback = $('#ap_fallback').prop('checked');
Network_Config.ap_reboot = $('#ap_reboot').prop('checked');
Network_Config.ap_timeout = $('#apt').prop('checked');
} // ExtractNetworkConfigFromHtmlPage
// Builds JSON config submission for "WiFi" tab
function submitWiFiConfig() {
ExtractNetworkConfigFromHtmlPage();
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'device': Device_Config, 'network': Network_Config } } }));
} // submitWiFiConfig
function ExtractChannelConfigFromHtmlPage(JsonConfig, SectionName)
{
// for each option channel:
jQuery.each(JsonConfig, function (DisplayedChannelId, CurrentChannelConfigurationData)
{
let elementids = [];
let modeControlName = '#' + SectionName + 'mode' + DisplayedChannelId;
elementids = $(modeControlName + ' *[id]').filter(":input").map(function ()
{
return $(this).attr('id');
}).get();
let ChannelType = parseInt($("#" + SectionName + DisplayedChannelId + " option:selected").val(), 10);
let ChannelConfig = CurrentChannelConfigurationData[ChannelType];
// tell the ESP what type of channel it should be using
CurrentChannelConfigurationData.type = ChannelType;
if ((ChannelConfig.type === "Relay") && ($("#relaychannelconfigurationtable").length))
{
ChannelConfig.updateinterval = parseInt($('#updateinterval').val(), 10);
$.each(ChannelConfig.channels, function (i, CurrentChannelConfig) {
// console.info("Current Channel Id = " + CurrentChannelConfig.id);
let currentChannelRowId = CurrentChannelConfig.id + 1;
CurrentChannelConfig.en = $('#Enabled_' + (currentChannelRowId)).prop("checked");
CurrentChannelConfig.inv = $('#Inverted_' + (currentChannelRowId)).prop("checked");
CurrentChannelConfig.gid = parseInt($('#gpioId_' + (currentChannelRowId)).val(), 10);
CurrentChannelConfig.trig = parseInt($('#threshhold_' + (currentChannelRowId)).val(), 10);
});
}
else if ((ChannelConfig.type === "Servo PCA9685") && ($("#servo_pca9685channelconfigurationtable").length))
{
ChannelConfig.updateinterval = parseInt($('#updateinterval').val(), 10);
$.each(ChannelConfig.channels, function (i, CurrentChannelConfig) {
// console.info("Current Channel Id = " + CurrentChannelConfig.id);
let currentChannelRowId = CurrentChannelConfig.id + 1;
CurrentChannelConfig.en = $('#ServoEnabled_' + (currentChannelRowId)).prop("checked");
CurrentChannelConfig.Min = parseInt($('#ServoMinLevel_' + (currentChannelRowId)).val(), 10);
CurrentChannelConfig.Max = parseInt($('#ServoMaxLevel_' + (currentChannelRowId)).val(), 10);
let ServoDataType = parseInt($('#ServoDataType_' + (currentChannelRowId)).val(), 10);
CurrentChannelConfig.rev = (ServoDataType & 0x01) ? true : false;
CurrentChannelConfig.sca = (ServoDataType & 0x02) ? true : false;
CurrentChannelConfig.b16 = (ServoDataType & 0x04) ? true : false;
});
}
else
{
elementids.forEach(function (elementid) {
let SelectedElement = modeControlName + ' #' + elementid;
if ($(SelectedElement).is(':checkbox')) {
ChannelConfig[elementid] = $(SelectedElement).prop('checked');
}
else {
ChannelConfig[elementid] = $(SelectedElement).val();
}
});
}
}); // end for each channel
} // ExtractChannelConfigFromHtmlPage
function ValidateConfigFields(ElementList)
{
// return true if errors were found
let response = false;
for (let ChildElementId = 0;
ChildElementId < ElementList.length;
ChildElementId++)
{
let ChildElement = ElementList[ChildElementId];
// let ChildType = ChildElement.type;
if ((ChildElement.validity.valid !== undefined) && (!$(ChildElement).hasClass('hidden')))
{
// console.info("ChildElement.validity.valid: " + ChildElement.validity.valid);
if (false === ChildElement.validity.valid)
{
// console.info(" Element: " + ChildElement.id);
// console.info(" ChildElementId: " + ChildElementId);
// console.info("ChildElement Type: " + ChildType);
response = true;
}
}
}
return response;
} // ValidateConfigFields
// Build dynamic JSON config submission for "Device" tab
function submitDeviceConfig()
{
ExtractChannelConfigFromHtmlPage(Input_Config.channels, "input");
Input_Config.ecb.enabled = $("#ecb_enable").is(':checked');
Input_Config.ecb.id = $("#ecb_gpioid").val();
Input_Config.ecb.polarity = $("#ecb_polarity").val();
ExtractChannelConfigFromHtmlPage(Output_Config.channels, "output");
Device_Config.id = $('#config #device #id').val();
Device_Config.blanktime = $('#config #device #blanktime').val();
Device_Config.miso_pin = $('#config #device #miso_pin').val();
Device_Config.mosi_pin = $('#config #device #mosi_pin').val();
Device_Config.clock_pin = $('#config #device #clock_pin').val();
Device_Config.cs_pin = $('#config #device #cs_pin').val();
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'device': Device_Config, 'network': Network_Config } } }));
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'input': { 'input_config': Input_Config } } } }));
wsEnqueue(JSON.stringify({ 'cmd': { 'set': { 'output': { 'output_config': Output_Config } } } }));
} // submitDeviceConfig
function convertUTCDateToLocalDate(date)
{
date = new Date(date);
let localOffset = date.getTimezoneOffset() * 60000;
let localTime = date.getTime();
date = localTime - localOffset;
return date;
} // convertUTCDateToLocalDate
function int2ip(num)
{
let d = num % 256;
for (let i = 3; i > 0; i--)
{