-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcalibration.html
More file actions
948 lines (836 loc) · 43.3 KB
/
Copy pathcalibration.html
File metadata and controls
948 lines (836 loc) · 43.3 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>UWB Distance Calibration</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: #333;
}
.container {
max-width: 900px;
margin: 0 auto;
}
h1 {
text-align: center;
color: white;
margin-bottom: 10px;
font-size: 2.5em;
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
}
.subtitle {
text-align: center;
color: rgba(255,255,255,0.9);
margin-bottom: 30px;
font-size: 1.1em;
}
.nav-button {
position: fixed;
top: 20px;
left: 20px;
padding: 12px 24px;
background: rgba(255, 255, 255, 0.95);
border: none;
border-radius: 8px;
color: #667eea;
font-weight: bold;
font-size: 1em;
cursor: pointer;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
transition: all 0.3s;
}
.nav-button:hover {
background: white;
box-shadow: 0 6px 12px rgba(0,0,0,0.15);
transform: translateY(-2px);
}
.controls-panel {
background: rgba(255, 255, 255, 0.95);
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
margin-bottom: 20px;
}
.controls-title {
font-size: 1.3em;
font-weight: bold;
color: #333;
margin-bottom: 15px;
text-align: center;
}
.control-item {
margin-bottom: 15px;
}
.control-label {
display: flex;
justify-content: space-between;
font-size: 0.9em;
color: #666;
margin-bottom: 5px;
}
.control-value {
color: #667eea;
font-weight: bold;
}
.control-hint {
font-size: 0.75em;
color: #999;
margin-top: 3px;
font-style: italic;
}
input[type="number"] {
width: 100%;
padding: 8px;
border: 2px solid #e0e0e0;
border-radius: 5px;
font-size: 0.9em;
background: white;
color: #333;
}
input[type="number"]:focus {
outline: none;
border-color: #667eea;
}
select {
width: 100%;
padding: 8px;
border: 2px solid #e0e0e0;
border-radius: 5px;
font-size: 0.9em;
background: white;
color: #333;
}
button {
cursor: pointer;
transition: all 0.3s;
}
button:hover {
opacity: 0.9;
transform: translateY(-1px);
}
@media (max-width: 768px) {
h1 {
font-size: 1.8em;
}
.nav-button {
position: static;
width: 100%;
margin-bottom: 20px;
}
}
</style>
</head>
<body>
<button class="nav-button" onclick="window.location.href='uwb_dashboard.html'">← Back to Dashboard</button>
<div class="container">
<h1>📏 Distance Calibration</h1>
<div class="subtitle">Calibrate distance measurements for optimal accuracy</div>
<!-- Calibration Panel -->
<div class="controls-panel">
<div class="controls-title">Measurement Collection (Global Calibration)</div>
<div class="control-item">
<div class="control-label">
<span>Select Anchor for Measurement</span>
</div>
<select id="calAnchor" style="width: 100%; padding: 8px; border: 2px solid #e0e0e0; border-radius: 5px; font-size: 0.9em;">
<option value="0">Anchor 0</option>
<option value="1">Anchor 1</option>
<option value="2">Anchor 2</option>
<option value="3">Anchor 3</option>
<option value="4">Anchor 4</option>
<option value="5">Anchor 5</option>
<option value="6">Anchor 6</option>
<option value="7">Anchor 7</option>
</select>
<div class="control-hint">Measurements from all anchors are used together for one global calibration</div>
</div>
<div class="control-item">
<div class="control-label">
<span>Current Measured Distance</span>
<span class="control-value" id="calCurrentDist">-- m</span>
</div>
</div>
<div class="control-item">
<div class="control-label">
<span>True Distance (meters)</span>
</div>
<div style="display: flex; gap: 10px;">
<input type="number" id="calTrueDist" min="0.1" max="20" step="0.01" value="1.0" style="flex: 1; width: auto;">
<button id="calAddMeasurement" style="padding: 8px 20px; border: none; border-radius: 5px; background: #4CAF50; color: white; font-weight: bold; cursor: pointer;">
Add Measurement
</button>
</div>
<div class="control-hint">Place tag/anchor at known distance, enter value, click Add</div>
</div>
<div class="control-item">
<div class="control-label">
<span>Measurements</span>
<span class="control-value" id="calMeasCount">0</span>
</div>
<div id="calMeasurements" style="max-height: 200px; overflow-y: auto; border: 1px solid #e0e0e0; border-radius: 5px; padding: 5px; background: #f9f9f9;"></div>
</div>
<div class="control-item">
<div style="display: flex; gap: 10px;">
<button id="calFit" style="flex: 1; padding: 10px; border: none; border-radius: 5px; background: #667eea; color: white; font-weight: bold; cursor: pointer;">
Fit Calibration
</button>
<button id="calClear" style="flex: 1; padding: 10px; border: none; border-radius: 5px; background: #f44336; color: white; font-weight: bold; cursor: pointer;">
Clear
</button>
</div>
</div>
<div class="control-item" id="calResults" style="display: none; background: #e8f5e9; padding: 12px; border-radius: 5px; margin-top: 10px;">
<div style="font-weight: bold; color: #2e7d32; margin-bottom: 8px;">Calibration Results:</div>
<div style="font-size: 0.9em;">
<div>Scale Factor: <strong id="calScale">--</strong></div>
<div>Offset: <strong id="calOffset">--</strong> mm</div>
<div>R² (fit quality): <strong id="calR2">--</strong></div>
</div>
<div style="margin-top: 12px; background: white; padding: 10px; border-radius: 5px;">
<canvas id="calPlot" style="height: 450px; max-width: 500px; margin: 0 auto;"></canvas>
</div>
</div>
<div class="control-item" style="margin-top: 10px;">
<button id="calStageFit" style="width: 100%; padding: 10px; border: none; border-radius: 5px; background: #4CAF50; color: white; font-weight: bold; cursor: pointer;">
⬇️ Stage Fit Results
</button>
<div class="control-hint">Load fit results into parameters below (fills defaults for empty fields)</div>
</div>
</div>
<!-- Device Parameters Panel -->
<div class="controls-panel">
<div class="controls-title">Device Parameters (AT+SETDEV)</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.9em;">
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X1: Label Rate</label>
<input type="number" id="paramLabelRate" placeholder="5" step="1" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X2: Antenna Delay</label>
<input type="number" id="paramAntennaDelay" placeholder="16336" step="1" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X3: Kalman Enable</label>
<input type="number" id="paramKalmanEnable" placeholder="1" min="0" max="1" step="1" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X4: Kalman Q</label>
<input type="number" id="paramKalmanQ" placeholder="0.018" step="0.001" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X5: Kalman R</label>
<input type="number" id="paramKalmanR" placeholder="0.642" step="0.001" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X6: Correction A</label>
<input type="number" id="paramCorrectionA" placeholder="1.0" step="0.0001" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X7: Correction B (mm)</label>
<input type="number" id="paramCorrectionB" placeholder="0.0" step="0.01" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X8: Positioning Enable</label>
<input type="number" id="paramPosEnable" placeholder="0" min="0" max="1" step="1" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
<div>
<label style="display: block; font-size: 0.85em; color: #666; margin-bottom: 2px;">X9: Positioning Dim</label>
<input type="number" id="paramPosDim" placeholder="0" step="1" style="width: 100%; padding: 6px; border: 1px solid #ddd; border-radius: 3px;">
</div>
</div>
<div class="control-item" style="margin-top: 15px;">
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<button id="calRead" style="padding: 10px; border: none; border-radius: 5px; background: #2196F3; color: white; font-weight: bold; cursor: pointer;">
📖 Read from Device
</button>
<button id="calReset" style="padding: 10px; border: none; border-radius: 5px; background: #9E9E9E; color: white; font-weight: bold; cursor: pointer;">
🔄 Reset to Raw
</button>
</div>
<button id="calWrite" style="width: 100%; margin-top: 10px; padding: 12px; border: none; border-radius: 5px; background: #FF9800; color: white; font-weight: bold; cursor: pointer; font-size: 1.05em;">
📝 Write to Device & Save
</button>
<div class="control-hint">Read: Load current params | Reset: Set a=1.0, b=0.0 | Write: Send all params to device (TTL port required)</div>
</div>
</div>
</div>
<script>
// ===== Calibration Controls =====
let calibrationData = {};
let calibrationChart = null;
let currentData = {};
function updateCurrentDistance() {
const anchorId = document.getElementById('calAnchor').value;
const anchorData = currentData?.anchors?.[anchorId];
const distElement = document.getElementById('calCurrentDist');
if (anchorData && anchorData.connected && anchorData.distance !== null) {
distElement.textContent = anchorData.distance.toFixed(3) + ' m';
distElement.style.color = '#4CAF50';
} else {
distElement.textContent = '-- m (disconnected)';
distElement.style.color = '#999';
}
}
// Poll for current distance data
async function updateCurrentData() {
try {
const response = await fetch('/data');
currentData = await response.json();
updateCurrentDistance();
} catch (error) {
console.error('Error fetching current data:', error);
}
}
function setupCalibrationControls() {
const anchorSelect = document.getElementById('calAnchor');
const addBtn = document.getElementById('calAddMeasurement');
const fitBtn = document.getElementById('calFit');
const clearBtn = document.getElementById('calClear');
const plotAllBtn = document.getElementById('calPlotAll');
const trueDist = document.getElementById('calTrueDist');
// Load initial calibration status
fetchCalibrationStatus();
// Update current distance when anchor selection changes
anchorSelect.addEventListener('change', () => {
updateCurrentDistance();
});
// Add measurement
addBtn.addEventListener('click', async () => {
const anchorId = anchorSelect.value;
const trueDistance = parseFloat(trueDist.value);
if (isNaN(trueDistance) || trueDistance <= 0) {
alert('Please enter a valid true distance');
return;
}
try {
const response = await fetch('/calibration/add_measurement', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
anchor_id: anchorId,
true_distance_m: trueDistance
})
});
const data = await response.json();
if (data.status === 'ok') {
console.log('Measurement added:', data);
await fetchCalibrationStatus();
updateMeasurementsList();
// No popup on success - just update UI
} else {
alert('Error: ' + data.message);
}
} catch (error) {
console.error('Error adding measurement:', error);
alert('Failed to add measurement: ' + error.message);
}
});
// Fit calibration
fitBtn.addEventListener('click', async () => {
try {
const response = await fetch('/calibration/fit', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
const data = await response.json();
if (data.status === 'ok') {
console.log('Calibration fitted:', data);
// Show results
document.getElementById('calResults').style.display = 'block';
document.getElementById('calScale').textContent = data.scale_factor.toFixed(4);
document.getElementById('calOffset').textContent = data.offset_mm.toFixed(2);
document.getElementById('calR2').textContent = data.r_squared.toFixed(4);
await fetchCalibrationStatus();
// Draw calibration plot
drawCalibrationPlot(data.scale_factor, data.offset_mm);
alert(`Global calibration fitted!\nScale: ${data.scale_factor.toFixed(4)}\nOffset: ${data.offset_mm.toFixed(2)}mm\nR²: ${data.r_squared.toFixed(4)}\n\nThis will be applied to ALL anchors.`);
} else {
alert('Error: ' + data.message);
}
} catch (error) {
console.error('Error fitting calibration:', error);
alert('Failed to fit calibration: ' + error.message);
}
});
// Clear calibration
clearBtn.addEventListener('click', async () => {
if (!confirm(`Clear ALL calibration data?`)) {
return;
}
try {
const response = await fetch('/calibration/clear', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
const data = await response.json();
if (data.status === 'ok') {
console.log('Calibration cleared');
document.getElementById('calResults').style.display = 'none';
await fetchCalibrationStatus();
updateMeasurementsList();
alert('All calibration data cleared');
} else {
alert('Error: ' + data.message);
}
} catch (error) {
console.error('Error clearing calibration:', error);
alert('Failed to clear calibration: ' + error.message);
}
});
// Stage fit results into parameter fields
const stageFitBtn = document.getElementById('calStageFit');
stageFitBtn.addEventListener('click', () => {
// Get fit results from the UI
const scaleText = document.getElementById('calScale').textContent;
const offsetText = document.getElementById('calOffset').textContent;
if (scaleText === '--' || offsetText === '--') {
alert('Please fit calibration first before staging results');
return;
}
const scale = parseFloat(scaleText);
const offset = parseFloat(offsetText);
// Fill correction_a and correction_b
document.getElementById('paramCorrectionA').value = scale.toFixed(4);
document.getElementById('paramCorrectionB').value = offset.toFixed(2);
// Fill defaults for any empty fields
const defaults = {
'paramLabelRate': '5',
'paramAntennaDelay': '16336',
'paramKalmanEnable': '1',
'paramKalmanQ': '0.018',
'paramKalmanR': '0.642',
'paramPosEnable': '0',
'paramPosDim': '0'
};
for (const [id, defaultVal] of Object.entries(defaults)) {
const field = document.getElementById(id);
if (!field.value) {
field.value = defaultVal;
}
}
alert(`Fit results staged!\n\nCorrection A: ${scale.toFixed(4)}\nCorrection B: ${offset.toFixed(2)} mm\n\nEmpty fields filled with defaults. Review and click "Write to Device & Save".`);
});
// Read device parameters
const readBtn = document.getElementById('calRead');
readBtn.addEventListener('click', async () => {
const maxRetries = 3;
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const response = await fetch('/calibration/read_device', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
const data = await response.json();
if (data.status === 'ok') {
// Parse the response: cap:5 anndelay:16336, kalman_enable:1, kalman_Q:0.018, kalman_R:0.642, para_a:1.0000, para_b:0.00, pos_enable:0, pos_dimen:0
const response = data.response;
// Extract values using regex for each parameter
const extractValue = (param) => {
const regex = new RegExp(param + ':([-0-9.]+)');
const match = response.match(regex);
return match ? match[1] : null;
};
const cap = extractValue('cap');
const anndelay = extractValue('anndelay');
const kalman_enable = extractValue('kalman_enable');
const kalman_Q = extractValue('kalman_Q');
const kalman_R = extractValue('kalman_R');
const para_a = extractValue('para_a');
const para_b = extractValue('para_b');
const pos_enable = extractValue('pos_enable');
const pos_dimen = extractValue('pos_dimen');
if (cap && anndelay && kalman_enable && kalman_Q && kalman_R && para_a && para_b !== null && pos_enable !== null && pos_dimen !== null) {
document.getElementById('paramLabelRate').value = cap;
document.getElementById('paramAntennaDelay').value = anndelay;
document.getElementById('paramKalmanEnable').value = kalman_enable;
document.getElementById('paramKalmanQ').value = kalman_Q;
document.getElementById('paramKalmanR').value = kalman_R;
document.getElementById('paramCorrectionA').value = parseFloat(para_a).toFixed(4);
document.getElementById('paramCorrectionB').value = parseFloat(para_b).toFixed(2);
document.getElementById('paramPosEnable').value = pos_enable;
document.getElementById('paramPosDim').value = pos_dimen;
alert('Device parameters loaded into fields!\n\nYou can now edit and write back to device.');
return; // Success - exit the retry loop
} else {
// Could not parse - retry
lastError = 'Could not parse all parameters from device response:\n' + response;
console.log(`Attempt ${attempt}/${maxRetries} failed: parse error`);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 200)); // Wait 200ms before retry
continue;
}
}
} else {
// Error response - retry
lastError = 'Error reading device parameters: ' + data.message;
console.log(`Attempt ${attempt}/${maxRetries} failed: ${data.message}`);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 200)); // Wait 200ms before retry
continue;
}
}
} catch (error) {
lastError = 'Failed to read device parameters: ' + error.message + '\n\nMake sure TTL port is connected.';
console.log(`Attempt ${attempt}/${maxRetries} failed:`, error);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 200)); // Wait 200ms before retry
continue;
}
}
}
// If we get here, all retries failed
console.error('All retry attempts failed');
alert(lastError);
});
// Reset calibration to raw in parameter fields
const resetBtn = document.getElementById('calReset');
resetBtn.addEventListener('click', () => {
// Set all fields to default values with calibration reset
document.getElementById('paramLabelRate').value = '5';
document.getElementById('paramAntennaDelay').value = '16336';
document.getElementById('paramKalmanEnable').value = '1';
document.getElementById('paramKalmanQ').value = '0.018';
document.getElementById('paramKalmanR').value = '0.642';
document.getElementById('paramCorrectionA').value = '1.0000';
document.getElementById('paramCorrectionB').value = '0.00';
document.getElementById('paramPosEnable').value = '0';
document.getElementById('paramPosDim').value = '0';
alert('Parameters reset to defaults with raw calibration (a=1.0, b=0.0).\n\nClick "Write to Device & Save" to apply.');
});
// Write all parameters to device
const writeBtn = document.getElementById('calWrite');
writeBtn.addEventListener('click', async () => {
// Read all parameter fields
const labelRate = document.getElementById('paramLabelRate').value || '5';
const antennaDelay = document.getElementById('paramAntennaDelay').value || '16336';
const kalmanEnable = document.getElementById('paramKalmanEnable').value || '1';
const kalmanQ = document.getElementById('paramKalmanQ').value || '0.018';
const kalmanR = document.getElementById('paramKalmanR').value || '0.642';
const correctionA = document.getElementById('paramCorrectionA').value || '1.0';
const correctionB = document.getElementById('paramCorrectionB').value || '0.0';
const posEnable = document.getElementById('paramPosEnable').value || '0';
const posDim = document.getElementById('paramPosDim').value || '0';
const params = {
label_rate: parseInt(labelRate),
antenna_delay: parseInt(antennaDelay),
kalman_enable: parseInt(kalmanEnable),
kalman_q: parseFloat(kalmanQ),
kalman_r: parseFloat(kalmanR),
correction_a: parseFloat(correctionA),
correction_b: parseFloat(correctionB),
positioning_enable: parseInt(posEnable),
positioning_dim: parseInt(posDim)
};
// Confirm before writing
const confirmMsg = `Write these parameters to device?\n\n` +
`X1 (Label Rate): ${params.label_rate}\n` +
`X2 (Antenna Delay): ${params.antenna_delay}\n` +
`X3 (Kalman Enable): ${params.kalman_enable}\n` +
`X4 (Kalman Q): ${params.kalman_q}\n` +
`X5 (Kalman R): ${params.kalman_r}\n` +
`X6 (Correction A): ${params.correction_a}\n` +
`X7 (Correction B): ${params.correction_b} mm\n` +
`X8 (Pos Enable): ${params.positioning_enable}\n` +
`X9 (Pos Dim): ${params.positioning_dim}\n\n` +
`Device will save and reboot. Requires TTL port. Continue?`;
if (!confirm(confirmMsg)) {
return;
}
// Show writing indicator by disabling button
writeBtn.disabled = true;
writeBtn.style.opacity = '0.5';
writeBtn.textContent = '⏳ Writing...';
const maxRetries = 2;
let lastError = null;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
// Create abort controller for timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
const response = await fetch('/calibration/write_device', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(params),
signal: controller.signal
});
clearTimeout(timeoutId);
const data = await response.json();
if (data.status === 'ok') {
// Success
writeBtn.disabled = false;
writeBtn.style.opacity = '1';
writeBtn.textContent = '📝 Write to Device & Save';
alert('✓ Parameters successfully written to device!\n\nDevice saved and will reboot.\n\nUSB port will auto-reconnect in a few seconds.');
return;
} else {
// Error response
lastError = data.message || 'Unknown error';
console.log(`Attempt ${attempt}/${maxRetries} failed: ${lastError}`);
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 500));
continue;
}
}
} catch (error) {
if (error.name === 'AbortError') {
lastError = 'Request timed out after 10 seconds. Device may still be processing.';
// Don't retry on timeout - the request might have succeeded but response was slow
break;
} else {
lastError = error.message;
}
if (attempt < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 500));
continue;
}
}
}
// All retries failed
writeBtn.disabled = false;
writeBtn.style.opacity = '1';
writeBtn.textContent = '📝 Write to Device & Save';
let errorAlert = `✗ Failed to write parameters.\n\nError: ${lastError}\n\n`;
if (lastError.includes('timed out')) {
errorAlert += `The request timed out, but the write may have succeeded.\n\nTo verify:\n• Click "Read from Device" to check if parameters were updated\n• Look for device reboot in server console\n• Check that TTL port is connected and responsive`;
} else {
errorAlert += `Troubleshooting:\n• Make sure TTL (serial) port is connected\n• Check that device is powered on\n• Try clicking "Read from Device" first to verify connection\n• Check server console for detailed error messages`;
}
alert(errorAlert);
});
}
async function fetchCalibrationStatus() {
try {
const response = await fetch('/calibration/status');
calibrationData = await response.json();
console.log('Calibration data loaded:', calibrationData);
} catch (error) {
console.error('Error fetching calibration status:', error);
}
}
function updateMeasurementsList() {
const measurements = calibrationData?.measurements || [];
const container = document.getElementById('calMeasurements');
const countElement = document.getElementById('calMeasCount');
countElement.textContent = measurements.length;
if (measurements.length === 0) {
container.innerHTML = '<div style="color: #999; text-align: center; padding: 10px;">No measurements yet</div>';
document.getElementById('calResults').style.display = 'none';
return;
}
let html = '';
measurements.forEach((m, i) => {
const error = m.measured_distance_m - m.true_distance_m;
const isEditing = container.dataset.editingIndex == i;
const anchorLabel = m.anchor_id !== undefined ? `A${m.anchor_id} ` : '';
if (isEditing) {
// Show edit mode
html += `
<div style="padding: 5px; border-bottom: 1px solid #ddd; display: flex; gap: 5px; align-items: center; background: #fff3cd;">
<span style="min-width: 20px;">${i + 1}.</span>
<input type="number" id="editTrue_${i}" value="${m.true_distance_m}" step="0.01" style="width: 60px; padding: 2px 4px; border: 1px solid #667eea; border-radius: 3px;">
<span style="font-size: 0.85em;">m</span>
<button onclick="saveMeasurementEdit(${i})" style="padding: 2px 8px; border: none; border-radius: 3px; background: #4CAF50; color: white; cursor: pointer; font-size: 0.85em;">✓</button>
<button onclick="cancelMeasurementEdit()" style="padding: 2px 8px; border: none; border-radius: 3px; background: #9E9E9E; color: white; cursor: pointer; font-size: 0.85em;">✗</button>
<span style="flex: 1; text-align: right; font-size: 0.85em;">${anchorLabel}Meas: ${m.measured_distance_m.toFixed(3)}m</span>
</div>
`;
} else {
// Show normal mode
html += `
<div style="padding: 5px; border-bottom: 1px solid #ddd; display: flex; gap: 5px; align-items: center;">
<span style="flex: 1;">${i + 1}. ${anchorLabel}True: ${m.true_distance_m.toFixed(2)}m | Meas: ${m.measured_distance_m.toFixed(3)}m</span>
<span style="color: ${error > 0 ? '#f44336' : '#4CAF50'}; font-size: 0.85em;">Δ: ${error.toFixed(3)}m</span>
<button onclick="editMeasurement(${i})" style="padding: 2px 6px; border: none; border-radius: 3px; background: #2196F3; color: white; cursor: pointer; font-size: 0.85em;" title="Edit">✏️</button>
<button onclick="deleteMeasurement(${i})" style="padding: 2px 6px; border: none; border-radius: 3px; background: #f44336; color: white; cursor: pointer; font-size: 0.85em;" title="Delete">✗</button>
</div>
`;
}
});
container.innerHTML = html;
}
async function deleteMeasurement(index) {
if (!confirm(`Delete measurement ${index + 1}?`)) {
return;
}
try {
const response = await fetch('/calibration/delete_measurement', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
index: index
})
});
const data = await response.json();
if (data.status === 'ok') {
await fetchCalibrationStatus();
updateMeasurementsList();
} else {
alert('Error deleting measurement: ' + data.message);
}
} catch (error) {
console.error('Error deleting measurement:', error);
alert('Failed to delete measurement: ' + error.message);
}
}
function editMeasurement(index) {
const container = document.getElementById('calMeasurements');
container.dataset.editingIndex = index;
updateMeasurementsList();
}
function cancelMeasurementEdit() {
const container = document.getElementById('calMeasurements');
delete container.dataset.editingIndex;
updateMeasurementsList();
}
async function saveMeasurementEdit(index) {
const newValue = parseFloat(document.getElementById(`editTrue_${index}`).value);
if (isNaN(newValue) || newValue <= 0) {
alert('Please enter a valid distance');
return;
}
try {
const response = await fetch('/calibration/edit_measurement', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
index: index,
true_distance_m: newValue
})
});
const data = await response.json();
if (data.status === 'ok') {
const container = document.getElementById('calMeasurements');
delete container.dataset.editingIndex;
await fetchCalibrationStatus();
updateMeasurementsList();
} else {
alert('Error updating measurement: ' + data.message);
}
} catch (error) {
console.error('Error updating measurement:', error);
alert('Failed to update measurement: ' + error.message);
}
}
function drawCalibrationPlot(scaleFactor, offsetMm) {
const measurements = calibrationData?.measurements || [];
if (measurements.length === 0) {
return;
}
const canvas = document.getElementById('calPlot');
const ctx = canvas.getContext('2d');
// Clear existing chart
if (calibrationChart) {
calibrationChart.destroy();
}
// Prepare data - color by anchor
const colors = ['#667eea', '#f44336', '#4CAF50', '#FF9800', '#9C27B0', '#00BCD4', '#FFEB3B', '#795548'];
const measData = measurements.map(m => ({
x: m.measured_distance_m,
y: m.true_distance_m,
backgroundColor: colors[parseInt(m.anchor_id) % 8] || '#667eea'
}));
// Calculate fit line points
const minMeas = Math.min(...measurements.map(m => m.measured_distance_m));
const maxMeas = Math.max(...measurements.map(m => m.measured_distance_m));
const fitLine = [
{ x: minMeas, y: scaleFactor * minMeas + offsetMm / 1000.0 },
{ x: maxMeas, y: scaleFactor * maxMeas + offsetMm / 1000.0 }
];
// Perfect line (y=x)
const perfectLine = [
{ x: minMeas, y: minMeas },
{ x: maxMeas, y: maxMeas }
];
calibrationChart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [
{
label: 'Measurements',
data: measData,
backgroundColor: function(context) {
return context.raw.backgroundColor;
},
pointRadius: 6,
pointHoverRadius: 8
},
{
label: 'Fitted Line',
data: fitLine,
type: 'line',
borderColor: '#4CAF50',
borderWidth: 2,
fill: false,
pointRadius: 0
},
{
label: 'Perfect (y=x)',
data: perfectLine,
type: 'line',
borderColor: '#ccc',
borderWidth: 1,
borderDash: [5, 5],
fill: false,
pointRadius: 0
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
title: {
display: true,
text: 'Global Calibration (All Anchors)'
},
legend: {
display: true
}
},
scales: {
x: {
title: {
display: true,
text: 'Measured Distance (m)'
},
ticks: {
callback: function(value) { return value.toFixed(2); }
}
},
y: {
title: {
display: true,
text: 'True Distance (m)'
},
ticks: {
callback: function(value) { return value.toFixed(2); }
}
}
}
}
});
}
// ===== Initialize =====
setupCalibrationControls();
// Update current distance every 500ms
setInterval(updateCurrentData, 500);
// Initial update
updateCurrentData();
</script>
</body>
</html>