-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3719 lines (3216 loc) · 163 KB
/
Copy pathapp.js
File metadata and controls
3719 lines (3216 loc) · 163 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
/* ==========================================================================
ARGOS - CORE SYSTEM JS CONTROLLER (FULLY CORRECTED & STABLE)
========================================================================== */
document.addEventListener('DOMContentLoaded', () => {
// ==========================================
// 1. STATE VARIABLES
// ==========================================
const state = {
currentTab: 'inicio',
currentProfile: 'operador', // default to Operator so they can see all interactive features
droneStatus: 'hangar', // hangar, launching, flying, landing
droneAlt: 0.0,
droneBattery: 100,
systemBattery: 98,
solarPower: 18.4,
cameraScanlines: true,
cameraNoise: false,
sensors: {
temperature: 22.4,
humidity: 68.0,
pressure: 1013,
rain: false,
flame: false,
accelX: 0,
accelY: 0,
gpsLat: 9.93242,
gpsLon: -84.07921
},
// Locomotion
locoSpeed: 1, // 1x, 2x, 3x
locoMoving: false,
locoDirection: null,
wheelAngle: 0,
// Headlights
headlights: false,
// Lab 1
steamLab1Loaded: false,
// Lab 2 (Sim)
steamSimActive: false,
steamSimInterval: null,
steamSimDronePos: 90, // bottom distance in px
steamSimWind: 15,
steamSimScore: 0,
// Lab 3 (AI Trainer)
aiAccuracy: 0,
currentCrackSample: 'sano', // sano, leve, grave
aiLabsCompleted: false
};
// ==========================================
// 2. ELEMENT SELECTORS
// ==========================================
// Navigation & Tabs
const navBtns = document.querySelectorAll('.nav-btn');
const tabContents = document.querySelectorAll('.tab-content');
const heroGoDashboard = document.querySelector('[data-target="dashboard"]');
const heroGoSteam = document.querySelector('[data-target="steam"]');
// Top Header Status Panel
const topGpsVal = document.getElementById('gps-coords');
const topAltVal = document.getElementById('robot-alt');
const topBatVal = document.getElementById('robot-battery-pct');
const topSignalVal = document.getElementById('telemetry-latency');
// Connection Controls Panel
const esp32Toggle = document.getElementById('esp32-toggle');
const robotIpInput = document.getElementById('robot-ip');
const cameraStreamPathInput = document.getElementById('camera-stream-path');
const camSourceSelect = document.getElementById('cam-source-select');
const camDeviceContainer = document.getElementById('cam-device-container');
const camDeviceSelect = document.getElementById('cam-device-select');
const connStatus = document.getElementById('conn-status');
const labelSim = document.getElementById('label-sim');
const labelReal = document.getElementById('label-real');
// Profile Selector
const profileSelect = document.getElementById('profile-select');
const globalStatusBadge = document.getElementById('global-status-badge');
const globalStatusText = document.getElementById('global-status-text');
// Cameras
const canvasFrontal = document.getElementById('canvas-cam-frontal');
const canvasTrasera = document.getElementById('canvas-cam-trasera');
const canvasDrone = document.getElementById('canvas-cam-drone');
const toggleScanlinesBtn = document.getElementById('toggle-scanlines');
const toggleStaticBtn = document.getElementById('toggle-static');
const aiBoxFrontal = document.getElementById('ai-box-frontal');
const aiBoxTrasera = document.getElementById('ai-box-trasera');
const aiBoxDrone = document.getElementById('ai-box-drone');
const droneFeedOverlay = document.getElementById('drone-feed-overlay');
const hudDroneAlt = document.getElementById('hud-drone-alt');
const hudDroneBat = document.getElementById('hud-drone-bat');
// Headlights
const ledLightSwitch = document.getElementById('led-light-switch');
const ledLightOverlay = document.getElementById('led-light-overlay');
// Telemetry Dashboard
const gaugePressVal = document.getElementById('gauge-press-val');
const gaugePressRing = document.getElementById('pressure-gauge-ring');
const rainIndicator = document.getElementById('rain-indicator-box');
const rainText = document.getElementById('sensor-rain-val');
const flameIndicator = document.getElementById('flame-indicator-box');
const flameText = document.getElementById('sensor-flame-val');
const tiltXText = document.getElementById('tilt-x');
const tiltYText = document.getElementById('tilt-y');
const oscilloscopeCanvas = document.getElementById('oscilloscope-canvas');
const radarPing = document.getElementById('radar-pos-ping');
const radarLatText = document.getElementById('radar-lat');
const radarLonText = document.getElementById('radar-lon');
// Terrestrial Locomotion
const btnLocoForward = document.getElementById('btn-loco-forward');
const btnLocoBack = document.getElementById('btn-loco-back');
const btnLocoLeft = document.getElementById('btn-loco-left');
const btnLocoRight = document.getElementById('btn-loco-right');
const locoSpeedSlider = document.getElementById('loco-speed-slider');
// Drone Flight Controls
const flightSystemStatus = document.getElementById('flight-system-status');
const takeoffLogs = document.getElementById('takeoff-logs');
const btnPreFlight = document.getElementById('btn-pre-flight');
const manualControlsCard = document.getElementById('manual-controls-card');
const droneAltSlider = document.getElementById('drone-alt-slider');
const sliderAltVal = document.getElementById('slider-alt-val');
const btnRTL = document.getElementById('btn-rtl');
const btnLand = document.getElementById('btn-land');
const joyForward = document.getElementById('ctrl-forward');
const joyBack = document.getElementById('ctrl-back');
const joyLeft = document.getElementById('ctrl-left');
const joyRight = document.getElementById('ctrl-right');
// STEAM Section
const steamProfileDisplay = document.getElementById('steam-profile-display');
const studentModule = document.getElementById('student-module');
const teacherModule = document.getElementById('teacher-module');
const btnExportCSV = document.getElementById('btn-export-csv');
const btnExportJSON = document.getElementById('btn-export-json');
const exportMsg = document.getElementById('export-msg');
const studentLabsProgress = document.getElementById('student-labs-progress');
// STEAM Lab 1
const btnLoadLabData = document.getElementById('btn-load-lab-data');
const labDataStatus = document.getElementById('lab-data-status');
const labQuizBox = document.getElementById('lab-quiz');
const btnSubmitQuiz = document.getElementById('btn-submit-quiz');
const quizFeedbackBox = document.getElementById('quiz-feedback-box');
// STEAM Lab 2 (Sim)
const simDroneElement = document.getElementById('sim-drone-element');
const simWindSpeedText = document.getElementById('sim-wind-speed');
const rpmSlider = document.getElementById('rpm-slider');
const rpmDisplayVal = document.getElementById('rpm-display-val');
const btnStartSim = document.getElementById('btn-start-sim');
const btnResetSim = document.getElementById('btn-reset-sim');
const simFeedbackMsg = document.getElementById('sim-feedback-msg');
// STEAM Lab 3 (AI Trainer)
const canvasAiCrack = document.getElementById('canvas-ai-crack');
const btnAiSano = document.getElementById('btn-ai-sano');
const btnAiLeve = document.getElementById('btn-ai-leve');
const btnAiGrave = document.getElementById('btn-ai-grave');
const aiAccuracyBar = document.getElementById('ai-accuracy-bar');
const aiAccuracyPct = document.getElementById('ai-accuracy-pct');
const aiTrainingFeedback = document.getElementById('ai-training-feedback');
const aiCertBadge = document.getElementById('ai-cert-badge');
// Clickable Schematic
const svgOrugas = document.getElementById('svg-part-orugas');
const svgSolar = document.getElementById('svg-part-solar');
const svgHangar = document.getElementById('svg-part-hangar');
const schematicDetailCard = document.getElementById('schematic-detail-card');
const detailPartName = document.getElementById('detail-part-name');
const detailPartDesc = document.getElementById('detail-part-desc');
const btnCloseDetails = document.getElementById('btn-close-details');
// ==========================================
// 3. SOUND SYNTHESIZER & SPEECH CONTROLLER (WEB AUDIO API)
// ==========================================
class WebSynth {
constructor() {
this.ctx = null;
this.initialized = false;
}
init() {
if (this.initialized) return;
try {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
this.ctx = new AudioContextClass();
this.initialized = true;
} catch (e) {
console.warn('AudioContext not supported or blocked in this browser.', e);
}
}
resume() {
if (this.ctx && this.ctx.state === 'suspended') {
this.ctx.resume().catch(e => console.warn('Failed to resume AudioContext:', e));
}
}
beep(freq = 600, type = 'sine', duration = 0.08) {
this.init();
this.resume();
if (!this.ctx) return;
try {
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, this.ctx.currentTime);
gain.gain.setValueAtTime(0.08, this.ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, this.ctx.currentTime + duration);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start();
osc.stop(this.ctx.currentTime + duration);
} catch (err) {
// Suppress audio warnings before user interaction gestures
}
}
alarm(duration = 0.5) {
this.init();
this.resume();
if (!this.ctx) return;
try {
const now = this.ctx.currentTime;
const osc1 = this.ctx.createOscillator();
const osc2 = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc1.type = 'sawtooth';
osc1.frequency.setValueAtTime(880, now);
osc1.frequency.linearRampToValueAtTime(440, now + duration);
osc2.type = 'sine';
osc2.frequency.setValueAtTime(220, now);
osc2.frequency.linearRampToValueAtTime(110, now + duration);
gain.gain.setValueAtTime(0.05, now);
gain.gain.exponentialRampToValueAtTime(0.0001, now + duration);
osc1.connect(gain);
osc2.connect(gain);
gain.connect(this.ctx.destination);
osc1.start();
osc2.start();
osc1.stop(now + duration);
osc2.stop(now + duration);
} catch (err) {}
}
victory() {
this.init();
this.resume();
if (!this.ctx) return;
try {
const now = this.ctx.currentTime;
const notes = [261.63, 329.63, 392.00, 523.25]; // C4, E4, G4, C5
notes.forEach((freq, idx) => {
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(freq, now + idx * 0.12);
gain.gain.setValueAtTime(0.06, now + idx * 0.12);
gain.gain.exponentialRampToValueAtTime(0.0001, now + idx * 0.12 + 0.3);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start(now + idx * 0.12);
osc.stop(now + idx * 0.12 + 0.3);
});
} catch (err) {}
}
speak(text) {
if ('speechSynthesis' in window) {
try {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'es-ES';
utterance.rate = 1.0;
utterance.pitch = 1.15;
window.speechSynthesis.speak(utterance);
} catch (err) {}
}
}
}
const synth = new WebSynth();
// Attach hover beeps safely
function attachHoverSounds() {
const interactiveElements = document.querySelectorAll('button, select, input[type="range"], .clickable-part');
interactiveElements.forEach(el => {
el.addEventListener('mouseenter', () => {
synth.beep(800, 'sine', 0.03);
});
el.addEventListener('click', () => {
synth.beep(550, 'sine', 0.06);
});
});
}
setTimeout(attachHoverSounds, 500);
// ==========================================
// 4. TAB ROUTING & SCHEMATIC INTERACTIVE BLUEPRINT
// ==========================================
function switchTab(tabId) {
state.currentTab = tabId;
// Update navigation active states
navBtns.forEach(btn => {
if (btn.getAttribute('data-tab') === tabId) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
// Update section visibility
tabContents.forEach(section => {
if (section.id === tabId) {
section.classList.add('active');
} else {
section.classList.remove('active');
}
});
// Resize charts/canvases dynamically (Fixes 0x0 hidden render errors)
if (tabId === 'dashboard') {
setTimeout(() => {
resizeCanvases();
resizeOscilloscope();
if (telemetryChart && typeof Chart !== 'undefined') {
try {
telemetryChart.resize();
} catch (err) {}
}
}, 100);
}
}
navBtns.forEach(btn => {
btn.addEventListener('click', () => {
switchTab(btn.getAttribute('data-tab'));
});
});
// Bind all elements with data-target to switch tabs (like the "Ingresar al Aula Virtual" button)
const targetBtns = document.querySelectorAll('[data-target]');
targetBtns.forEach(btn => {
btn.addEventListener('click', () => {
const targetTab = btn.getAttribute('data-target');
switchTab(targetTab);
});
});
// Interactive Schematic Parts
const specs = {
orugas: {
name: "Sistema de Tracción Oruga 12V",
desc: "Tracción por orugas robustas de goma impulsadas por motores de corriente continua de 12 V con alto torque y reductores metálicos. Permite al robot superar pendientes de hasta 35° y desplazarse en lodo, asfalto roto o rocas. La velocidad máxima terrestre es de 1.5 m/s."
},
solar: {
name: "Generación Solar Fotovoltaica",
desc: "Panel solar monocristalino integrado de 20 W montado en el chasis superior. Cuenta con un regulador de carga MPPT (Maximum Power Point Tracking) conectado a los ESP32, que recarga la batería central de LiFePO4 durante exploraciones prolongadas a la luz del día, extendiendo la autonomía hasta un 40%."
},
hangar: {
name: "Hangar y Rampa de UAV Aéreo",
desc: "Bahía mecánica hermética trasera equipada con servo-motores de apertura superior. Aloja un micro-dron (quadcopter) de reconocimiento aéreo. Dispone de un elevador interior y un cargador de contacto inductivo automático para reponer el nivel del dron mientras está alojado en base."
}
};
function selectSchematicPart(element, key) {
if (!element || !specs[key]) return;
[svgOrugas, svgSolar, svgHangar].forEach(part => {
if (part) part.classList.remove('selected');
});
element.classList.add('selected');
if (detailPartName) detailPartName.textContent = specs[key].name;
if (detailPartDesc) detailPartDesc.textContent = specs[key].desc;
if (schematicDetailCard) schematicDetailCard.classList.remove('hidden');
synth.speak(specs[key].name);
}
if (svgOrugas) svgOrugas.addEventListener('click', () => selectSchematicPart(svgOrugas, 'orugas'));
if (svgSolar) svgSolar.addEventListener('click', () => selectSchematicPart(svgSolar, 'solar'));
if (svgHangar) svgHangar.addEventListener('click', () => selectSchematicPart(svgHangar, 'hangar'));
if (btnCloseDetails) {
btnCloseDetails.addEventListener('click', () => {
[svgOrugas, svgSolar, svgHangar].forEach(part => {
if (part) part.classList.remove('selected');
});
if (schematicDetailCard) schematicDetailCard.classList.add('hidden');
});
}
// ==========================================
// 5. ROLE ACCESS CONTROL
// ==========================================
function handleProfileChange(selectedProfile) {
state.currentProfile = selectedProfile;
let profileLabelText = 'Público General';
if (selectedProfile === 'operador') profileLabelText = 'Operador Autorizado';
if (selectedProfile === 'estudiante') profileLabelText = 'Estudiante STEAM';
if (selectedProfile === 'docente') profileLabelText = 'Docente';
if (steamProfileDisplay) steamProfileDisplay.textContent = profileLabelText;
// Keep both visible so the user can see what they contain
if (teacherModule) teacherModule.classList.remove('hidden');
if (studentModule) studentModule.classList.remove('hidden');
// Toggle dashboard controls lock (unlocked for all profiles in demo mode)
const locomotionControls = [btnLocoForward, btnLocoBack, btnLocoLeft, btnLocoRight, locoSpeedSlider];
if (btnPreFlight) {
btnPreFlight.disabled = false;
btnPreFlight.style.opacity = '1';
if (state.droneStatus === 'hangar') {
btnPreFlight.textContent = 'PREPARAR DESPEGUE';
}
}
appendLog('console', `[SISTEMA] Nivel de acceso: ${profileLabelText.toUpperCase()}.`, 'success');
locomotionControls.forEach(el => { if (el) el.disabled = false; });
if (state.droneStatus === 'flying') {
unlockFlightControls();
}
}
if (profileSelect) {
profileSelect.addEventListener('change', (e) => {
handleProfileChange(e.target.value);
});
handleProfileChange(profileSelect.value);
}
// ==========================================
// 5B. ESP32 WEBSOCKET NETWORKING CLIENT
// ==========================================
let robotSocket = null;
let reconnectInterval = null;
function sendRobotCommand(payload) {
if (robotSocket && robotSocket.readyState === WebSocket.OPEN) {
try {
robotSocket.send(JSON.stringify(payload));
} catch (err) {
console.warn("Failed to transmit WebSocket payload:", err);
}
}
}
function updateRainStatusUI() {
if (rainIndicator && rainText) {
if (state.sensors.rain) {
rainIndicator.classList.add('rain-active');
rainText.textContent = 'DETECTADA';
appendLog('console', '[ALERTA] Sensor de lluvia: Precipitación activa. Humedad ascendente.', 'warning');
synth.speak('Lluvia detectada');
} else {
rainIndicator.classList.remove('rain-active');
rainText.textContent = 'NO DETECTADA';
}
}
}
function updateFlameStatusUI() {
if (flameIndicator && flameText) {
if (state.sensors.flame) {
flameIndicator.classList.remove('flame-normal');
flameIndicator.classList.add('flame-danger');
flameText.textContent = '!!! FUEGO !!!';
if (globalStatusBadge && globalStatusText) {
globalStatusBadge.className = 'system-status';
globalStatusBadge.style.background = 'rgba(255, 59, 48, 0.15)';
globalStatusBadge.style.borderColor = 'var(--accent-red)';
globalStatusText.textContent = '¡ALERTA DE RIESGO - FLAMA!';
}
appendLog('console', '[CRÍTICO] Sensor de llamas: ¡Detección de foco de incendio!', 'error');
synth.alarm(1.0);
synth.speak('Advertencia. Foco de incendio detectado.');
} else {
flameIndicator.classList.add('flame-normal');
flameIndicator.classList.remove('flame-danger');
flameText.textContent = 'NORMAL';
if (globalStatusBadge && globalStatusText) {
globalStatusBadge.style.background = '';
globalStatusBadge.style.borderColor = '';
}
updateGlobalStatusBadge();
}
}
}
// --- REAL CAMERA STREAM OV2640 & USB LOCAL CAMERA CLIENT ---
let liveStreamActive = false;
const liveCameraImage = new Image();
// USB Video DOM Elements (Created dynamically for multi-camera support)
const localVideoElement1 = document.createElement('video');
localVideoElement1.autoplay = true;
localVideoElement1.playsInline = true;
localVideoElement1.muted = true;
let localVideoStream1 = null;
const localVideoElement2 = document.createElement('video');
localVideoElement2.autoplay = true;
localVideoElement2.playsInline = true;
localVideoElement2.muted = true;
let localVideoStream2 = null;
const localVideoElement3 = document.createElement('video');
localVideoElement3.autoplay = true;
localVideoElement3.playsInline = true;
localVideoElement3.muted = true;
let localVideoStream3 = null;
liveCameraImage.onload = () => {
liveStreamActive = true;
appendLog('console', '[CAM] Transmisión de video OV2640 activa.', 'success');
};
liveCameraImage.onerror = () => {
liveStreamActive = false;
appendLog('console', '[ERROR CAM] Error al decodificar video OV2640. Verifique la RUTA.', 'error');
};
function enumerateVideoDevices(stream) {
if (navigator.mediaDevices && navigator.mediaDevices.enumerateDevices) {
navigator.mediaDevices.enumerateDevices()
.then(devices => {
const videoDevices = devices.filter(device => device.kind === 'videoinput');
if (camDeviceSelect) {
const oldVal = camDeviceSelect.value;
camDeviceSelect.innerHTML = '';
videoDevices.forEach((device, index) => {
const opt = document.createElement('option');
opt.value = device.deviceId;
opt.textContent = device.label || `Cámara USB ${index + 1}`;
camDeviceSelect.appendChild(opt);
});
if (stream) {
const activeTrack = stream.getVideoTracks()[0];
if (activeTrack) {
const settings = activeTrack.getSettings();
if (settings && settings.deviceId) {
camDeviceSelect.value = settings.deviceId;
}
}
} else if (oldVal && videoDevices.some(d => d.deviceId === oldVal)) {
camDeviceSelect.value = oldVal;
} else if (videoDevices.length > 0) {
camDeviceSelect.value = videoDevices[0].deviceId;
}
// Show device selector if we have cameras connected
if (videoDevices.length >= 1) {
if (camDeviceContainer) camDeviceContainer.classList.remove('hidden');
} else {
if (camDeviceContainer) camDeviceContainer.classList.add('hidden');
}
}
})
.catch(err => {
console.warn("Error enumerating devices:", err);
if (camDeviceContainer) camDeviceContainer.classList.add('hidden');
});
}
}
function startLiveCameraStream(preferredDeviceId = null) {
const camSource = camSourceSelect ? camSourceSelect.value : 'simulado';
// Stop old stream, but do NOT wipe dropdown options if switching device
stopLiveCameraStream(preferredDeviceId ? false : true);
if (camSource === 'esp32') {
if (camDeviceContainer) camDeviceContainer.classList.add('hidden');
const ip = robotIpInput ? robotIpInput.value.trim() : '192.168.4.1';
const camPath = cameraStreamPathInput ? cameraStreamPathInput.value.trim() : ':81/stream';
let streamUrl = '';
if (camPath.startsWith('http://') || camPath.startsWith('https://')) {
streamUrl = camPath;
} else {
streamUrl = `http://${ip}${camPath}`;
}
appendLog('console', `[CAM] Conectando a transmisión de video en ${streamUrl}...`, 'warning');
liveCameraImage.src = streamUrl;
} else if (camSource === 'usb') {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
appendLog('console', '[CAM] Inicializando cámara física USB/Tipo-C...', 'warning');
navigator.mediaDevices.enumerateDevices().then(devices => {
const videoDevices = devices.filter(d => d.kind === 'videoinput');
if (videoDevices.length === 0) {
throw new Error("No hay dispositivos de entrada de video.");
}
const devId1 = preferredDeviceId || videoDevices[0].deviceId;
const devId2 = (videoDevices.length >= 2) ? videoDevices[1].deviceId : null;
const devId3 = (videoDevices.length >= 3) ? videoDevices[2].deviceId : null;
// Request stream 1
const constraints1 = {
video: {
deviceId: { ideal: devId1 },
width: { ideal: 640 },
height: { ideal: 480 }
}
};
navigator.mediaDevices.getUserMedia(constraints1).then(stream1 => {
localVideoStream1 = stream1;
localVideoElement1.srcObject = stream1;
localVideoElement1.onloadedmetadata = () => {
localVideoElement1.play().catch(e => console.warn("Video 1 play failed:", e));
};
appendLog('console', '[CAM] Cámara 1 (Frontal) conectada con éxito.', 'success');
enumerateVideoDevices(stream1);
}).catch(err => {
console.error("Error accessing camera 1:", err);
appendLog('console', '[ERROR CAM 1] No se pudo acceder a la Cámara 1.', 'error');
});
// Request stream 2 if second device exists
if (devId2) {
const constraints2 = {
video: {
deviceId: { ideal: devId2 },
width: { ideal: 640 },
height: { ideal: 480 }
}
};
navigator.mediaDevices.getUserMedia(constraints2).then(stream2 => {
localVideoStream2 = stream2;
localVideoElement2.srcObject = stream2;
localVideoElement2.onloadedmetadata = () => {
localVideoElement2.play().catch(e => console.warn("Video 2 play failed:", e));
};
appendLog('console', '[CAM] Cámara 2 (Trasera) conectada con éxito.', 'success');
}).catch(err => {
console.error("Error accessing camera 2:", err);
});
}
// Request stream 3 if third device exists
if (devId3) {
const constraints3 = {
video: {
deviceId: { ideal: devId3 },
width: { ideal: 640 },
height: { ideal: 480 }
}
};
navigator.mediaDevices.getUserMedia(constraints3).then(stream3 => {
localVideoStream3 = stream3;
localVideoElement3.srcObject = stream3;
localVideoElement3.onloadedmetadata = () => {
localVideoElement3.play().catch(e => console.warn("Video 3 play failed:", e));
};
appendLog('console', '[CAM] Cámara 3 (Dron) conectada con éxito.', 'success');
}).catch(err => {
console.error("Error accessing camera 3:", err);
});
}
synth.speak("Cámaras USB conectadas.");
}).catch(err => {
console.error("Error setting up multi-streams:", err);
appendLog('console', '[ERROR CAM] Error al mapear cámaras USB múltiples.', 'error');
synth.speak("Error al conectar las cámaras.");
});
} else {
appendLog('console', '[ERROR CAM] La API de cámara no es compatible con este navegador.', 'error');
}
} else {
if (camDeviceContainer) camDeviceContainer.classList.add('hidden');
}
}
function stopLiveCameraStream(clearDevices = true) {
liveCameraImage.removeAttribute('src');
liveStreamActive = false;
[localVideoStream1, localVideoStream2, localVideoStream3].forEach(stream => {
if (stream) {
stream.getTracks().forEach(track => track.stop());
}
});
localVideoStream1 = null;
localVideoStream2 = null;
localVideoStream3 = null;
localVideoElement1.srcObject = null;
localVideoElement2.srcObject = null;
localVideoElement3.srcObject = null;
if (clearDevices) {
if (camDeviceSelect) camDeviceSelect.innerHTML = '';
if (camDeviceContainer) camDeviceContainer.classList.add('hidden');
}
}
// Bind change event on camera source select
if (camSourceSelect) {
camSourceSelect.addEventListener('change', () => {
const selected = camSourceSelect.value;
if (selected === 'simulado') {
stopLiveCameraStream();
appendLog('console', '[CAM] Retornando a Simulación de Telemetría Táctica.', 'info');
} else {
startLiveCameraStream();
}
});
}
// Bind change event on specific camera device select
if (camDeviceSelect) {
camDeviceSelect.addEventListener('change', () => {
const selectedDeviceId = camDeviceSelect.value;
if (selectedDeviceId) {
startLiveCameraStream(selectedDeviceId);
}
});
}
// Monitor USB device changes (Plug & Play webcams)
if (navigator.mediaDevices && navigator.mediaDevices.addEventListener) {
navigator.mediaDevices.addEventListener('devicechange', () => {
const currentSource = camSourceSelect ? camSourceSelect.value : 'simulado';
if (currentSource === 'usb') {
appendLog('console', '[CAM] Cambio de hardware detectado en puertos USB. Re-escaneando cámaras...', 'info');
enumerateVideoDevices(localVideoStream1);
}
});
}
function connectToESP32() {
if (!esp32Toggle || !esp32Toggle.checked) return;
const ip = robotIpInput ? robotIpInput.value.trim() : '192.168.4.1';
if (connStatus) {
connStatus.className = 'status-badge';
connStatus.innerHTML = `<i class="fa-solid fa-satellite-dish"></i> Buscando Nodo ESP32...`;
}
if (robotSocket) {
robotSocket.close();
robotSocket = null;
}
// Start video streaming and websocket
startLiveCameraStream();
appendLog('console', `[RED] Intentando conectar con el robot en ws://${ip}/ws...`, 'warning');
try {
robotSocket = new WebSocket(`ws://${ip}/ws`);
robotSocket.onopen = () => {
if (reconnectInterval) {
clearInterval(reconnectInterval);
reconnectInterval = null;
}
if (connStatus) {
connStatus.className = 'status-badge connected';
connStatus.innerHTML = `<i class="fa-solid fa-link"></i> Enlace Seguro Activo`;
}
if (labelSim) labelSim.classList.remove('active');
if (labelReal) labelReal.classList.add('active');
appendLog('console', `[RED] ¡Enlace establecido con el robot! Recibiendo telemetría.`, 'success');
synth.speak("Enlace WebSocket con el robot establecido con éxito.");
};
robotSocket.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.temp !== undefined) state.sensors.temperature = parseFloat(data.temp);
if (data.hum !== undefined) state.sensors.humidity = parseFloat(data.hum);
if (data.press !== undefined) state.sensors.pressure = parseInt(data.press);
if (data.ax !== undefined) state.sensors.accelX = Math.round(data.ax);
if (data.ay !== undefined) state.sensors.accelY = Math.round(data.ay);
if (data.flame !== undefined) {
state.sensors.flame = !!data.flame;
updateFlameStatusUI();
}
if (data.rain !== undefined) {
state.sensors.rain = !!data.rain;
updateRainStatusUI();
}
if (data.bat !== undefined) state.systemBattery = parseFloat(data.bat);
if (data.solar !== undefined) state.solarPower = parseFloat(data.solar);
if (data.lat !== undefined) state.sensors.gpsLat = parseFloat(data.lat);
if (data.lon !== undefined) state.sensors.gpsLon = parseFloat(data.lon);
} catch (e) {
console.warn("Error parsing incoming WebSocket frame:", e);
}
};
robotSocket.onclose = () => {
robotSocket = null;
if (connStatus) {
connStatus.className = 'status-badge';
connStatus.innerHTML = `<i class="fa-solid fa-wifi-slash"></i> Enlace Perdido`;
}
if (labelSim) labelSim.classList.add('active');
if (labelReal) labelReal.classList.remove('active');
appendLog('console', `[RED] Enlace perdido con el robot. Intentando reconexión...`, 'error');
if (esp32Toggle && esp32Toggle.checked && !reconnectInterval) {
reconnectInterval = setInterval(connectToESP32, 5000);
}
};
robotSocket.onerror = (err) => {
console.warn("WebSocket error:", err);
};
} catch (err) {
console.error("Failed to construct WebSocket client:", err);
}
}
function disconnectESP32() {
if (reconnectInterval) {
clearInterval(reconnectInterval);
reconnectInterval = null;
}
if (robotSocket) {
robotSocket.close();
robotSocket = null;
}
if (connStatus) {
connStatus.className = 'status-badge';
connStatus.innerHTML = `<i class="fa-solid fa-wifi"></i> NODO AISLADO (LOCAL)`;
}
if (labelSim) labelSim.classList.add('active');
if (labelReal) labelReal.classList.remove('active');
stopLiveCameraStream();
appendLog('console', `[RED] Enlace cerrado. Modo simulación activo.`, 'info');
synth.speak("Enlace cerrado. Simulación restaurada.");
}
if (esp32Toggle) {
esp32Toggle.addEventListener('change', () => {
if (esp32Toggle.checked) {
connectToESP32();
} else {
disconnectESP32();
}
});
}
// ==========================================
// 6. LED LIGHT SPOTLIGHT SWITCH
// ==========================================
if (ledLightSwitch) {
ledLightSwitch.addEventListener('change', (e) => {
state.headlights = e.target.checked;
if (ledLightOverlay) ledLightOverlay.classList.toggle('active', state.headlights);
if (state.headlights) {
appendLog('console', '[SISTEMA] Focos LED delanteros de alta potencia encendidos.', 'info');
synth.speak('Focos LED activados');
} else {
appendLog('console', '[SISTEMA] Focos LED apagados.', 'info');
synth.speak('Focos LED desactivados');
}
sendRobotCommand({ type: "lights", state: state.headlights });
});
}
// ==========================================
// 7. CAMERA CANVAS DRAWS & AI RADAR HUDS
// ==========================================
const ctxFront = canvasFrontal ? canvasFrontal.getContext('2d') : null;
const ctxRear = canvasTrasera ? canvasTrasera.getContext('2d') : null;
const ctxDrone = canvasDrone ? canvasDrone.getContext('2d') : null;
function resizeCanvases() {
[canvasFrontal, canvasTrasera, canvasDrone].forEach(canvas => {
if (canvas && canvas.parentElement) {
canvas.width = canvas.parentElement.clientWidth;
canvas.height = canvas.parentElement.clientHeight;
}
});
}
window.addEventListener('resize', resizeCanvases);
setTimeout(resizeCanvases, 200);
let frameCount = 0;
function drawCameraFeeds() {
frameCount++;
if (canvasFrontal && ctxFront) {
const wF = canvasFrontal.width;
const hF = canvasFrontal.height;
if (wF > 0 && hF > 0) {
let drewRealCamera = false;
const camSource = camSourceSelect ? camSourceSelect.value : 'simulado';
if (state.droneStatus !== 'flying') {
if (camSource === 'esp32' && liveStreamActive) {
try {
ctxFront.drawImage(liveCameraImage, 0, 0, wF, hF);
drewRealCamera = true;
} catch (e) {
// fallback
}
} else if (camSource === 'usb' && localVideoStream1 && localVideoElement1.readyState >= 2) {
try {
ctxFront.drawImage(localVideoElement1, 0, 0, wF, hF);
drewRealCamera = true;
} catch (e) {
// fallback
}
}
}
if (!drewRealCamera) {
ctxFront.fillStyle = '#020308';
ctxFront.fillRect(0, 0, wF, hF);
ctxFront.strokeStyle = 'rgba(0, 240, 255, 0.12)';
ctxFront.lineWidth = 1;
ctxFront.beginPath();
ctxFront.moveTo(0, hF * 0.6);
ctxFront.lineTo(wF, hF * 0.6);
ctxFront.moveTo(wF * 0.5, hF * 0.6);
ctxFront.lineTo(wF * 0.1, hF);
ctxFront.moveTo(wF * 0.5, hF * 0.6);
ctxFront.lineTo(wF * 0.9, hF);
ctxFront.stroke();
ctxFront.fillStyle = 'rgba(0, 240, 255, 0.01)';
ctxFront.strokeStyle = 'rgba(0, 240, 255, 0.18)';
ctxFront.beginPath();
ctxFront.rect(wF * 0.08, hF * 0.25, wF * 0.22, hF * 0.35);
ctxFront.rect(wF * 0.72, hF * 0.18, wF * 0.22, hF * 0.42);
ctxFront.fill();
ctxFront.stroke();
ctxFront.strokeStyle = 'rgba(0, 240, 255, 0.3)';
ctxFront.beginPath();
ctxFront.moveTo(wF * 0.45, hF * 0.5);
ctxFront.lineTo(wF * 0.47, hF * 0.55);
ctxFront.lineTo(wF * 0.46, hF * 0.62);
ctxFront.lineTo(wF * 0.49, hF * 0.7);
ctxFront.stroke();
}
const jitterX = Math.sin(frameCount * 0.1) * (state.sensors.accelX / 10);
const jitterY = Math.cos(frameCount * 0.1) * (state.sensors.accelY / 10);
if (aiBoxFrontal) {