-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.js
More file actions
2148 lines (1895 loc) · 82.1 KB
/
functions.js
File metadata and controls
2148 lines (1895 loc) · 82.1 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
let settingsData = null;
let settingsMap = new Map(); // maps int ID -> [key, meta]
let settingsMeta = null;
const intervalPatterns = [
/^(?!.*advertisement).*_interval(?:_\d+|\d+)?$/, // matches _interval, _interval1, _interval2, _interval_2, etc., but not _advertisement_interval
/^rf_scan_duration$/,
/^(cold|hot)_fix_timeout$/,
/^ublox_min_fix_time$/,
/^cmdq_on_no_detection_wait_duration$/,
/^fence_sampling_length$/
];
const intervalPatternExclusions = new Set([
'satellite_max_messages_per_interval',
'gps_motion_triggered_min_num_of_triggers_per_interval',
'gps_skipped_triggered_interval'
]);
function isIntervalSetting(key) {
return !intervalPatternExclusions.has(key) && intervalPatterns.some(rx => rx.test(key));
}
const grouping = {
"^(hot|cold)_": "satellite",
"^sat_send_flag$": "satellite",
"^rejoin_interval$": "lr",
"^app_(key|eui)$": "lr",
"^device_eui$": "lr",
"^horizontal_accuracy$": "ublox",
"^motion_ths$": "gps",
"^enable_motion_trig_gps$": "gps",
"^rf_open_sky_detection": 0,
"^rf_scan": 0,
"(^.{2,}?)_": 1
};
const bitmapSettings = [/^.*_flag$/];
const customBitmaskRenderers = {
gps_open_sky_detection_bitmask: renderOpenSkyDetectionBitmask
};
const skipPorts = ['port_lr_messaging', 'port_flash_log', 'port_values', 'port_messages', 'port_commands'];
const customByteArrayRenderers = {
lp0_communication_params: renderLp0CommunicationParams,
lp0_node_params: renderLp0NodeParams,
outdoor_detection_parameters: renderOutdoorDetectionParameters,
cmdq_searched_mac_address: renderMacAddressParameters
};
const customInputRenderers = {
ble_advertisement_interval: renderMsInput,
ble_auto_disconnect: renderMsInput,
ble_scan_duration: renderMsInput,
ble_scan_manufacturer_id: renderHexUint16Input,
cmdq_scan_duration: renderMsInput,
device_pin: renderDevicePinInput,
external_switch_detection_trigger_debounce_ms: renderMsInput,
gps_init_lat: renderLatitudeInput,
gps_init_lon: renderLongitudeInput,
ublox_interval1_start: renderUtcHourInput,
ublox_interval2_start: renderUtcHourInput,
satellite_interval1_start: renderUtcHourInput,
satellite_send_interval2_start: renderUtcHourInput,
vhf_interval1_start: renderUtcHourInput,
vhf_interval2_start: renderUtcHourInput,
vhf_time_between_packets_ms: renderMsInput,
init_time: renderUnixTimeInput
};
// Static list of settings files
const SETTINGS_FILES = [
"settings-v7.2.0.json",
"settings-v7.1.0.json",
"settings_v7.0.0.json",
"settings-v5.0.1.json",
"settings-v6.15.0.json",
"settings-v6.14.1.json",
"settings-v6.12.1.json",
"settings-v6.11.0.json",
"settings-v6.10.0.json",
"settings-v6.9.0.json",
"settings-v6.8.1.json",
"settings-v4.4.2.json"
];
const SETTINGS_META_FILE = "settings-meta.json";
const APP_VERSION_FILE = "version.json";
window.SETTINGS_FILES = SETTINGS_FILES;
const dangerousCommands = [/_th$/, /set_hibernation_mode/, /almanac_update/];
function formatBuildTime(buildTime) {
if (!buildTime) {
return '';
}
const parsed = new Date(buildTime);
if (Number.isNaN(parsed.getTime())) {
return '';
}
return parsed.toISOString().slice(0, 10);
}
async function updateAppVersionBadge() {
const versionElement = document.getElementById('app-version');
if (!versionElement) {
return;
}
try {
const response = await fetch(APP_VERSION_FILE, { cache: 'no-store' });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const versionInfo = await response.json();
const version = versionInfo.version || 'unknown';
const commit = versionInfo.commit ? ` (${String(versionInfo.commit).slice(0, 7)})` : '';
const buildDate = formatBuildTime(versionInfo.built_at);
versionElement.textContent = `Version: ${version}${commit}${buildDate ? ` - ${buildDate}` : ''}`;
} catch (error) {
versionElement.textContent = 'Version: unavailable';
console.warn('Failed to load app version:', error);
}
}
document.addEventListener('DOMContentLoaded', () => {
updateAppVersionBadge();
});
const minMaxValues = {
'uint8': { min: 0, max: 255 },
'uint16': { min: 0, max: 65535 },
'uint32': { min: 0, max: 4294967295 },
'int8': { min: -128, max: 127 },
'int32': { min: -2147483648, max: 2147483647 },
'float': { min: -3.4e38, max: 3.4e38 }
}
function populateSettingsIntoPage(firstItem = null) {
const dropdown = document.getElementById('settings-dropdown');
dropdown.innerHTML = ''; // Clear previous options
if (firstItem) {
const option = document.createElement('option');
option.value = "";
option.textContent = firstItem;
dropdown.appendChild(option);
}
SETTINGS_FILES.forEach(file => {
const option = document.createElement('option');
option.value = `./settings/${file}`;
option.textContent = file;
dropdown.appendChild(option);
});
}
async function loadSettingsMeta() {
if (settingsMeta) {
return;
}
try {
const response = await fetch(SETTINGS_META_FILE);
settingsMeta = await response.json();
} catch (error) {
console.warn('Failed to load settings metadata:', error);
settingsMeta = { settings: {}, commands: {} };
}
}
async function loadSettings(selectedFile) {
settingsData = null;
settingsMap = new Map();
try {
await loadSettingsMeta();
const response = await fetch(selectedFile);
settingsData = await response.json();
settingsMap = new Map();
registerValues(settingsData.settings, "setting");
registerValues(settingsData.commands, "command");
registerValues(settingsData.values, "value");
} catch (error) {
throw new Error(`Error loading settings: ${error.message}`);
}
}
function __onInputChanged(settingId) {
const [key, setting] = getById(settingId);
const value = getInputValue(setting.id);
const errorElement = document.getElementById(`input-error-${setting.id}`);
const rawValueElement = document.getElementById(`raw-value-${setting.id}`);
let valid = true;
try {
validateInput(key, setting, value);
errorElement.innerText = '';
} catch (error) {
valid = false;
errorElement.innerText = error.message;
}
if (rawValueElement) {
rawValueElement.value = value ?? '';
}
if (typeof (onInputChanged) === typeof (Function)) {
onInputChanged(setting, value, valid);
}
if (typeof window.handleSettingInputChange === 'function') {
window.handleSettingInputChange(setting.id, value, valid, key, setting);
}
refreshDynamicSettingHelpers(key);
}
function setInputValue(settingId, value) {
const [key, setting] = getById(settingId);
document.getElementById(`input-container-${settingId}`).innerHTML = sanitizeRenderedInputHtml(renderInputControl(
key,
setting,
normalizeRenderableValue(value)
));
refreshDynamicSettingHelpers(key);
}
function clearInputValue(settingId) {
const [key] = getById(settingId);
const container = document.getElementById(`input-container-${settingId}`);
if (!container) {
return;
}
container.innerHTML = '';
refreshDynamicSettingHelpers(key);
}
function setDefaultValue(settingId) {
const [key, setting] = getById(settingId);
const container = document.getElementById(`input-container-${settingId}`);
if (!container) {
return;
}
container.innerHTML = sanitizeRenderedInputHtml(
renderInputControl(key, setting, normalizeRenderableValue(setting.default))
);
refreshDynamicSettingHelpers(key);
}
function getInputValue(settingId) {
const el = document.getElementById(`new-value-${settingId}`);
if (el) {
return el.value.trim();
}
}
function filterSettings() {
const query = document.getElementById('settings-search').value.toLowerCase();
const showNonDefaultOnly = document.getElementById('non-default-checkbox') ? document.getElementById('non-default-checkbox').checked : false;
const settingsSection = document.getElementById('settings-section');
const groups = settingsSection.querySelectorAll('.settings-group');
groups.forEach(group => {
const settingsContainer = group.querySelector('.settings-container');
const groupToggle = group.querySelector('.group-toggle');
let hasVisibleSettings = false;
const settings = settingsContainer ? settingsContainer.querySelectorAll('.setting') : [];
settings.forEach(setting => {
const dataSearch = setting.getAttribute('data-search') || setting.querySelector('h4').textContent;
const matchesSearch = dataSearch.toLowerCase().includes(query);
const isNonDefault = setting.classList.contains('value-not-default');
const shouldShow = matchesSearch && (!showNonDefaultOnly || isNonDefault);
if (shouldShow) {
setting.classList.remove('hidden');
hasVisibleSettings = true;
} else {
setting.classList.add('hidden');
}
});
if (hasVisibleSettings) {
group.classList.remove('hidden');
if (query || showNonDefaultOnly) {
group.classList.remove('is-collapsed');
if (groupToggle) {
groupToggle.setAttribute('aria-expanded', 'true');
}
}
} else {
group.classList.add('hidden');
}
});
}
function toggleGroup(group) {
const isCollapsed = group.classList.toggle('is-collapsed');
const groupToggle = group.querySelector('.group-toggle');
if (groupToggle) {
groupToggle.setAttribute('aria-expanded', (!isCollapsed).toString());
}
}
function registerValues(data, type) {
for (const [key, value] of Object.entries(data)) {
// key is the string name of the setting
// value includes: id, default, min, max, conversion, etc.
value["type"] = type;
settingsMap.set(parseInt(value.id, 16), [key, value]);
}
}
function getByKey(key) {
return settingsData.settings[key];
}
function getById(id) {
if (typeof id === 'string' || id instanceof String) {
id = parseInt(id, 16);
}
if (!settingsMap.has(id)) {
throw new Error(`Value with ID ${toHex(id)} not found`);
}
return settingsMap.get(id);
}
function isBitmaskSetting(key) {
return bitmapSettings.some(rx => rx.test(key)) || key in customBitmaskRenderers;
}
function convertUnitToSeconds(value, unit) {
return value * parseInt(unit, 10);
}
function convertSecondsToUnit(valueInSeconds, unit) {
return valueInSeconds / parseInt(unit);
}
function stripBytes(s) {
return s.replace(/0x/g, '').replace(/[^0-9A-Fa-f]/g, '').toUpperCase();
}
function normalizeMacAddressInput(value) {
return String(value || '')
.trim()
.replace(/[^0-9A-Fa-f]/g, '')
.toUpperCase()
.slice(0, 12);
}
function formatMacAddressForDisplay(value, expectedLength = 6) {
const hex = normalizeMacAddressInput(value);
const requiredHexLength = expectedLength * 2;
if (!hex) {
return '';
}
if (hex.length !== requiredHexLength) {
return hex.match(/.{1,2}/g)?.join(':') || hex;
}
return hex.match(/.{2}/g).join(':');
}
function renderPortCheckboxes(setting, value) {
const defaultVal = parseInt(value || 0, 10);
let html = `
<!-- hidden field to store the final bitmask -->
<input type="hidden" id="new-value-${setting.id}" value="${defaultVal}" />
<div class="checkbox-scroll">
`;
for (const [portName, portNum] of Object.entries(settingsData.ports)) {
if (skipPorts.includes(portName)) {
continue;
}
const bitIsSet = (defaultVal & (1 << (portNum - 1))) !== 0;
const checkboxId = `${portName}-${setting.id}`;
html += `
<div class="checkbox-container">
<input type="checkbox"
id="${checkboxId}"
onchange="updateBitmaskForSetting('${setting.id}')"
${bitIsSet ? 'checked' : ''}
/>
<label for="${checkboxId}">${portName.replace(/^port_/, "")}</label>
</div>
`;
}
html += `</div>`;
return html;
}
function renderOpenSkyDetectionBitmask(setting, value) {
const defaultVal = parseInt(value || 0, 10);
const bands = [
{ bit: 7, label: 'Enabled' },
{ bit: 6, label: '100–200 MHz' },
{ bit: 5, label: '400–500 MHz' },
{ bit: 4, label: '800–1000 MHz' },
{ bit: 3, label: '1200–1400 MHz' },
{ bit: 2, label: '1500–1600 MHz' },
{ bit: 1, label: '1800–2100 MHz' },
{ bit: 0, label: '2400–2500 MHz' }
];
let html = `
<input type="hidden" id="new-value-${setting.id}" value="${defaultVal}" />
<div class="checkbox-scroll">
`;
for (const band of bands) {
const bitIsSet = (defaultVal & (1 << band.bit)) !== 0;
const checkboxId = `band-${band.bit}-${setting.id}`;
html += `
<div class="checkbox-container">
<input type="checkbox"
id="${checkboxId}"
onchange="updateCustomBitmask('${setting.id}', ${band.bit})"
${bitIsSet ? 'checked' : ''}
/>
<label for="${checkboxId}">${band.label}</label>
</div>
`;
}
html += `</div>`;
return html;
}
function renderIntervalSetting(key, setting, value) {
const defaultSeconds = parseInt(value || 0, 10);
// Guess a default unit based on the numeric value:
// >=86400 => days, >=3600 => hours, >=60 => minutes, else seconds
const guessedUnit = (key === 'cold_fix_timeout' || key === 'hot_fix_timeout') ? '1' : guessTimeUnit(defaultSeconds);
// Convert the default seconds into that guessed unit
const displayValueInGuessedUnit = Math.round(convertSecondsToUnit(defaultSeconds, guessedUnit));
const lockToSeconds = key === 'cold_fix_timeout' || key === 'hot_fix_timeout';
return `
<!-- hidden actual seconds value -->
<input type="hidden" id="new-value-${setting.id}" value="${defaultSeconds}" />
<div class="interval-container">
<!-- The numeric input displayed to user -->
<input type="number"
id="interval-num-${setting.id}"
oninput="updateIntervalValue('${setting.id}')"
value="${displayValueInGuessedUnit}" />
<!-- The time unit select, with guessedUnit pre-selected -->
${lockToSeconds
? `<input type="hidden" id="interval-unit-${setting.id}" value="1" /><span class="interval-unit-label">second(s)</span>`
: `<select id="interval-unit-${setting.id}" onchange="updateIntervalUnit('${setting.id}')">
<option value="1"${guessedUnit === '1' ? ' selected' : ''}>second(s)</option>
<option value="60"${guessedUnit === '60' ? ' selected' : ''}>minute(s)</option>
<option value="3600"${guessedUnit === '3600' ? ' selected' : ''}>hour(s)</option>
<option value="86400"${guessedUnit === '86400' ? ' selected' : ''}>day(s)</option>
</select>`
}
</div>
`;
}
function guessTimeUnit(seconds) {
if (seconds >= 86400 && (seconds % 86400 === 0)) {
return '86400';
} else if (seconds >= 3600 && (seconds % 3600 === 0)) {
return '3600';
} else if (seconds >= 60 && (seconds % 60 === 0)) {
return '60';
}
return '1';
}
function formatSettingName(settingName, group) {
if (settingName.startsWith(group + "_")) {
settingName = settingName.replace(group + "_", "");
}
return settingName;
}
function getSettingMeta(key) {
return settingsMeta && settingsMeta.settings ? settingsMeta.settings[key] : null;
}
function getCommandMeta(key) {
return settingsMeta && settingsMeta.commands ? settingsMeta.commands[key] : null;
}
function getCommandInputMeta(key) {
const meta = getCommandMeta(key);
if (!meta) {
return null;
}
if (meta.input && meta.input.source) {
if (meta.input.source === 'values') {
return { source: 'values' };
}
if (meta.input.source === 'settings') {
return { source: 'settings' };
}
}
if (meta.options || meta.input) {
return meta;
}
return null;
}
function getCommandValueOptions() {
if (!settingsData || !settingsData.values) {
return [];
}
return Object.entries(settingsData.values)
.map(([name, meta]) => ({
name,
id: meta.id
}))
.sort((a, b) => a.name.localeCompare(b.name));
}
function getCommandSettingOptions() {
if (!settingsData || !settingsData.settings) {
return [];
}
return Object.entries(settingsData.settings)
.map(([name, meta]) => ({
name,
id: meta.id
}))
.sort((a, b) => a.name.localeCompare(b.name));
}
function getSettingLabel(key, group) {
const meta = getSettingMeta(key);
if (meta) {
if (meta.display_name) {
return meta.display_name;
}
if (meta.label) {
return meta.label;
}
}
return formatSettingName(key, group).replace(/_/g, " ");
}
function getSettingDescription(key) {
const meta = getSettingMeta(key);
return meta && meta.description ? meta.description : "";
}
function renderSettingInfoTrigger(description, details = []) {
const parts = [];
if (description) {
parts.push(String(description).trim());
}
if (Array.isArray(details)) {
details
.map((detail) => String(detail || '').trim())
.filter(Boolean)
.forEach((detail) => parts.push(detail));
}
if (!parts.length) {
return '';
}
const tooltipText = parts.join('\n');
const safeTooltip = escapeHtml(tooltipText);
return `<button type="button" class="setting-info-button" aria-label="${safeTooltip}" data-tooltip="${safeTooltip}" title="${safeTooltip}">i</button>`;
}
function getSettingOptions(key) {
const meta = getSettingMeta(key);
return meta && Array.isArray(meta.options) ? meta.options : null;
}
function getCommandLabel(key) {
const meta = getCommandMeta(key);
if (meta) {
if (meta.display_name) {
return meta.display_name;
}
if (meta.label) {
return meta.label;
}
}
return key.replace(/^cmd_/, "").replace(/_/g, " ");
}
function getCommandDescription(key) {
const meta = getCommandMeta(key);
return meta && meta.description ? meta.description : "";
}
function getGroupName(key) {
const meta = getSettingMeta(key);
if (meta && meta.category) {
return meta.category;
}
for (const [rx, groupName] of Object.entries(grouping)) {
const match = key.match(rx);
if (match) {
if (typeof groupName === 'number') {
return match[groupName];
} else {
return groupName;
}
}
}
return key;
}
function formatGroupTitle(groupName) {
if (!groupName) {
return '';
}
const normalized = String(groupName).trim().toLowerCase();
const customGroupTitles = {
ble: 'BLE',
ble_scan: 'BLE Scan',
cmdq: 'CMDQ',
gps: 'GPS',
lorawan: 'LoRaWAN',
lp0: 'LP0',
lr_gps: 'LR GPS',
lr_messaging: 'Messaging',
outdoor: 'Outdoor detection',
s_band: 'S-Band Satellite',
satellite: 'Iridium Satellite',
vhf: 'VHF',
wifi_scan: 'WiFi Scan'
};
if (customGroupTitles[normalized]) {
return customGroupTitles[normalized];
}
return String(groupName).replace(/_/g, ' ');
}
function groupAndSortSettings() {
const grouped = {};
const other = {};
const keepSingletonGroups = new Set(['status', 'memfault']);
for (const key in settingsData.settings) {
const groupName = getGroupName(key);
if (!grouped[groupName]) {
grouped[groupName] = {};
}
grouped[groupName][key] = settingsData.settings[key];
}
// Move singletons into "_other"
for (const prefix in grouped) {
if (Object.keys(grouped[prefix]).length === 1 && !keepSingletonGroups.has(prefix)) {
const [singleKey] = Object.keys(grouped[prefix]);
other[singleKey] = grouped[prefix][singleKey];
delete grouped[prefix];
}
}
if (Object.keys(other).length > 0) {
grouped["_other"] = other;
}
for (const groupName in grouped) {
for (const key in grouped[groupName]) {
grouped[groupName][key].display_name = getSettingLabel(key, groupName);
const description = getSettingDescription(key);
if (description) {
grouped[groupName][key].description = description;
}
}
}
// Sort groups
const sortedGroups = Object.keys(grouped).sort().reduce((acc, group) => {
acc[group] = Object.keys(grouped[group]).sort((a, b) => {
const nameA = grouped[group][a].display_name.toLowerCase();
const nameB = grouped[group][b].display_name.toLowerCase();
return nameA.localeCompare(nameB);
}).reduce((groupAcc, key) => {
groupAcc[key] = grouped[group][key];
return groupAcc;
}, {});
return acc;
}, {});
return sortedGroups;
}
function renderInput(key, setting) {
if (setting.length === 0) {
return '';
}
return `<div class="input-container" id="input-container-${setting.id}">${sanitizeRenderedInputHtml(
renderInputControl(key, setting, normalizeRenderableValue(setting.default))
)}</div>`;
}
function renderInputContainer(key, setting) {
return `<div class="input-container" id="input-container-${setting.id}"></div>`;
}
function renderInputControl(key, setting, value) {
if (setting.length === 0) {
return '';
}
value = normalizeRenderableValue(value);
// Build the "include" checkbox + label
let html = '';
// 0) Special byte array renderers
if (customByteArrayRenderers[key]) {
value = stripBytes(value);
html += customByteArrayRenderers[key](setting, value);
}
// 1) Custom input renderers
else if (customInputRenderers[key]) {
html += customInputRenderers[key](setting, value);
if (key === 'device_pin') {
value = normalizeDevicePinStorageValue(value);
}
}
// 2) If it's one of the bitmask settings -> render custom or port checkboxes
else if (isBitmaskSetting(key) && (setting.conversion === 'uint32' || setting.conversion === 'uint8')) {
if (customBitmaskRenderers[key]) {
html += customBitmaskRenderers[key](setting, value);
} else {
html += renderPortCheckboxes(setting, value);
}
}
// 3) If the key ends with "_interval" -> render numeric + time-unit select (with auto-guess)
else if (isIntervalSetting(key)) {
html += renderIntervalSetting(key, setting, value);
}
// 4) If metadata provides options -> render select + raw value
else if (getSettingOptions(key)) {
const metaOptions = getSettingOptions(key);
html += `<select id="new-value-${setting.id}" onchange="__onInputChanged('${setting.id}')">`;
for (const option of metaOptions) {
const optionValue = option.value;
const selected = String(optionValue) === String(value) ? ' selected' : '';
html += `<option value="${optionValue}"${selected}>${option.label}</option>`;
}
html += `</select>`;
html += `
<label class="raw-value-label" for="raw-value-${setting.id}">Raw value</label>
<input type="text" id="raw-value-${setting.id}" class="raw-value" value="${value ?? ''}" readonly />
`;
}
// 5) If it's a normal bool
else if (setting.conversion === 'bool') {
const boolValue = String(value).toLowerCase() === 'true';
html += `<select id="new-value-${setting.id}" onchange="__onInputChanged('${setting.id}')">`;
if (boolValue) {
html += `<option value="true" selected>true</option><option value="false">false</option>`;
} else {
html += `<option value="true">true</option><option value="false" selected>false</option>`;
}
html += `</select>`;
}
// 6) If it's a normal numeric input
else if (['uint32', 'uint16', 'uint8', 'int32', 'int8', 'float'].includes(setting.conversion)) {
const min = setting.min != undefined ? setting.min : minMaxValues[setting.conversion].min;
const max = setting.max != undefined ? setting.max : minMaxValues[setting.conversion].max;
html += `<input
type="number"
id="new-value-${setting.id}"
min="${min}"
max="${max}"
step="${setting.conversion === 'float' ? '0.01' : '1'}"
value="${value}"
oninput="__onInputChanged('${setting.id}')"
/>`;
}
// 7) If it's a byte_array
else if (setting.conversion === 'byte_array') {
value = stripBytes(value);
html += `<textarea id="new-value-${setting.id}" rows="4" oninput="__onInputChanged('${setting.id}')">${value}</textarea>`;
}
// 8) If it's a string
else if (setting.conversion === 'string') {
html += `<input type="text" id="new-value-${setting.id}" value="${value}" oninput="__onInputChanged('${setting.id}')"/>`;
}
// 9) Otherwise unknown/custom, default to text
else {
html += `<input type="text" id="new-value-${setting.id}" value="${value}" oninput="__onInputChanged('${setting.id}')"/>`;
}
let errorText = '';
try {
validateInput(key, setting, value);
} catch (error) {
errorText = error.message;
}
html += `<div class="input-error" id="input-error-${setting.id}">${errorText}</div>`; // close input-container
html += renderDynamicSettingHelper(key, setting);
return html;
}
function formatDurationCompact(totalSeconds) {
const seconds = Number(totalSeconds);
if (!Number.isFinite(seconds) || seconds < 0) {
return '—';
}
if (seconds === 0) {
return '0 seconds';
}
const units = [
{ size: 86400, label: 'day' },
{ size: 3600, label: 'hour' },
{ size: 60, label: 'minute' },
{ size: 1, label: 'second' }
];
const parts = [];
let remaining = Math.round(seconds);
for (const unit of units) {
if (remaining < unit.size) {
continue;
}
const count = Math.floor(remaining / unit.size);
remaining -= count * unit.size;
parts.push(`${count} ${unit.label}${count === 1 ? '' : 's'}`);
if (parts.length === 2) {
break;
}
}
return parts.join(' ');
}
function getSettingEffectiveValue(key) {
if (!settingsData || !settingsData.settings || !settingsData.settings[key]) {
return null;
}
const setting = settingsData.settings[key];
const currentValue = getInputValue(setting.id);
if (currentValue !== undefined && currentValue !== null && String(currentValue).trim() !== '') {
return currentValue;
}
return normalizeRenderableValue(setting.default);
}
function getGpsSkippedTriggeredIntervalHelperText() {
const skippedRaw = getSettingEffectiveValue('gps_skipped_triggered_interval');
const intervalRaw = getSettingEffectiveValue('ublox_send_interval');
const skippedCount = Number.parseInt(skippedRaw, 10);
const intervalSeconds = Number.parseInt(intervalRaw, 10);
if (!Number.isFinite(intervalSeconds) || intervalSeconds < 0) {
return 'Set ublox send interval to estimate how long the device may wait before forcing a GPS fix.';
}
const intervalLabel = formatDurationCompact(intervalSeconds);
if (!Number.isFinite(skippedCount) || skippedCount < 0) {
return `Ublox send interval is currently ${intervalLabel}.`;
}
if (skippedCount === 0) {
return `0 means the device performs a GPS fix on every ublox send interval (${intervalLabel}).`;
}
const maxSkipDuration = skippedCount * intervalSeconds;
return `With ublox send interval at ${intervalLabel}, the device may skip fixes for about ${formatDurationCompact(maxSkipDuration)} before forcing a new fix if no motion is detected.`;
}
function getDynamicSettingHelperText(key) {
if (key === 'gps_skipped_triggered_interval') {
return getGpsSkippedTriggeredIntervalHelperText();
}
return '';
}
function renderDynamicSettingHelper(key, setting) {
const text = getDynamicSettingHelperText(key);
if (!text) {
return '';
}
return `<div class="input-helper dynamic-setting-helper" id="dynamic-helper-${setting.id}">${escapeHtml(text)}</div>`;
}
function refreshDynamicSettingHelperByKey(key) {
const setting = settingsData && settingsData.settings ? settingsData.settings[key] : null;
if (!setting) {
return;
}
const helper = document.getElementById(`dynamic-helper-${setting.id}`);
if (!helper) {
return;
}
helper.textContent = getDynamicSettingHelperText(key);
}
function refreshDynamicSettingHelpers(key) {
const normalizedKey = String(key || '');
if (normalizedKey === 'gps_skipped_triggered_interval' || normalizedKey === 'ublox_send_interval') {
refreshDynamicSettingHelperByKey('gps_skipped_triggered_interval');
}
}
function parseByteArrayValue(value, expectedLength) {
const hex = stripBytes(value || '');
const bytes = new Uint8Array(expectedLength);
for (let i = 0; i < expectedLength; i++) {
const start = i * 2;
if (start + 2 <= hex.length) {
bytes[i] = parseInt(hex.substr(start, 2), 16);
} else {
bytes[i] = 0;
}
}
return bytes;
}
function renderByteArrayField(settingId, index, label, value, options, helpText, readOnly) {
const inputId = `byte-${settingId}-${index}`;
const control = options
? `<select id="${inputId}" onchange="updateLp0ByteArray('${settingId}')">
${options.map(option => `<option value="${option.value}"${option.value === value ? ' selected' : ''}>${option.label}</option>`).join('')}
</select>`
: `<input type="number"
id="${inputId}"
min="0"
max="255"
value="${value}"
${readOnly ? 'readonly' : ''}
oninput="updateLp0ByteArray('${settingId}')"
/>`;
return `
<div class="byte-array-field">
<label for="${inputId}">${label}</label>
${control}
${helpText ? `<div class="byte-array-help">${helpText}</div>` : ''}
</div>
`;
}
function renderLp0CommunicationParams(setting, value) {
const bytes = parseByteArrayValue(value, setting.length);
return `
<input type="hidden" id="new-value-${setting.id}" value="${bytesToHex(bytes)}" />
<div class="byte-array-grid">
${renderByteArrayField(setting.id, 0, 'Spreading factor', bytes[0], [
{ value: 0x05, label: 'LR11XX_RADIO_LORA_SF5 (0x05)' },
{ value: 0x06, label: 'LR11XX_RADIO_LORA_SF6 (0x06)' },
{ value: 0x07, label: 'LR11XX_RADIO_LORA_SF7 (0x07)' },
{ value: 0x08, label: 'LR11XX_RADIO_LORA_SF8 (0x08)' },
{ value: 0x09, label: 'LR11XX_RADIO_LORA_SF9 (0x09)' },
{ value: 0x0A, label: 'LR11XX_RADIO_LORA_SF10 (0x0A)' },
{ value: 0x0B, label: 'LR11XX_RADIO_LORA_SF11 (0x0B)' },
{ value: 0x0C, label: 'LR11XX_RADIO_LORA_SF12 (0x0C)' }
], 'Default: LR11XX_RADIO_LORA_SF9 (0x09)')}
${renderByteArrayField(setting.id, 1, 'Bandwidth', bytes[1], [
{ value: 0x08, label: 'LR11XX_RADIO_LORA_BW_10 (10.42 kHz, 0x08)' },
{ value: 0x01, label: 'LR11XX_RADIO_LORA_BW_15 (15.63 kHz, 0x01)' },
{ value: 0x09, label: 'LR11XX_RADIO_LORA_BW_20 (20.83 kHz, 0x09)' },
{ value: 0x02, label: 'LR11XX_RADIO_LORA_BW_31 (31.25 kHz, 0x02)' },
{ value: 0x0A, label: 'LR11XX_RADIO_LORA_BW_41 (41.67 kHz, 0x0A)' },
{ value: 0x03, label: 'LR11XX_RADIO_LORA_BW_62 (62.50 kHz, 0x03)' },
{ value: 0x04, label: 'LR11XX_RADIO_LORA_BW_125 (125.00 kHz, 0x04)' },
{ value: 0x05, label: 'LR11XX_RADIO_LORA_BW_250 (250.00 kHz, 0x05)' },
{ value: 0x06, label: 'LR11XX_RADIO_LORA_BW_500 (500.00 kHz, 0x06)' },
{ value: 0x0D, label: 'LR11XX_RADIO_LORA_BW_200 (203.00 kHz, 0x0D)' },
{ value: 0x0E, label: 'LR11XX_RADIO_LORA_BW_400 (406.00 kHz, 0x0E)' },
{ value: 0x0F, label: 'LR11XX_RADIO_LORA_BW_800 (812.00 kHz, 0x0F)' }
], 'Default: LR11XX_RADIO_LORA_BW_125 (0x04)')}
${renderByteArrayField(setting.id, 2, 'Coding rate', bytes[2], [
{ value: 0x00, label: 'LR11XX_RADIO_LORA_NO_CR (0x00)' },
{ value: 0x01, label: 'LR11XX_RADIO_LORA_CR_4_5 (0x01)' },
{ value: 0x02, label: 'LR11XX_RADIO_LORA_CR_4_6 (0x02)' },
{ value: 0x03, label: 'LR11XX_RADIO_LORA_CR_4_7 (0x03)' },
{ value: 0x04, label: 'LR11XX_RADIO_LORA_CR_4_8 (0x04)' },
{ value: 0x05, label: 'LR11XX_RADIO_LORA_CR_LI_4_5 (0x05)' },
{ value: 0x06, label: 'LR11XX_RADIO_LORA_CR_LI_4_6 (0x06)' },
{ value: 0x07, label: 'LR11XX_RADIO_LORA_CR_LI_4_8 (0x07)' }
], 'Default: LR11XX_RADIO_LORA_CR_4_5 (0x01)')}
${renderByteArrayField(setting.id, 3, 'RX1 window delay (seconds)', bytes[3], null, 'Must match across devices in the same network')}
${renderByteArrayField(setting.id, 4, 'Unused (reserved)', bytes[4], null, 'Currently not used')}
</div>
`;
}
function renderLp0NodeParams(setting, value) {
const bytes = parseByteArrayValue(value, setting.length);
return `
<input type="hidden" id="new-value-${setting.id}" value="${bytesToHex(bytes)}" />
<div class="byte-array-grid">