-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
3781 lines (3309 loc) · 146 KB
/
Copy pathmainwindow.cpp
File metadata and controls
3781 lines (3309 loc) · 146 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
/**
* @file mainwindow.cpp
* @brief Implementación de la lógica de control, comunicaciones y telemetría de MainWindow.
* @author Gonzalo Gomez
* @date 2026
*
* @details Este archivo implementa las funciones de negocio de la estación terrena:
* - Configuración del entorno gráfico, gráficos QChart y enlace QML 3D.
* - Despacho de paquetes mediante protocolo UNER a través de Serial, UDP y TCP.
* - Decodificación de flujos de telemetría y actualización de indicadores en tiempo real.
* - Gestión de atajos de teclado y eventos interactivos para el modo Joystick / GoTo.
*
* @see mainwindow.h
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "internal_data.h"
#include <limits>
#include <QSpinBox>
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QDateTime>
#include <QtWidgets/QGraphicsLayout>
#include <QListWidget>
static bool isWaitingReply = false;
static int timeoutPatience = 0;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
myDebugDialog = new QDialog(this);
myDebugDialog->setWindowTitle("WIFI");
myDebugDialog->setWindowFlags(Qt::Window);
myDebugDialog->setStyleSheet(this->styleSheet());
ui->stackedWidget->removeWidget(ui->DEBUG_PAGE);
QVBoxLayout *debugLayout = new QVBoxLayout(myDebugDialog);
debugLayout->setContentsMargins(0, 0, 0, 0);
debugLayout->addWidget(ui->DEBUG_PAGE);
ui->DEBUG_PAGE->show();
myDebugDialog->adjustSize();
myHelpDialog = new QDialog(this);
myHelpDialog->setWindowTitle("HELP - MCC25");
myHelpDialog->setWindowFlags(Qt::Window);
myHelpDialog->setStyleSheet(this->styleSheet());
ui->stackedWidget->removeWidget(ui->HELP_PAGE);
QVBoxLayout *helpLayout = new QVBoxLayout(myHelpDialog);
helpLayout->setContentsMargins(0, 0, 0, 0);
helpLayout->addWidget(ui->HELP_PAGE);
ui->HELP_PAGE->show();
myHelpDialog->resize(720, 560);
myPasswordDialog = new QDialog(this);
myPasswordDialog->setWindowTitle("ACCESO A CONFIGURACIÓN");
myPasswordDialog->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
myPasswordDialog->setModal(true);
myPasswordDialog->setStyleSheet(this->styleSheet());
ui->stackedWidget->removeWidget(ui->PASSWORD_PAGE);
QVBoxLayout *passwordLayout = new QVBoxLayout(myPasswordDialog);
passwordLayout->setContentsMargins(0, 0, 0, 0);
passwordLayout->addWidget(ui->PASSWORD_PAGE);
ui->PASSWORD_PAGE->show();
myPasswordDialog->resize(440, 260);
connect(ui->lineEdit_configPassword, &QLineEdit::returnPressed, this, &MainWindow::on_btn_password_accept_clicked, Qt::UniqueConnection);
connect(ui->lineEdit_configPassword, &QLineEdit::textEdited, this, &MainWindow::resetPasswordDialogStyle, Qt::UniqueConnection);
connect(ui->btn_password_cancel, &QPushButton::clicked, this, &MainWindow::on_btn_password_cancel_clicked, Qt::UniqueConnection);
connect(ui->btn_password_retry, &QPushButton::clicked, this, &MainWindow::on_btn_password_retry_clicked, Qt::UniqueConnection);
connect(ui->btn_password_error_cancel, &QPushButton::clicked, this, &MainWindow::on_btn_password_cancel_clicked, Qt::UniqueConnection);
ui->btn_password_cancel->setAutoDefault(false);
ui->btn_password_cancel->setDefault(false);
ui->btn_password_error_cancel->setAutoDefault(false);
ui->btn_password_error_cancel->setDefault(false);
ui->btn_password_accept->setAutoDefault(true);
ui->btn_password_accept->setDefault(true);
ui->btn_password_retry->setAutoDefault(true);
ui->btn_password_retry->setDefault(true);
myJoystickExitDialog = new QDialog(this);
myJoystickExitDialog->setWindowTitle("MODO JOYSTICK ACTIVO");
myJoystickExitDialog->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
myJoystickExitDialog->setModal(true);
myJoystickExitDialog->setStyleSheet(this->styleSheet());
ui->stackedWidget->removeWidget(ui->JOYSTICK_EXIT_PAGE);
QVBoxLayout *joystickExitLayout = new QVBoxLayout(myJoystickExitDialog);
joystickExitLayout->setContentsMargins(0, 0, 0, 0);
joystickExitLayout->addWidget(ui->JOYSTICK_EXIT_PAGE);
ui->JOYSTICK_EXIT_PAGE->show();
myJoystickExitDialog->resize(440, 220);
connect(ui->btn_joystick_exit_cancel, &QPushButton::clicked, this, &MainWindow::on_btn_joystick_exit_cancel_clicked, Qt::UniqueConnection);
connect(ui->btn_joystick_exit_confirm, &QPushButton::clicked, this, &MainWindow::on_btn_joystick_exit_confirm_clicked, Qt::UniqueConnection);
initHelpContent();
connect(ui->actionHELP, &QAction::triggered, this, &MainWindow::on_actionDocu_triggered);
// Limitar los logs a los últimos 50 comandos
ui->textBrowserProcessed->document()->setMaximumBlockCount(50);
ui->textBrowserUnProcessed->document()->setMaximumBlockCount(50);
initPIDChart();
// Conectar checkboxes para activar/desactivar curvas de la gráfica PID
connect(ui->checkBox_P, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_I, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_D, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Out, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_P_line, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_D_line, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Out_line, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Pitch, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Roll, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Yaw, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ax, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ay, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Az, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Gx, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Gy, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Gz, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir1, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir2, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir3, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir4, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir5, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir6, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir7, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
connect(ui->checkBox_Ir8, &QCheckBox::toggled, this, &MainWindow::updatePIDChartRange);
timer1 = new QTimer(this);
timer2 = new QTimer(this);
// Inicializar barras de progreso de sensores
ui->bar_ir1->setValue(100); ui->bar_ir1->setFormat("Libre (100%)");
ui->bar_ir3->setValue(100); ui->bar_ir3->setFormat("Libre (100%)");
ui->bar_ir5->setValue(100); ui->bar_ir5->setFormat("Libre (100%)");
ui->bar_ir7->setValue(100); ui->bar_ir7->setFormat("Libre (100%)");
ui->bar_ir8->setValue(100); ui->bar_ir8->setFormat("Libre (100%)");
ui->bar_ir2->setValue(0); ui->bar_ir2->setFormat("0 / 4095");
ui->bar_ir4->setValue(0); ui->bar_ir4->setFormat("0 / 4095");
ui->bar_ir6->setValue(0); ui->bar_ir6->setFormat("0 / 4095");
// Configurar foco seguro para MainWindow
this->setFocusPolicy(Qt::StrongFocus);
// Desactivar autoExclusive y foco en los botones de navegación y modos para que las flechas jamás cambien de pestaña
ui->btn_nav_infrarrojos->setAutoExclusive(false);
ui->btn_nav_visualizacion->setAutoExclusive(false);
ui->btn_nav_tuning->setAutoExclusive(false);
ui->btn_nav_goto->setAutoExclusive(false);
ui->btn_mode_balance->setAutoExclusive(false);
ui->btn_mode_line->setAutoExclusive(false);
ui->btn_mode_dodge->setAutoExclusive(false);
ui->btn_mode_goto->setAutoExclusive(false);
ui->btn_nav_infrarrojos->setFocusPolicy(Qt::NoFocus);
ui->btn_nav_visualizacion->setFocusPolicy(Qt::NoFocus);
ui->btn_nav_tuning->setFocusPolicy(Qt::NoFocus);
ui->btn_nav_goto->setFocusPolicy(Qt::NoFocus);
ui->btn_mode_balance->setFocusPolicy(Qt::NoFocus);
ui->btn_mode_line->setFocusPolicy(Qt::NoFocus);
ui->btn_mode_dodge->setFocusPolicy(Qt::NoFocus);
ui->btn_mode_goto->setFocusPolicy(Qt::NoFocus);
// Conexiones de controles del Modo Joystick
if (ui->btn_goto_up) connect(ui->btn_goto_up, &QPushButton::clicked, this, &MainWindow::on_btn_goto_up_clicked);
if (ui->btn_goto_down) connect(ui->btn_goto_down, &QPushButton::clicked, this, &MainWindow::on_btn_goto_down_clicked);
if (ui->btn_goto_left) {
connect(ui->btn_goto_left, &QPushButton::pressed, this, &MainWindow::on_btn_goto_left_pressed);
connect(ui->btn_goto_left, &QPushButton::released, this, &MainWindow::on_btn_goto_left_released);
}
if (ui->btn_goto_right) {
connect(ui->btn_goto_right, &QPushButton::pressed, this, &MainWindow::on_btn_goto_right_pressed);
connect(ui->btn_goto_right, &QPushButton::released, this, &MainWindow::on_btn_goto_right_released);
}
if (ui->btn_goto_center) connect(ui->btn_goto_center, &QPushButton::clicked, this, &MainWindow::on_btn_goto_center_clicked);
if (ui->spinBox_gotoStep) {
connect(ui->spinBox_gotoStep, QOverload<double>::of(&QDoubleSpinBox::valueChanged),
this, &MainWindow::on_spinBox_gotoStep_valueChanged);
}
if (ui->spinBox_gotoTurnIntensity) {
connect(ui->spinBox_gotoTurnIntensity, QOverload<int>::of(&QSpinBox::valueChanged),
this, &MainWindow::on_spinBox_gotoTurnIntensity_valueChanged);
}
if (ui->spinBox_gotoTurnDuration) {
connect(ui->spinBox_gotoTurnDuration, QOverload<int>::of(&QSpinBox::valueChanged),
this, &MainWindow::on_spinBox_gotoTurnDuration_valueChanged);
}
if (ui->btn_goto_reset_yaw) {
connect(ui->btn_goto_reset_yaw, &QPushButton::clicked, this, &MainWindow::on_btn_goto_reset_yaw_clicked);
}
m_gotoTurnKeepAliveTimer = new QTimer(this);
m_gotoTurnKeepAliveTimer->setInterval(100);
connect(m_gotoTurnKeepAliveTimer, &QTimer::timeout, this, [this]() {
if (m_isRotatingLeft) sendGoToTurn(m_gotoTurnIntensity, m_gotoTurnDuration);
else if (m_isRotatingRight) sendGoToTurn(-m_gotoTurnIntensity, m_gotoTurnDuration);
});
connect(ui->stackedWidget, &QStackedWidget::currentChanged, this, &MainWindow::updateNavSelection);
ui->stackedWidget->setCurrentIndex(0);
updateNavSelection(0);
ui->AutoWidget->setSource(QUrl(QStringLiteral("qrc:/Scene3D.qml")));
ui->AutoWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
connect(ui->AutoWidget, &QQuickWidget::statusChanged, this, [this](QQuickWidget::Status status) {
if (status == QQuickWidget::Ready) {
update3DModelConnectionState(isRobotConnected());
}
});
// Integración de Brújula de Orientación
m_compassWidget = new CompassWidget(this);
if (ui->layout_compass_dial) {
ui->layout_compass_dial->addWidget(m_compassWidget);
}
//comunicacion
QSerialPort1 = new QSerialPort(this);
QUdpSocket1 = new QUdpSocket(this);
QTcpServer1 = new QTcpServer(this);
QTcpSocketClient = nullptr;
//debug de comandos
ui->comboBox_PORT->installEventFilter(this);
qApp->installEventFilter(this);
//connects del puerto serial
connect(QSerialPort1,&QSerialPort::readyRead,this,&MainWindow::dataReceived);
//connects de los timers con las funciones
connect(timer1,&QTimer::timeout,this,&MainWindow::timeOut);
connect(timer2,&QTimer::timeout,this,&MainWindow::getData);
//connects de udp/tcp
connect(QUdpSocket1,&QUdpSocket::readyRead,this,&MainWindow::OnUdpRxData);
connect(QTcpServer1,&QTcpServer::newConnection,this,&MainWindow::OnTcpNewConnection);
//connect(ui->actionScanPorts, &QAction::triggered, settingPorts,&SettingsDialog::show);
//inicializamos
estadoProtocolo=START;
rxData.timeOut=0;
timer2->start(75);
statusMode = ui->label_statusMode;
ui->statusBar->addWidget(statusMode);
statusMode->setText("ESTADO --> DESCONECTADO");
statusMode->setStyleSheet("color: #fd5d93; font-weight: bold; font-size: 11px; padding-left: 5px;");
runtimeTimer.start();
timer1->start(100);
timer2->start(35);
// Permitir valores de hasta 10000 (y -10000) en todos los QSpinBox
QList<QSpinBox *> spinBoxes = this->findChildren<QSpinBox *>();
for (QSpinBox *spinBox : spinBoxes) {
spinBox->setMinimum(-10000);
spinBox->setMaximum(10000);
}
// Iniciar desconectado por defecto (requerimiento de usuario)
ui->pushButton_connectUdp->setText("CONNECT");
updateProtocolUI();
// Inicializar lista de comandos individuales
if (ui->comboBox_CMD) {
ui->comboBox_CMD->clear();
ui->comboBox_CMD->addItem("GETALIVE (0xA0)", GETALIVE);
ui->comboBox_CMD->addItem("GETFIRMWARE (0xA1)", GETFIRMWARE);
ui->comboBox_CMD->addItem("GETMPU (0xA2)", GETMPU);
ui->comboBox_CMD->addItem("GETADC (0xA3)", GETADC);
ui->comboBox_CMD->addItem("GETINTERNALDATA (0xF0)", GETINTERNALDATA);
ui->comboBox_CMD->addItem("GETPIDBALANCE (0xF1)", GETPIDBALANCE);
ui->comboBox_CMD->addItem("EXPORTIRCSV (0xD3)", EXPORTIRCSV);
ui->comboBox_CMD->addItem("SETPWML (0xA4)", SETPWML);
ui->comboBox_CMD->addItem("SETPWMR (0xA5)", SETPWMR);
ui->comboBox_CMD->addItem("SETPWMMINL (0xA7)", SETPWMMINL);
ui->comboBox_CMD->addItem("SETPWMMINR (0xA6)", SETPWMMINR);
ui->comboBox_CMD->addItem("SETBALANCEKP (0xA8)", SETBALANCEKP);
ui->comboBox_CMD->addItem("SETBALANCEKD (0xA9)", SETBALANCEKD);
ui->comboBox_CMD->addItem("SETBALANCEKI (0xAA)", SETBALANCEKI);
ui->comboBox_CMD->addItem("SETSETPOINT (0xAB)", SETSETPOINT);
ui->comboBox_CMD->addItem("SETSPEED (0xB1)", SETSPEED);
ui->comboBox_CMD->addItem("SETBKANG (0xB2)", SETBKANG);
ui->comboBox_CMD->addItem("SETSTATICOFF (0xC1)", SETSTATICOFF);
ui->comboBox_CMD->addItem("SETMOVINGOFF (0xC2)", SETMOVINGOFF);
ui->comboBox_CMD->addItem("SETLIMITANG (0xC4)", SETLIMITANG);
ui->comboBox_CMD->addItem("SET_KP_EXT (0xC3)", SET_KP_EXT);
ui->comboBox_CMD->addItem("SET_KI_EXT (0xC5)", SET_KI_EXT);
ui->comboBox_CMD->addItem("SET_ALFA_LPF (0xC6)", SET_ALFA_LPF);
ui->comboBox_CMD->addItem("SETVELDAMPDIV (0xC7)", SETVELDAMPDIV);
ui->comboBox_CMD->addItem("SETVELDAMPLIM (0xC8)", SETVELDAMPLIM);
ui->comboBox_CMD->addItem("SETTURNLIMIT (0xC9)", SETTURNLIMIT);
ui->comboBox_CMD->addItem("SETLINEKP (0xAC)", SETLINEKP);
ui->comboBox_CMD->addItem("SETLINEKD (0xAD)", SETLINEKD);
ui->comboBox_CMD->addItem("SETOFFSETL (0xAE)", SETOFFSETL);
ui->comboBox_CMD->addItem("SETOFFSETR (0xAF)", SETOFFSETR);
ui->comboBox_CMD->addItem("SETCUSTOMTURN (0xB0)", SETCUSTOMTURN);
ui->comboBox_CMD->addItem("SETFRONTDIST (0xB3)", SETFRONTDIST);
ui->comboBox_CMD->addItem("SETSIDEDIST (0xB4)", SETSIDEDIST);
ui->comboBox_CMD->addItem("SETLOSTDIST (0xB5)", SETLOSTDIST);
ui->comboBox_CMD->addItem("SETSTOPCYCLES (0xB6)", SETSTOPCYCLES);
ui->comboBox_CMD->addItem("SETCORNERDIST (0xB7)", SETCORNERDIST);
ui->comboBox_CMD->addItem("SETALIGNDIST (0xB8)", SETALIGNDIST);
ui->comboBox_CMD->addItem("SETPWMLROT (0xB9)", SETPWMLROT);
ui->comboBox_CMD->addItem("SETPWMRROT (0xC0)", SETPWMRROT);
ui->comboBox_CMD->addItem("SETWALLKP (0xCB)", SETWALLKP);
ui->comboBox_CMD->addItem("SETWALLKD (0xCC)", SETWALLKD);
ui->comboBox_CMD->addItem("SETFRONTKP (0xCD)", SETFRONTKP);
ui->comboBox_CMD->addItem("SETFRONTKD (0xCE)", SETFRONTKD);
ui->comboBox_CMD->addItem("SETDODGEMODE (0xCF)", SETDODGEMODE);
ui->comboBox_CMD->addItem("SETROBOTMODE (0xD2)", SETROBOTMODE);
ui->comboBox_CMD->addItem("SETJOYSTICKTURN (0xD3)", SETGOTOTURN);
ui->comboBox_CMD->addItem("SETDODGEBIASTIME (0xD4)", SETDODGEBIASTIME);
ui->comboBox_CMD->addItem("SETDODGEBIASMULT (0xD5)", SETDODGEBIASMULT);
connect(ui->comboBox_CMD, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::on_comboBox_CMD_currentIndexChanged);
on_comboBox_CMD_currentIndexChanged(0);
}
if (ui->spinBox_cmdParam) {
ui->spinBox_cmdParam->setSingleStep(1);
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::addLogEntry(const QString &data, const QString &type) {
LogEntry entry;
entry.time = QDateTime::currentDateTime();
entry.data = data;
entry.type = type;
m_logHistory.append(entry);
if (type == "UNKNOWN") m_countUnknown++;
else if (type == "CHK_ERROR") m_countChecksumErrors++;
cleanOldLogs();
}
void MainWindow::cleanOldLogs() {
QDateTime fiveMinutesAgo = QDateTime::currentDateTime().addSecs(-300);
while (!m_logHistory.isEmpty() && m_logHistory.first().time < fiveMinutesAgo) {
m_logHistory.removeFirst();
}
}
void MainWindow::on_pushButton_exportExcel_clicked() {
QString fileName = QFileDialog::getSaveFileName(this, "Exportar Historial (Excel/CSV)",
"log_robot_" + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + ".csv",
"Archivos CSV (*.csv)");
if (fileName.isEmpty()) return;
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::critical(this, "Error", "No se pudo crear el archivo.");
return;
}
QTextStream out(&file);
int lost = (m_countSent > m_countReceived) ? (m_countSent - m_countReceived) : 0;
out << "TIEMPO;TIPO;DATO;ESTADISTICAS\n";
out << ";;;Enviados: " << m_countSent << "\n";
out << ";;;Recibidos: " << m_countReceived << "\n";
out << ";;;Perdidos: " << lost << "\n";
out << ";;;Desconocidos: " << m_countUnknown << "\n";
out << ";;;Errores Checksum: " << m_countChecksumErrors << "\n\n";
out << "TIEMPO;TIPO;DATO\n";
for (const auto &entry : m_logHistory) {
QString cleanData = entry.data;
cleanData.replace("\n", " ").replace(";", ",");
out << entry.time.toString("hh:mm:ss.zzz") << ";" << entry.type << ";" << cleanData << "\n";
}
file.close();
QMessageBox::information(this, "Exportación Exitosa",
QString("Se han exportado %1 registros de los últimos 5 minutos.").arg(m_logHistory.size()));
}
void MainWindow::on_pushButton_exportTxt_clicked() {
QString fileName = QFileDialog::getSaveFileName(this, "Exportar Historial (Texto Plano)",
"log_robot_" + QDateTime::currentDateTime().toString("yyyyMMdd_HHmmss") + ".txt",
"Archivos de Texto (*.txt)");
if (fileName.isEmpty()) return;
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::critical(this, "Error", "No se pudo crear el archivo.");
return;
}
QTextStream out(&file);
int lost = (m_countSent > m_countReceived) ? (m_countSent - m_countReceived) : 0;
out << "====================================================\n";
out << " REPORTE DE ACTIVIDAD DEL ROBOT\n";
out << " Generado el: " << QDateTime::currentDateTime().toString("dd/MM/yyyy HH:mm:ss") << "\n";
out << "====================================================\n\n";
out << "ESTADISTICAS (Ultimos 5 minutos):\n";
out << "----------------------------------------------------\n";
out << " Comandos Enviados: " << m_countSent << "\n";
out << " Comandos Recibidos: " << m_countReceived << "\n";
out << " Comandos Perdidos: " << lost << "\n";
out << " Comandos Desconocidos: " << m_countUnknown << "\n";
out << " Errores de Checksum: " << m_countChecksumErrors << "\n";
out << "----------------------------------------------------\n\n";
out << "DETALLE DE LOGS:\n";
out << "TIMESTAMP | TIPO | DATO\n";
out << "-------------|-----------|--------------------------\n";
for (const auto &entry : m_logHistory) {
out << entry.time.toString("hh:mm:ss.zzz").leftJustified(12) << " | "
<< entry.type.leftJustified(9) << " | "
<< entry.data.simplified() << "\n";
}
out << "\n--- Fin del reporte ---";
file.close();
QMessageBox::information(this, "Exportación Exitosa", "Historial exportado correctamente a .txt");
}
void MainWindow::dataReceived(){
unsigned char *incomingBuffer;
int count;
//uint8_t xId;
count = QSerialPort1->bytesAvailable();
if(count<=0)
return;
incomingBuffer = new unsigned char[count];
QSerialPort1->read((char *)incomingBuffer,count);
QString str="";
for(int i=0; i<count; i++){
if(isalnum(incomingBuffer[i]))
str = str + QString("%1").arg((char)incomingBuffer[i]);
else
str = str +"{" + QString("%1").arg(incomingBuffer[i],2,16,QChar('0')) + "}";
}
addLogEntry("MBED-->SERIAL-->PC (" + str + ")", "RX");
ui->textBrowserUnProcessed->append("MBED-->SERIAL-->PC (" + str + ")");
//Cada vez que se recibe un dato reinicio el timeOut
rxData.timeOut=6;
m_lastRxTime = QDateTime::currentMSecsSinceEpoch();
for(int i=0;i<count; i++){
switch (estadoProtocolo) {
case START:
if (incomingBuffer[i]=='U'){
estadoProtocolo=HEADER_1;
}
break;
case HEADER_1:
if (incomingBuffer[i]=='N')
estadoProtocolo=HEADER_2;
else{
i--;
estadoProtocolo=START;
}
break;
case HEADER_2:
if (incomingBuffer[i]=='E')
estadoProtocolo=HEADER_3;
else{
i--;
estadoProtocolo=START;
}
break;
case HEADER_3:
if (incomingBuffer[i]=='R')
estadoProtocolo=NBYTES;
else{
i--;
estadoProtocolo=START;
}
break;
case NBYTES:
rxData.nBytes=incomingBuffer[i];
estadoProtocolo=TOKEN;
break;
case TOKEN:
if (incomingBuffer[i]==':'){
estadoProtocolo=PAYLOAD;
rxData.cheksum='U'^'N'^'E'^'R'^ rxData.nBytes^':';
rxData.payLoad[0]=rxData.nBytes;
rxData.index=1;
}
else{
i--;
estadoProtocolo=START;
}
break;
case PAYLOAD:
if (rxData.nBytes>1){
rxData.payLoad[rxData.index++]=incomingBuffer[i];
rxData.cheksum^=incomingBuffer[i];
}
rxData.nBytes--;
if(rxData.nBytes==0){
estadoProtocolo=START;
if(rxData.cheksum==incomingBuffer[i]){
decodeData(&rxData.payLoad[0], SERIE);
}else{
addLogEntry("Chk Calculado ** " +QString().number(rxData.cheksum,16) + " **", "CHK_ERROR");
ui->textBrowserUnProcessed->append("Chk Calculado ** " +QString().number(rxData.cheksum,16) + " **" );
addLogEntry("Chk recibido ** " +QString().number(incomingBuffer[i],16) + " **", "CHK_ERROR");
ui->textBrowserUnProcessed->append("Chk recibido ** " +QString().number(incomingBuffer[i],16) + " **" );
}
}
break;
default:
estadoProtocolo=START;
break;
}
}
delete [] incomingBuffer;
}
static const uint16_t PC_LUT_Y_SCALE[16] = {0, 67, 133, 200, 267, 333, 400, 467, 533, 600, 667, 733, 800, 867, 933, 1000};
// (LUTs de PC para sensores superiores eliminadas para usar valores crudos directamente)
[[maybe_unused]] static uint16_t PC_LUT_Interpolate(const uint16_t *x, const uint16_t *lut_y, uint16_t raw) {
if(raw <= x[0])
return lut_y[0];
if(raw >= x[15])
return lut_y[15];
for(int i = 0; i < 15; i++) {
if(raw >= x[i] && raw <= x[i + 1]) {
uint32_t diff_x = x[i + 1] - x[i];
if (diff_x == 0) return lut_y[i];
uint32_t diff_y = lut_y[i + 1] - lut_y[i];
uint32_t offset_x = raw - x[i];
uint32_t y = lut_y[i] + (((offset_x * diff_y) + (diff_x / 2)) / diff_x);
return (uint16_t)y;
}
}
return lut_y[15];
}
void MainWindow::decodeData(uint8_t *datosRx, uint8_t source){
m_countReceived++; // Comando completo y válido recibido
//int32_t length = sizeof(*datosRx)/sizeof(datosRx[0]);
int32_t length = datosRx[0];
uint8_t id = datosRx[1];
QString str, strOut;
_udat w;
// --- SEMÁFORO PING-PONG ---
// Solo liberamos el semáforo si la respuesta pertenece a un comando solicitado (MPU, ADC, etc).
// El heartbeat ALIVE es autónomo del STM32, NO debe liberar el semáforo
// porque no fue una respuesta a algo que nosotros pedimos.
if (id != GETALIVE) {
isWaitingReply = false;
}
for(int i = 1; i<length; i++){
if(isalnum(datosRx[i]))
str = str + QString("%1").arg(char(datosRx[i]));
else
str = str +QString("%1").arg(datosRx[i],2,16,QChar('0'));
}
addLogEntry("*(MBED-S->PC)->decodeData (" + str + ")", "RX");
ui->textBrowserUnProcessed->append("*(MBED-S->PC)->decodeData (" + str + ")");
str=QString().number(datosRx[0]);
addLogEntry(str, "RX");
ui->textBrowserProcessed->append(str);
str=QString().number(datosRx[1]);
addLogEntry(str, "RX");
ui->textBrowserProcessed->append(str);
switch (datosRx[1]) {
case GETALIVE:// GETALIVE=0xF0,
if(datosRx[2]==ACK){
contadorAlive++;
if(source)
str="ALIVE BLUEPILL VIA *SERIE* RECIBIDO!!!";
else{
str="ALIVE BLUEPILL VIA *UDP* RECIBIDO N°: " + QString().number(contadorAlive,10);
}
}else{
str= "ALIVE BLUEPILL VIA *SERIE* NO ACK!!!";
}
addLogEntry(str, "RX");
ui->textBrowserProcessed->append(str);
break;
case GETFIRMWARE:// GETFIRMWARE=0xF1
str = "FIRMWARE: ";
for(uint8_t i=0;i<(datosRx[0]-2);i++){ //datosRx[0] -> tamaño en bytes del mensaje.
str += (QChar)datosRx[2+i];
}
addLogEntry(str, "RX");
ui->textBrowserProcessed->append(str);
break;
case GETMPU:{
//Datos acelerometro
w.i8[0] = datosRx[2];
w.i8[1] = datosRx[3];
float ax = w.i16[0];
str = QString("%1").arg(w.i16[0], 5, 10, QChar('0'));
strOut = "Ax: " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ax_data->display(str);
/// setText(str);
w.i8[0] = datosRx[4];
w.i8[1] = datosRx[5];
float ay = w.i16[0];
str = QString("%1").arg(w.i16[0], 5, 10, QChar('0'));
strOut = "Ay: " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ay_data->display(str);
w.i8[0] = datosRx[6];
w.i8[1] = datosRx[7];
float az = w.i16[0];
str = QString("%1").arg(w.i16[0], 5, 10, QChar('0'));
strOut = "Az: " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->az_data->display(str);
//Datos giroscopio
w.i8[0] = datosRx[8];
w.i8[1] = datosRx[9];
float gx = w.i16[0];
str = QString("%1").arg(w.i16[0], 5, 10, QChar('0'));
strOut = "Gx: " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->gx_data->display(str);
w.i8[0] = datosRx[10];
w.i8[1] = datosRx[11];
float gy = w.i16[0];
str = QString("%1").arg(w.i16[0], 5, 10, QChar('0'));
strOut = "Gy: " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->gy_data->display(str);
w.i8[0] = datosRx[12];
w.i8[1] = datosRx[13];
float gz = w.i16[0];
str = QString("%1").arg(w.i16[0], 5, 10, QChar('0'));
strOut = "Gz: " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->gz_data->display(str);
// 1. Delta-time real entre paquetes MPU
static double lastMpuTimestamp = -1.0;
double t = runtimeTimer.elapsed() / 1000.0;
double dt = (lastMpuTimestamp >= 0.0) ? (t - lastMpuTimestamp) : 0.0;
lastMpuTimestamp = t;
// 2. Calcular ángulos
float pitch = atan2(ay, sqrt(ax * ax + az * az)) * 180.0 / M_PI;
float roll = atan2(-ax, sqrt(ay * ay + az * az)) * 180.0 / M_PI;
// 3. Integración precisa de Yaw con el dt real medido
float gz_grados_seg = gz / 131.0f; // Asumiendo escala de +/- 250deg/s (131 LSB/(°/s))
if (std::abs(gz_grados_seg) > 1.2f && dt > 0.0 && dt < 0.5) {
yawAcumulado += gz_grados_seg * static_cast<float>(dt);
}
m_gotoRelativeYaw = yawAcumulado - m_gotoStartYaw;
updateGoToAngleDisplays();
// Imprimir los ángulos finales en la consola de Qt Creator
qDebug() << "Angulos Calculados -> Pitch:" << pitch << " | Roll:" << roll << " | Yaw:" << yawAcumulado << " | dt:" << dt;
// ---- Enviar a la gráfica ----
updateMPUChart(t, ax, ay, az, gx, gy, gz, pitch, roll, yawAcumulado);
// 4. Enviar los ángulos a Qt Quick 3D
if (ui->AutoWidget && ui->AutoWidget->rootObject()) {
ui->AutoWidget->rootObject()->setProperty("carPitch", pitch);
ui->AutoWidget->rootObject()->setProperty("carRoll", roll);
ui->AutoWidget->rootObject()->setProperty("carYaw", yawAcumulado);
}
m_lastMpuTime = QDateTime::currentMSecsSinceEpoch();
update3DModelConnectionState(true);
// 5. Actualizar la Brújula de Orientación (rumbo náutico horario: Este = +90°, Oeste = 270°)
if (m_compassWidget) {
m_compassWidget->setHeading(-yawAcumulado);
}
break;
}
case GETADC: {
int16_t sumLineSensors = 0;
//Datos acelerometro
w.ui8[0] = datosRx[2];
w.ui8[1] = datosRx[3];
uint16_t ir1 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR0 (Der 90°): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir1_data->display(str);
double dist1 = adcToDistanceCm(ir1);
ui->ir1_cm_data->display(QString::number(dist1, 'f', 1));
int pct1 = (dist1 >= 80.0) ? 100 : qBound(0, (int)((dist1 / 80.0) * 100.0), 100);
ui->bar_ir1->setValue(pct1);
ui->bar_ir1->setFormat((dist1 >= 80.0) ? QString("Libre (100%)") : QString("%1 cm (%2%)").arg(dist1, 0, 'f', 1).arg(pct1));
w.ui8[0] = datosRx[4];
w.ui8[1] = datosRx[5];
uint16_t ir2 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR1 (Línea Izq): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir2_data->display(str);
ui->bar_ir2->setValue(ir2);
ui->bar_ir2->setFormat(QString("%1 / 4095").arg(ir2));
sumLineSensors += qMax(0, 2400 - w.i16[0]);
w.ui8[0] = datosRx[6];
w.ui8[1] = datosRx[7];
uint16_t ir3 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR2 (Izq 90°): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir3_data->display(str);
double dist3 = adcToDistanceCm(ir3);
ui->ir3_cm_data->display(QString::number(dist3, 'f', 1));
int pct3 = (dist3 >= 80.0) ? 100 : qBound(0, (int)((dist3 / 80.0) * 100.0), 100);
ui->bar_ir3->setValue(pct3);
ui->bar_ir3->setFormat((dist3 >= 80.0) ? QString("Libre (100%)") : QString("%1 cm (%2%)").arg(dist3, 0, 'f', 1).arg(pct3));
w.ui8[0] = datosRx[8];
w.ui8[1] = datosRx[9];
uint16_t ir4 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR3 (Línea Cen): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir4_data->display(str);
ui->bar_ir4->setValue(ir4);
ui->bar_ir4->setFormat(QString("%1 / 4095").arg(ir4));
sumLineSensors += qMax(0, 2400 - w.i16[0]);
w.ui8[0] = datosRx[10];
w.ui8[1] = datosRx[11];
uint16_t ir5 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR4 (Izq 45°): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir5_data->display(str);
double dist5 = adcToDistanceCm(ir5);
ui->ir5_cm_data->display(QString::number(dist5, 'f', 1));
int pct5 = (dist5 >= 80.0) ? 100 : qBound(0, (int)((dist5 / 80.0) * 100.0), 100);
ui->bar_ir5->setValue(pct5);
ui->bar_ir5->setFormat((dist5 >= 80.0) ? QString("Libre (100%)") : QString("%1 cm (%2%)").arg(dist5, 0, 'f', 1).arg(pct5));
w.ui8[0] = datosRx[12];
w.ui8[1] = datosRx[13];
uint16_t ir6 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR5 (Línea Der): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir6_data->display(str);
ui->bar_ir6->setValue(ir6);
ui->bar_ir6->setFormat(QString("%1 / 4095").arg(ir6));
sumLineSensors += qMax(0, 2400 - w.i16[0]);
str = QString("%1").arg(sumLineSensors, 5, 10, QChar('0'));
w.ui8[0] = datosRx[14];
w.ui8[1] = datosRx[15];
uint16_t ir7 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR6 (Frontal): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir7_data->display(str);
double dist7 = adcToDistanceCm(ir7);
ui->ir7_cm_data->display(QString::number(dist7, 'f', 1));
int pct7 = (dist7 >= 80.0) ? 100 : qBound(0, (int)((dist7 / 80.0) * 100.0), 100);
ui->bar_ir7->setValue(pct7);
ui->bar_ir7->setFormat((dist7 >= 80.0) ? QString("Libre (100%)") : QString("%1 cm (%2%)").arg(dist7, 0, 'f', 1).arg(pct7));
w.ui8[0] = datosRx[16];
w.ui8[1] = datosRx[17];
uint16_t ir8 = w.ui16[0];
str = QString("%1").arg(w.ui16[0], 5, 10, QChar('0'));
strOut = "IR7 (Der 45°): " + str;
addLogEntry(strOut, "RX");
ui->textBrowserProcessed->append(strOut);
ui->ir8_data->display(str);
double dist8 = adcToDistanceCm(ir8);
ui->ir8_cm_data->display(QString::number(dist8, 'f', 1));
int pct8 = (dist8 >= 80.0) ? 100 : qBound(0, (int)((dist8 / 80.0) * 100.0), 100);
ui->bar_ir8->setValue(pct8);
ui->bar_ir8->setFormat((dist8 >= 80.0) ? QString("Libre (100%)") : QString("%1 cm (%2%)").arg(dist8, 0, 'f', 1).arg(pct8));
// ---- NUEVO: Enviar a la gráfica ----
double t = runtimeTimer.elapsed() / 1000.0;
updateIRChart(t, ir1, ir2, ir3, ir4, ir5, ir6, ir7, ir8);
// --- Acumular muestra en buffer circular de IR superiores (último minuto) ---
UpperIrSample upperSample;
upperSample.timestamp = QDateTime::currentDateTime();
upperSample.ir1 = ir1;
upperSample.ir3 = ir3;
upperSample.ir5 = ir5;
upperSample.ir7 = ir7;
upperSample.ir8 = ir8;
m_upperIrBuffer.append(upperSample);
if (m_upperIrBuffer.size() > IR_BUFFER_SIZE)
m_upperIrBuffer.removeFirst();
break;
}
case GETINTERNALDATA: {
w.ui8[0] = datosRx[58]; w.ui8[1] = datosRx[59]; w.ui8[2] = datosRx[60]; w.ui8[3] = datosRx[61];
float hr_angle = w.i32 / 10000.0f;
ui->angle_hr_data->display(QString::number(hr_angle, 'f', 4));
// Unpack raw IR values (IR1=Izq, IR3=Cen, IR5=Der)
w.ui8[0] = datosRx[68]; w.ui8[1] = datosRx[69];
uint16_t rawIr1 = w.ui16[0]; // Izquierda (IR1)
w.ui8[0] = datosRx[70]; w.ui8[1] = datosRx[71];
uint16_t rawIr3 = w.ui16[0]; // Centro (IR3)
w.ui8[0] = datosRx[72]; w.ui8[1] = datosRx[73];
uint16_t rawIr5 = w.ui16[0]; // Derecha (IR5)
// Unpack calibrated IR values (IR1=Izq, IR3=Cen, IR5=Der)
w.ui8[0] = datosRx[74]; w.ui8[1] = datosRx[75];
uint16_t calIr1 = w.ui16[0]; // Izquierda (IR1)
m_calIr1 = calIr1;
w.ui8[0] = datosRx[76]; w.ui8[1] = datosRx[77];
uint16_t calIr3 = w.ui16[0]; // Centro (IR3)
m_calIr3 = calIr3;
w.ui8[0] = datosRx[78]; w.ui8[1] = datosRx[79];
uint16_t calIr5 = w.ui16[0]; // Derecha (IR5)
m_calIr5 = calIr5;
// --- Modo del robot en tiempo real ---
uint8_t currentRobotMode = datosRx[87];
updateRobotModeUI(currentRobotMode);
// --- Acumular muestra en buffer circular IR (último minuto) ---
IrSample sample;
sample.timestamp = QDateTime::currentDateTime();
sample.ir1 = rawIr1; // Guardar el valor sin procesar (raw)
sample.ir3 = rawIr3; // Guardar el valor sin procesar (raw)
sample.ir5 = rawIr5; // Guardar el valor sin procesar (raw)
m_irBuffer.append(sample);
if (m_irBuffer.size() > IR_BUFFER_SIZE)
m_irBuffer.removeFirst();
if (!paramsSynced) {
// 1. PID Balancín (indices 2 a 11)
w.ui8[0] = datosRx[2]; w.ui8[1] = datosRx[3]; ui->setBalanceKp->setValue(w.i16[0]);
w.ui8[0] = datosRx[4]; w.ui8[1] = datosRx[5]; ui->setBalanceKi->setValue(w.i16[0]);
w.ui8[0] = datosRx[6]; w.ui8[1] = datosRx[7]; ui->setBalanceKd->setValue(w.i16[0]);
w.ui8[0] = datosRx[8]; w.ui8[1] = datosRx[9]; ui->setPWMMINR->setValue(w.ui16[0]);
w.ui8[0] = datosRx[10]; w.ui8[1] = datosRx[11]; ui->setPWMMINL->setValue(w.ui16[0]);
// 2. Setpoint (indices 12 a 15)
w.ui8[0] = datosRx[12]; w.ui8[1] = datosRx[13];
w.ui8[2] = datosRx[14]; w.ui8[3] = datosRx[15];
ui->setSetpoint->setValue(w.i32);
m_currentSetpoint = w.i32;
updateGoToAngleDisplays();
// 3. Extra (indices 16 a 29)
w.ui8[0] = datosRx[16]; w.ui8[1] = datosRx[17]; ui->setLineKp->setValue(w.i16[0]);
w.ui8[0] = datosRx[18]; w.ui8[1] = datosRx[19]; ui->setLineKd->setValue(w.i16[0]);
w.ui8[0] = datosRx[20]; w.ui8[1] = datosRx[21]; ui->setOFFSETL->setValue(w.i16[0]);
w.ui8[0] = datosRx[22]; w.ui8[1] = datosRx[23]; ui->setOFFSETR->setValue(w.i16[0]);
w.ui8[0] = datosRx[24]; w.ui8[1] = datosRx[25]; ui->setCustomTurn->setValue(w.i16[0]);
w.ui8[0] = datosRx[26]; w.ui8[1] = datosRx[27];
ui->setAttackSetpoint->blockSignals(true);
ui->setAttackSetpoint->setValue(w.i16[0]);
ui->setAttackSetpoint->blockSignals(false);
w.ui8[0] = datosRx[28]; w.ui8[1] = datosRx[29]; ui->setWallKp->setValue(w.i16[0]);
// 4. Esquivador (indices 30 a 39)
w.ui8[0] = datosRx[30]; w.ui8[1] = datosRx[31]; ui->setFrontDistance->setValue(w.ui16[0]);
w.ui8[0] = datosRx[32]; w.ui8[1] = datosRx[33]; ui->setSideDistance->setValue(w.ui16[0]);
w.ui8[0] = datosRx[34]; w.ui8[1] = datosRx[35]; ui->setLostDistance->setValue(w.ui16[0]);
w.ui8[0] = datosRx[36]; w.ui8[1] = datosRx[37]; ui->setStopCycles->setValue(w.ui16[0]);
w.ui8[0] = datosRx[38]; w.ui8[1] = datosRx[39]; ui->setCornerDist->setValue(w.ui16[0]);
w.ui8[0] = datosRx[40]; w.ui8[1] = datosRx[41]; ui->setAlignDist->setValue(w.ui16[0]);
// 5. Rotación (los controles de UI fueron reemplazados por la columna 5 de Sesgo de Enganche)
// w.ui8[0] = datosRx[42]; w.ui8[1] = datosRx[43]; ui->setPWMLROT->setValue(w.ui16[0]);
// w.ui8[0] = datosRx[44]; w.ui8[1] = datosRx[45]; ui->setPWMRROT->setValue(w.ui16[0]);
// w.ui8[0] = datosRx[46]; w.ui8[1] = datosRx[47]; ui->setStaticOff->setValue(w.ui16[0]);
// w.ui8[0] = datosRx[48]; w.ui8[1] = datosRx[49]; ui->setMovingOff->setValue(w.ui16[0]);
// w.ui8[0] = datosRx[50]; w.ui8[1] = datosRx[51]; ui->setLimitAngle->setValue(w.i16[0]);
w.ui8[0] = datosRx[52]; w.ui8[1] = datosRx[53]; ui->setKpCascada->setValue(w.i16[0]);
w.ui8[0] = datosRx[54]; w.ui8[1] = datosRx[55]; ui->setKiCascada->setValue(w.i16[0]);
w.ui8[0] = datosRx[56]; w.ui8[1] = datosRx[57]; ui->setFilterLPF->setValue(w.i16[0]);
w.ui8[0] = datosRx[62]; w.ui8[1] = datosRx[63]; ui->setVelDampDiv->setValue(w.i16[0]);
w.ui8[0] = datosRx[64]; w.ui8[1] = datosRx[65]; ui->setVelDampLim->setValue(w.i16[0]);
w.ui8[0] = datosRx[66]; w.ui8[1] = datosRx[67]; ui->setTurnLimit->setValue(w.i16[0]);
w.ui8[0] = datosRx[80]; w.ui8[1] = datosRx[81]; ui->setWallKd->setValue(w.i16[0]);
w.ui8[0] = datosRx[82]; w.ui8[1] = datosRx[83]; ui->setFrontKp->setValue(w.i16[0]);
w.ui8[0] = datosRx[84]; w.ui8[1] = datosRx[85]; ui->setFrontKd->setValue(w.i16[0]);
ui->comboDodgeDir->setCurrentIndex(datosRx[86]);
w.ui8[0] = datosRx[89]; w.ui8[1] = datosRx[90]; ui->setDodgeBiasTime->setValue(w.i16[0]);
w.ui8[0] = datosRx[91]; w.ui8[1] = datosRx[92]; ui->setDodgeBiasMult->setValue(w.i16[0]);
paramsSynced = true;
addLogEntry("***PARÁMETROS SINCRONIZADOS DESDE STM32***", "RX");
ui->textBrowserProcessed->append("***PARÁMETROS SINCRONIZADOS DESDE STM32***");
}
break;
}
case GETPIDBALANCE: {
// 1. Extraer Error (arranca en datosRx[2])
w.ui8[0] = datosRx[2]; w.ui8[1] = datosRx[3]; w.ui8[2] = datosRx[4]; w.ui8[3] = datosRx[5];
int32_t current_error = w.i32;
// 2. Extraer Integral
w.ui8[0] = datosRx[6]; w.ui8[1] = datosRx[7]; w.ui8[2] = datosRx[8]; w.ui8[3] = datosRx[9];
int32_t current_integral = w.i32;
// 3. Extraer Derivada
w.ui8[0] = datosRx[10]; w.ui8[1] = datosRx[11]; w.ui8[2] = datosRx[12]; w.ui8[3] = datosRx[13];
int32_t current_derivative = w.i32;
// 4. Extraer Output
w.ui8[0] = datosRx[14]; w.ui8[1] = datosRx[15]; w.ui8[2] = datosRx[16]; w.ui8[3] = datosRx[17];
int32_t current_output = w.i32;
// 5. Extraer Angulo Real del STM32 (Nuevo)
w.ui8[0] = datosRx[18]; w.ui8[1] = datosRx[19]; w.ui8[2] = datosRx[20]; w.ui8[3] = datosRx[21];
float stm_angle = w.i32 / 100.0f; // Escala x100 -> real
ui->angle_data->display(QString::number(stm_angle, 'f', 2));
m_currentAngle = stm_angle;
updateGoToAngleDisplays();
// 5b. Extraer Turn Offset del STM32 (Nuevo)
w.ui8[0] = datosRx[22]; w.ui8[1] = datosRx[23]; w.ui8[2] = datosRx[24]; w.ui8[3] = datosRx[25];
int32_t current_turn_offset = w.i32;
ui->turn_offset_data->display(current_turn_offset);
// 5c. Extraer Delta-time Medido en milisegundos (Nuevo)
w.ui8[0] = datosRx[26]; w.ui8[1] = datosRx[27]; w.ui8[2] = datosRx[28]; w.ui8[3] = datosRx[29];
int32_t current_dt_ms = w.i32;