]> rtime.felk.cvut.cz Git - eurobot/public.git/blob - src/robomon/RobomonAtlantis.cpp
Merge branch 'master' of kubiaj1@rtime.felk.cvut.cz:/var/git/eurobot
[eurobot/public.git] / src / robomon / RobomonAtlantis.cpp
1 /*
2  * RobomonAtlantis.cpp                  07/10/31
3  *
4  * Robot`s visualization and control GUI for robot of the
5  * Eurobot 2008 (Mission to Mars).
6  *
7  * Copyright: (c) 2008 CTU Dragons
8  *            CTU FEE - Department of Control Engineering
9  * Authors: Martin Zidek, Michal Sojka, Tran Duy Khanh
10  * License: GNU GPL v.2
11  */
12
13 #include <QtGui>
14 #include <queue>
15 #include <cstdlib>
16 #include <sys/shm.h>
17 #include <sys/stat.h>
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <math.h>
24
25 #include <orte.h>
26 #include <path_planner.h>
27 #include <robodim.h>
28 #include <sharp.h>
29 #include <trgen.h>
30 #include <map.h>
31 #include <robomath.h>
32 #include <hokuyo.h>
33 #include <actuators.h>
34 #include "PlaygroundScene.h"
35 #include "MiscGui.h"
36 #include "robomon_orte.h"
37 #include "RobomonAtlantis.h"
38 #include "playgroundview.h"
39
40 #include <QCoreApplication>
41 #include <QEvent>
42 #include <QKeyEvent>
43 #include <QDebug>
44 #include <QMessageBox>
45
46 RobomonAtlantis::RobomonAtlantis(QWidget *parent)
47         : QWidget(parent)
48 {
49         QFont font;
50         font.setPointSize(7);
51         setFont(font);
52
53         debugWindowEnabled = false;
54
55         createLeftLayout();
56         createRightLayout();
57
58         QHBoxLayout *mainLayout = new QHBoxLayout;
59         mainLayout->addLayout(leftLayout);
60         mainLayout->addLayout(rightLayout);
61         setLayout(mainLayout);
62
63         createOrte();
64         createRobots();
65         createActions();
66
67         setFocusPolicy(Qt::StrongFocus);
68         sharedMemoryOpened = false;
69         WDBG("Youuuhouuuu!!");
70 }
71
72 /**********************************************************************
73  * GUI
74  **********************************************************************/
75 void RobomonAtlantis::createLeftLayout()
76 {
77         leftLayout = new QVBoxLayout();
78         
79         createDebugGroupBox();
80         debugWindowEnabled = true;
81         createPlaygroundGroupBox();
82         leftLayout->addWidget(playgroundGroupBox);
83         leftLayout->addWidget(debugGroupBox);
84 }
85
86 void RobomonAtlantis::createRightLayout()
87 {
88         rightLayout = new QVBoxLayout();
89         QGridLayout *layout = new QGridLayout();
90         QVBoxLayout *vlayout = new QVBoxLayout();
91         
92         createPositionGroupBox();
93         createMiscGroupBox();
94         createFSMGroupBox();
95         createActuatorsGroupBox();
96         createDIOGroupBox();
97         createPowerGroupBox();
98         createSensorsGroupBox();
99
100         vlayout->addWidget(positionGroupBox);
101         vlayout->addWidget(miscGroupBox);
102         vlayout->addWidget(fsmGroupBox);
103         layout->addLayout(vlayout, 0, 0);
104         layout->addWidget(actuatorsGroupBox, 0, 1);
105 //      layout->addWidget(dioGroupBox, 0, 2);
106
107         rightLayout->addLayout(layout);
108         rightLayout->addWidget(powerGroupBox);
109         rightLayout->addWidget(sensorsGroupBox);
110 }
111
112 void RobomonAtlantis::createPlaygroundGroupBox()
113 {
114         playgroundGroupBox = new QGroupBox(tr("Playground"));
115         QHBoxLayout *layout = new QHBoxLayout();
116
117         playgroundScene = new PlaygroundScene();
118         playgroundSceneView = new PlaygroundView(playgroundScene);
119         //playgroundSceneView->setMinimumWidth(630);
120         //playgroundSceneView->setMinimumHeight(445);
121         playgroundSceneView->setMatrix(QMatrix(1,0,0,-1,0,0), true);
122         playgroundSceneView->fitInView(playgroundScene->itemsBoundingRect());
123         playgroundSceneView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
124         layout->addWidget(playgroundSceneView);
125
126         playgroundGroupBox->setLayout(layout);
127 }
128
129 void RobomonAtlantis::createPositionGroupBox()
130 {
131         positionGroupBox = new QGroupBox(tr("Position state"));
132         positionGroupBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
133         QGridLayout *layout = new QGridLayout();
134         
135         actPosX = new QLineEdit();
136         actPosY = new QLineEdit();
137         actPosPhi = new QLineEdit();
138
139         estPosX = new QLineEdit();
140         estPosY = new QLineEdit();
141         estPosPhi = new QLineEdit();
142         
143         actPosX->setReadOnly(true);
144         actPosY->setReadOnly(true);
145         actPosPhi->setReadOnly(true);
146
147         estPosX->setReadOnly(true);
148         estPosY->setReadOnly(true);
149         estPosPhi->setReadOnly(true);
150
151         layout->addWidget(MiscGui::createLabel("X"), 1, 0);
152         layout->addWidget(MiscGui::createLabel("Y"), 2, 0);
153         layout->addWidget(MiscGui::createLabel("Phi"), 3, 0);
154
155         layout->addWidget(MiscGui::createLabel("X"), 5, 0);
156         layout->addWidget(MiscGui::createLabel("Y"), 6, 0);
157         layout->addWidget(MiscGui::createLabel("Phi"), 7, 0);
158
159         layout->addWidget(MiscGui::createLabel("Reference", Qt::AlignLeft), 0, 1);
160         layout->addWidget(actPosX, 1, 1);
161         layout->addWidget(actPosY, 2, 1);
162         layout->addWidget(actPosPhi, 3, 1);
163
164         layout->addWidget(MiscGui::createLabel("Estimated", Qt::AlignLeft), 4, 1);
165         layout->addWidget(estPosX, 5, 1);
166         layout->addWidget(estPosY, 6, 1);
167         layout->addWidget(estPosPhi, 7, 1);
168
169         positionGroupBox->setLayout(layout);
170 }
171
172 void RobomonAtlantis::createMiscGroupBox()
173 {
174         miscGroupBox = new QGroupBox(tr("Miscellaneous"));
175         miscGroupBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
176         QGridLayout *layout = new QGridLayout();
177
178         showMapPushButton = new QCheckBox(tr("Show &map"));
179         showMapPushButton->setShortcut(tr("m"));
180
181         layout->addWidget(showMapPushButton, 0, 0);
182         
183         obstacleSimulationCheckBox = new QCheckBox(tr("&Obstacle simulation"));
184         obstacleSimulationCheckBox->setShortcut(tr("o"));
185         layout->addWidget(obstacleSimulationCheckBox);
186
187         miscGroupBox->setLayout(layout);
188 }
189
190 void RobomonAtlantis::createFSMGroupBox()
191 {
192         fsmGroupBox = new QGroupBox(tr("FSM"));
193         fsmGroupBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
194         QGridLayout *layout = new QGridLayout();
195
196         layout->addWidget(MiscGui::createLabel("Main:"), 1, 0);
197         fsm_main_state = new QLabel();
198         fsm_main_state->setMinimumWidth(100);
199         layout->addWidget(fsm_main_state, 1, 1);
200
201         layout->addWidget(MiscGui::createLabel("Act:"), 2, 0);
202         fsm_act_state = new QLabel();
203         layout->addWidget(fsm_act_state, 2, 1);
204
205         layout->addWidget(MiscGui::createLabel("Motion:"), 3, 0);
206         fsm_motion_state = new QLabel();
207         layout->addWidget(fsm_motion_state, 3, 1);
208
209         fsmGroupBox->setLayout(layout);
210 }
211
212 void RobomonAtlantis::createDebugGroupBox()
213 {
214         debugGroupBox = new QGroupBox(tr("Debug window"));
215         QHBoxLayout *layout = new QHBoxLayout();
216
217         debugWindow = new QTextEdit();
218         debugWindow->setReadOnly(true);
219
220         layout->addWidget(debugWindow);
221         debugGroupBox->setLayout(layout);
222 }
223
224 void RobomonAtlantis::createActuatorsGroupBox()
225 {
226         actuatorsGroupBox = new QGroupBox(tr("Actuators"));
227         QHBoxLayout *layout = new QHBoxLayout();
228
229         createMotorsGroupBox();
230         createPickerGroupBox();
231
232         layout->setAlignment(Qt::AlignLeft);
233         layout->addWidget(enginesGroupBox);
234         layout->addWidget(pickerGroupBox);
235         actuatorsGroupBox->setLayout(layout);
236 }
237
238 void RobomonAtlantis::createDIOGroupBox()
239 {
240         dioGroupBox = new QGroupBox(tr("DIO"));
241         QGridLayout *layout = new QGridLayout();
242         QFont font;
243
244         font.setPointSize(5);
245         dioGroupBox->setFont(font);
246
247         for (int i=0; i<8; i++) {
248                 diCheckBox[i] = new QCheckBox(QString("DI%1").arg(i));
249                 doCheckBox[i] = new QCheckBox(QString("D0%1").arg(i));
250                 layout->addWidget(diCheckBox[i], i, 0);
251                 layout->addWidget(doCheckBox[i], i+8, 0);
252         }
253
254         dioGroupBox->setMaximumWidth(70);
255         dioGroupBox->setLayout(layout);
256 }
257
258 void RobomonAtlantis::createPowerGroupBox()
259 {
260         powerGroupBox = new QGroupBox(tr("Power management"));
261         QGridLayout *layout = new QGridLayout();
262
263         voltage33CheckBox = new QCheckBox(tr("&3.3V"));
264         voltage50CheckBox = new QCheckBox(tr("&5.0V"));
265         voltage80CheckBox = new QCheckBox(tr("&8.0V"));
266
267         voltage33CheckBox->setShortcut(tr("3"));
268         voltage50CheckBox->setShortcut(tr("5"));
269         voltage80CheckBox->setShortcut(tr("8"));
270
271         layout->addWidget(voltage33CheckBox, 0, 0);
272         layout->addWidget(voltage50CheckBox, 0, 2);
273         layout->addWidget(voltage80CheckBox, 0, 4); //1, 0);
274         layout->addWidget(MiscGui::createLabel("BAT"), 0, 6); //1, 2);
275
276         voltage33LineEdit = new QLineEdit();
277         voltage50LineEdit = new QLineEdit();
278         voltage80LineEdit = new QLineEdit();
279         voltageBATLineEdit = new QLineEdit();
280
281         voltage33LineEdit->setReadOnly(true);
282         voltage50LineEdit->setReadOnly(true);
283         voltage80LineEdit->setReadOnly(true);
284         voltageBATLineEdit->setReadOnly(true);
285
286         layout->addWidget(voltage33LineEdit, 0, 1);
287         layout->addWidget(voltage50LineEdit, 0, 3);
288         layout->addWidget(voltage80LineEdit, 0, 5); //1, 1);
289         layout->addWidget(voltageBATLineEdit, 0, 7); //1, 3);
290
291         powerGroupBox->setLayout(layout);
292 }
293
294 void RobomonAtlantis::createSensorsGroupBox()
295 {
296         sensorsGroupBox = new QGroupBox(tr("Sensors"));
297         sensorsGroupBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
298         QHBoxLayout *layout = new QHBoxLayout();
299
300         layout->addWidget(MiscGui::createLabel("Puck Sharp"));
301         sharpPuck = new QProgressBar();
302         sharpPuck->setFormat("%v mm");
303         sharpPuck->setTextVisible(true);
304         sharpPuck->setMaximum(250);
305         layout->addWidget(sharpPuck);
306
307         sensorsGroupBox->setLayout(layout);
308 }
309
310 void RobomonAtlantis::createMotorsGroupBox()
311 {
312         enginesGroupBox = new QGroupBox(tr("Motors"));
313         QVBoxLayout *layout = new QVBoxLayout();
314         QHBoxLayout *layout1 = new QHBoxLayout();
315         QHBoxLayout *layout2 = new QHBoxLayout();
316
317         leftMotorSlider = new QSlider(Qt::Vertical);
318         rightMotorSlider = new QSlider(Qt::Vertical);
319         bothMotorsCheckBox = new QCheckBox(tr("Lock both"));
320         stopMotorsPushButton = new QPushButton(tr("Stop Motors"));
321
322         leftMotorSlider->setMinimum(-100);
323         leftMotorSlider->setMaximum(100);
324         leftMotorSlider->setTracking(false);
325         leftMotorSlider->setTickPosition(QSlider::TicksLeft);
326
327         rightMotorSlider->setMinimum(-100);
328         rightMotorSlider->setMaximum(100);
329         rightMotorSlider->setTracking(false);
330         rightMotorSlider->setTickPosition(QSlider::TicksRight);
331
332         stopMotorsPushButton->setMaximumWidth(90);
333
334         layout1->addWidget(leftMotorSlider);
335         layout1->addWidget(MiscGui::createLabel("0"));
336         layout1->addWidget(rightMotorSlider);
337
338         layout2->addWidget(bothMotorsCheckBox);
339
340         layout->addWidget(MiscGui::createLabel("100"));
341         layout->addLayout(layout1);
342         layout->addWidget(MiscGui::createLabel("-100"));
343         layout->addLayout(layout2);
344         layout->addWidget(stopMotorsPushButton);
345         enginesGroupBox->setLayout(layout);
346 }
347
348 void RobomonAtlantis::createPickerGroupBox()
349 {
350         pickerGroupBox = new QGroupBox(tr("Picker"));
351         QVBoxLayout *layout = new QVBoxLayout();
352
353         leftBeltCheckBox = new QCheckBox(tr("L Belt"));
354         rightBeltCheckBox = new QCheckBox(tr("R Belt"));
355         leftChelaCheckBox = new QCheckBox(tr("L Chela"));
356         rightChelaCheckBox = new QCheckBox(tr("R Chela"));
357         leftBeltDial = new QDial();
358         rightBeltDial = new QDial();
359         leftChelaDial = new QDial();
360         rightChelaDial = new QDial();
361         pickPushButton = new QPushButton(tr("Pick!"));
362
363         leftBeltDial->setMinimum(0);
364         leftBeltDial->setMaximum(200);
365         leftBeltDial->setValue(100);
366
367         rightBeltDial->setMinimum(0);
368         rightBeltDial->setMaximum(200);
369         rightBeltDial->setValue(100);
370
371         leftChelaDial->setMinimum(0);
372         leftChelaDial->setMaximum(255);
373         leftChelaDial->setValue(127);
374
375         rightChelaDial->setMinimum(0);
376         rightChelaDial->setMaximum(255);
377         rightChelaDial->setValue(127);
378
379         layout->addWidget(leftChelaDial);
380         layout->addWidget(leftChelaCheckBox);
381         layout->addWidget(rightChelaDial);
382         layout->addWidget(rightChelaCheckBox);
383         layout->addWidget(leftBeltDial);
384         layout->addWidget(leftBeltCheckBox);
385         layout->addWidget(rightBeltDial);
386         layout->addWidget(rightBeltCheckBox);
387         layout->addWidget(pickPushButton);
388
389         pickerGroupBox->setLayout(layout);
390 }
391
392 void RobomonAtlantis::createRobots()
393 {
394         robotActPos = new Robot(QPen(), QBrush(Qt::darkGray));
395         robotActPos->setZValue(10);
396         robotEstPos = new Robot(QPen(Qt::darkBlue), QBrush(Qt::NoBrush));
397         robotEstPos->setZValue(11);
398
399         playgroundScene->addItem(robotActPos);
400         playgroundScene->addItem(robotEstPos);
401 }
402
403 /**********************************************************************
404  * GUI actions
405  **********************************************************************/
406 void RobomonAtlantis::createActions()
407 {
408         /* power management */
409         connect(voltage33CheckBox, SIGNAL(stateChanged(int)), 
410                         this, SLOT(setVoltage33(int)));
411         connect(voltage50CheckBox, SIGNAL(stateChanged(int)), 
412                         this, SLOT(setVoltage50(int)));
413         connect(voltage80CheckBox, SIGNAL(stateChanged(int)), 
414                         this, SLOT(setVoltage80(int)));
415
416         /* motors */
417         connect(leftMotorSlider, SIGNAL(valueChanged(int)), 
418                         this, SLOT(setLeftMotor(int)));
419         connect(rightMotorSlider, SIGNAL(valueChanged(int)), 
420                         this, SLOT(setRightMotor(int)));
421         connect(stopMotorsPushButton, SIGNAL(clicked()), 
422                         this, SLOT(stopMotors()));
423
424         /* DIO */
425         for (int i=0; i<8; i++)
426                 connect(doCheckBox[0], SIGNAL(stateChanged(int)), 
427                                         this, SLOT(setDO(int)));
428
429         /* path planning map */
430         connect(showMapPushButton, SIGNAL(clicked()),
431                         this, SLOT(showMap()));
432
433         /* obstacle simulation */
434         simulationEnabled = 0;
435         connect(obstacleSimulationCheckBox, SIGNAL(stateChanged(int)),
436                         this, SLOT(setSimulation(int)));
437         connect(obstacleSimulationCheckBox, SIGNAL(stateChanged(int)),
438                         this, SLOT(setObstacleSimulation(int)));
439         connect(obstacleSimulationCheckBox, SIGNAL(stateChanged(int)),
440                         playgroundScene, SLOT(showObstacle(int)));
441         connect(playgroundScene, SIGNAL(obstacleChanged(QPointF)), 
442                         this, SLOT(changeObstacle(QPointF)));
443
444         /* Actuators */
445         connect(pickPushButton, SIGNAL(clicked()), this, SLOT(pick()));
446         connect(leftBeltCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setBelts(int)));
447         connect(rightBeltCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setBelts(int)));
448         connect(leftChelaCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setChelae(int)));
449         connect(rightChelaCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setChelae(int)));
450         connect(leftBeltDial, SIGNAL(valueChanged(int)), this, SLOT(setBelts(int)));
451         connect(rightBeltDial, SIGNAL(valueChanged(int)), this, SLOT(setBelts(int)));
452         connect(leftChelaDial, SIGNAL(valueChanged(int)), this, SLOT(setChelae(int)));
453         connect(rightChelaDial, SIGNAL(valueChanged(int)), this, SLOT(setChelae(int)));
454 }
455
456 void RobomonAtlantis::setVoltage33(int state)
457 {
458         if (state)
459                 orte.pwr_ctrl.voltage33 = true;
460         else
461                 orte.pwr_ctrl.voltage33 = false;
462 }
463
464 void RobomonAtlantis::setVoltage50(int state)
465 {
466         if (state)
467                 orte.pwr_ctrl.voltage50 = true;
468         else
469                 orte.pwr_ctrl.voltage50 = false;
470 }
471
472 void RobomonAtlantis::setVoltage80(int state)
473 {
474         if (state)
475                 orte.pwr_ctrl.voltage80 = true;
476         else
477                 orte.pwr_ctrl.voltage80 = false;
478 }
479
480 void RobomonAtlantis::setLeftMotor(int value)
481 {
482         short int leftMotor;
483         short int rightMotor;
484         
485         if(bothMotorsCheckBox->isChecked())
486                 rightMotorSlider->setValue(value);
487
488         leftMotor = (short int)(MOTOR_LIMIT * (leftMotorSlider->value()/100.0));
489         rightMotor = (short int)(MOTOR_LIMIT * (rightMotorSlider->value()/100.0));
490         
491         orte.motion_speed.left = leftMotor;
492         orte.motion_speed.right = rightMotor;
493         
494 }
495
496 void RobomonAtlantis::setRightMotor(int value)
497 {
498         short int leftMotor;
499         short int rightMotor;
500         
501         if(bothMotorsCheckBox->isChecked())
502                 leftMotorSlider->setValue(value);
503
504         leftMotor = (short int)(MOTOR_LIMIT * (leftMotorSlider->value()/100.0));
505         rightMotor = (short int)(MOTOR_LIMIT * (rightMotorSlider->value()/100.0));
506         
507         orte.motion_speed.left = leftMotor;
508         orte.motion_speed.right = rightMotor;
509         
510 }
511
512 void RobomonAtlantis::stopMotors()
513 {
514         leftMotorSlider->setValue(0);
515         rightMotorSlider->setValue(0);
516 }
517
518
519 void RobomonAtlantis::setDO(int state)
520 {
521         Q_UNUSED(state);
522         /* FIXME: digital output control comes here */
523 }
524
525 void RobomonAtlantis::pick()
526 {
527         // TODO: send signal to the fsmact
528 }
529
530 void RobomonAtlantis::setBelts(int value)
531 {
532         Q_UNUSED(value);
533         unsigned char leftBelt;
534         unsigned char rightBelt;
535
536         leftBelt = (unsigned char)leftBeltDial->value();
537         rightBelt = (unsigned char)rightBeltDial->value();
538
539         act_belts(leftBelt, rightBelt);
540 }
541
542 void RobomonAtlantis::setChelae(int value)
543 {
544         Q_UNUSED(value);
545         unsigned char leftChela;
546         unsigned char rightChela;
547
548         leftChela = (unsigned char)leftChelaDial->value();
549         rightChela = (unsigned char)rightChelaDial->value();
550
551         act_chelae(leftChela, rightChela);
552 }
553
554 void RobomonAtlantis::showMap()
555 {
556         openSharedMemory();
557
558         if (sharedMemoryOpened == false)
559                 return;
560
561         mapTimer = new QTimer(this);
562         connect(mapTimer, SIGNAL(timeout()), this, SLOT(paintMap()));
563         mapTimer->start(200);
564
565         disconnect(showMapPushButton, SIGNAL(clicked()), this, SLOT(showMap()));
566         connect(showMapPushButton, SIGNAL(clicked()),
567                                 this, SLOT(showPlayground()));
568         playgroundScene->showMap(true);
569 }
570
571 void RobomonAtlantis::showPlayground()
572 {
573         mapTimer->stop();
574         disconnect(mapTimer, SIGNAL(timeout()), this, SLOT(paintMap()));
575
576         disconnect(showMapPushButton, SIGNAL(clicked()),
577                                 this, SLOT(showPlayground()));
578         connect(showMapPushButton, SIGNAL(clicked()), this, SLOT(showMap()));
579         playgroundScene->showMap(false);
580 }
581
582 void RobomonAtlantis::paintMap()
583 {
584         using namespace Qt;
585         int x, y;
586         struct map *map = ShmapIsMapInit();
587
588         if (!map) return;
589         
590         for(int i=0; i < MAP_WIDTH; i++) {
591                 for(int j=0; j<MAP_HEIGHT; j++) {
592                         QColor color;
593                                 
594                         struct map_cell *cell = &map->cells[j][i];
595                         color = lightGray;
596                         if (cell->flags & MAP_FLAG_WALL)
597                                 color = darkYellow;
598                         if (cell->flags & MAP_FLAG_IGNORE_OBST)
599                                 color = darkGreen;
600                         if (cell->flags & MAP_FLAG_SIMULATED_WALL)
601                                 color = yellow;
602                         if (cell->flags & MAP_FLAG_PATH)
603                                 color = darkRed;
604                         if (cell->flags & MAP_FLAG_START)
605                                 color = red;
606                         if (cell->flags & MAP_FLAG_GOAL)
607                                 color = green;
608                         if (cell->detected_obstacle) {
609                                 QColor c1(color), c2(blue);
610                                 double f = (double)cell->detected_obstacle/MAP_NEW_OBSTACLE*0.7;
611                                 QColor c(c1.red()   + (int)(f*(c2.red()   - c1.red())),
612                                          c1.green() + (int)(f*(c2.green() - c1.green())),
613                                          c1.blue()  + (int)(f*(c2.blue()  - c1.blue())));
614                                 color = c;
615                         }
616                         if (cell->flags & MAP_FLAG_DET_OBST)
617                                 color = cyan;
618                         
619                         playgroundScene->setMapColor(i, j, color);
620                 }
621         }
622 }
623
624 void RobomonAtlantis::setSimulation(int state)
625 {
626         if(state) { 
627                 robottype_publisher_hokuyo_scan_create(&orte, 
628                                                        dummy_publisher_callback, this);
629         } else {
630                 if (!simulationEnabled)
631                         return;
632                 robottype_publisher_hokuyo_scan_destroy(&orte);
633         }
634         simulationEnabled = state;
635 }
636
637 /*!     
638         \fn RobomonAtlantis::setObstacleSimulation(int state)
639  */
640 void RobomonAtlantis::setObstacleSimulation(int state)
641 {
642         if (state) {
643                 /* TODO Maybe it is possible to attach only once to Shmap */
644                 ShmapInit(0);
645                 obstacleSimulationTimer = new QTimer(this);
646                 connect(obstacleSimulationTimer, SIGNAL(timeout()), 
647                         this, SLOT(simulateObstaclesHokuyo()));
648                 obstacleSimulationTimer->start(100);
649                 setMouseTracking(true);
650         } else {
651                 if (obstacleSimulationTimer) 
652                         delete obstacleSimulationTimer;
653                 //double distance = 0.8;
654         }
655 }
656
657
658 void RobomonAtlantis::simulateObstaclesHokuyo()
659 {
660         double distance, wall_distance;
661         int i;
662         uint16_t *hokuyo = orte.hokuyo_scan.data;
663         
664         for (i=0; i<HOKUYO_CLUSTER_CNT; i++) {
665                 wall_distance = distanceToWallHokuyo(i);
666                 distance = distanceToObstacleHokuyo(i, simulatedObstacle, SIM_OBST_SIZE_M/*meters*/);
667                 if (wall_distance < distance) 
668                         distance = wall_distance;
669                 hokuyo[i] = distance*1000;
670         }
671         ORTEPublicationSend(orte.publication_hokuyo_scan);
672         
673 }
674
675 void RobomonAtlantis::changeObstacle(QPointF position)
676 {
677         if (!simulationEnabled) {
678                 simulationEnabled = 1;
679                 obstacleSimulationCheckBox->setChecked(true);
680         }
681
682         simulatedObstacle.x = position.x();
683         simulatedObstacle.y = position.y();
684         simulateObstaclesHokuyo();
685 }       
686
687 /**********************************************************************
688  * EVENTS
689  **********************************************************************/
690 bool RobomonAtlantis::event(QEvent *event)
691 {
692         switch (event->type()) {
693                 case QEVENT(QEV_MOTION_STATUS):
694                         emit motionStatusReceivedSignal();
695                         break;
696                 case QEVENT(QEV_ACTUAL_POSITION):
697                         emit actualPositionReceivedSignal();
698                         break;
699                 case QEVENT(QEV_ESTIMATED_POSITION):
700                         emit estimatedPositionReceivedSignal();
701                         break;
702                 case QEVENT(QEV_DI):
703                         emit diReceivedSignal();
704                         break;
705                 case QEVENT(QEV_ACCELEROMETER):
706                         emit accelerometerReceivedSignal();
707                         break;
708                 case QEVENT(QEV_ACCUMULATOR):
709                         emit accumulatorReceivedSignal();
710                         break;
711                 case QEVENT(QEV_POWER_VOLTAGE):
712                         emit powerVoltageReceivedSignal();
713                         break;
714                 case QEVENT(QEV_FSM_MAIN):
715                         fsm_main_state->setText(orte.fsm_main.state_name);
716                         break;
717                 case QEVENT(QEV_FSM_ACT):
718                         fsm_act_state->setText(orte.fsm_act.state_name);
719                         break;
720                 case QEVENT(QEV_FSM_MOTION):
721                         fsm_motion_state->setText(orte.fsm_motion.state_name);
722                         break;
723                 case QEVENT(QEV_PUCK_DISTANCE):
724                         sharpPuck->setValue(orte.puck_distance.distance*1000);
725                         break;
726                 default:
727                         if (event->type() == QEvent::Close)
728                                 closeEvent((QCloseEvent *)event);
729                         else if (event->type() == QEvent::KeyPress)
730                                 keyPressEvent((QKeyEvent *)event);
731                         else if (event->type() == QEvent::KeyRelease)
732                                 keyReleaseEvent((QKeyEvent *)event);
733                         else if (event->type() == QEvent::FocusIn)
734                                 grabKeyboard();
735                         else if (event->type() == QEvent::FocusOut)
736                                 releaseKeyboard();
737                         else {
738                                 event->ignore();
739                                 return false;
740                         }
741                         break;
742         }
743         event->accept();
744         return true;
745 }
746
747 void RobomonAtlantis::keyPressEvent(QKeyEvent *event)
748 {
749         double peak, gain;
750
751         if (event->isAutoRepeat()) {
752                 switch (event->key()) {
753                         case Qt::Key_Down:
754                                 peak = leftMotorSlider->minimum()/2;
755                                 if (leftMotorValue < peak ||
756                                         rightMotorValue < peak)
757                                         gain = 1.01;
758                                 else
759                                         gain = 1.3;
760                                 leftMotorValue *= gain;
761                                 rightMotorValue *= gain;
762                                 leftMotorSlider->setValue((int)leftMotorValue);
763                                 rightMotorSlider->setValue((int)rightMotorValue);
764                                 break;
765
766                         case Qt::Key_Up:
767                         case Qt::Key_Left:
768                         case Qt::Key_Right:
769                                 peak = leftMotorSlider->maximum()/2;
770                                 if (leftMotorValue > peak ||
771                                         rightMotorValue > peak)
772                                         gain = 1.01;
773                                 else
774                                         gain = 1.3;
775                                 leftMotorValue *= gain;
776                                 rightMotorValue *= gain;
777                                 leftMotorSlider->setValue((int)leftMotorValue);
778                                 rightMotorSlider->setValue((int)rightMotorValue);
779                                 break;
780
781                         default:
782                                 event->ignore();
783                                 break;
784                 }
785                 return;
786         }
787
788         switch (event->key()) {
789                 case Qt::Key_Up:
790                         leftMotorValue = 1;
791                         rightMotorValue = 1;
792                         bothMotorsCheckBox->setChecked(true);
793                         leftMotorSlider->setValue((int)leftMotorValue);
794                         setLeftMotor((int)leftMotorValue);
795                         break;
796                 case Qt::Key_Down:
797                         leftMotorValue = -1;
798                         rightMotorValue = -1;
799                         bothMotorsCheckBox->setChecked(true);
800                         leftMotorSlider->setValue((int)leftMotorValue);
801                         setLeftMotor((int)leftMotorValue);
802                         break;
803                 case Qt::Key_Left:
804                         leftMotorValue = -1;
805                         rightMotorValue = 1;
806                         leftMotorSlider->setValue((int)leftMotorValue);
807                         rightMotorSlider->setValue((int)rightMotorValue);
808                         setLeftMotor((int)leftMotorValue);
809                         setRightMotor((int)leftMotorValue);
810                         break;
811                 case Qt::Key_Right:
812                         leftMotorValue = 1;
813                         rightMotorValue = -1;
814                         leftMotorSlider->setValue((int)leftMotorValue);
815                         rightMotorSlider->setValue((int)rightMotorValue);
816                         setLeftMotor((int)leftMotorValue);
817                         setRightMotor((int)rightMotorValue);
818                         break;
819                 default:
820                         event->ignore();
821                         break;
822         }
823         event->accept();
824 }
825
826 void RobomonAtlantis::keyReleaseEvent(QKeyEvent *event)
827 {
828         if (event->isAutoRepeat()) {
829                 event->ignore();
830                 return;
831         }
832
833         switch (event->key()) {
834                 case Qt::Key_Up:
835                 case Qt::Key_Down:
836                 case Qt::Key_Left:
837                 case Qt::Key_Right:
838                         leftMotorValue = 0;
839                         rightMotorValue = 0;
840                         bothMotorsCheckBox->setChecked(false);
841                         leftMotorSlider->setValue((int)leftMotorValue);
842                         rightMotorSlider->setValue((int)rightMotorValue);
843                         break;
844                 default:
845                         event->ignore();
846                         break;
847         }
848         event->accept();
849 }
850
851 void RobomonAtlantis::closeEvent(QCloseEvent *)
852 {
853         robottype_roboorte_destroy(&orte);
854 }
855
856 /**********************************************************************
857  * ORTE
858  **********************************************************************/
859 void RobomonAtlantis::createOrte()
860 {
861         int rv;
862
863         orte.strength = 11;
864         
865         rv = robottype_roboorte_init(&orte);
866         if (rv) {
867                 printf("RobomonAtlantis: Unable to initialize ORTE\n");
868         }
869
870         /* publishers */
871         robottype_publisher_motion_speed_create(&orte, dummy_publisher_callback, NULL);
872
873         robottype_publisher_pwr_ctrl_create(&orte, dummy_publisher_callback, NULL);
874         robottype_publisher_lift_create(&orte, NULL, &orte);
875         robottype_publisher_pusher_create(&orte, NULL, &orte);
876         robottype_publisher_chelae_create(&orte, NULL, &orte);
877         robottype_publisher_belts_create(&orte, NULL, &orte);
878         robottype_publisher_holder_create(&orte, NULL, &orte);
879
880         /* subscribers */
881         robottype_subscriber_pwr_voltage_create(&orte, 
882                                 receivePowerVoltageCallBack, this);
883         robottype_subscriber_motion_status_create(&orte, 
884                                 receiveMotionStatusCallBack, this);
885         robottype_subscriber_ref_pos_create(&orte, 
886                                 receiveActualPositionCallBack, this);
887         robottype_subscriber_est_pos_create(&orte, 
888                                 receiveEstimatedPositionCallBack, this);
889         robottype_subscriber_fsm_main_create(&orte, 
890                                              rcv_fsm_main_cb, this);
891         robottype_subscriber_fsm_motion_create(&orte, 
892                                              rcv_fsm_motion_cb, this);
893         robottype_subscriber_fsm_act_create(&orte, 
894                                              rcv_fsm_act_cb, this);
895         robottype_subscriber_puck_distance_create(&orte, rcv_puck_distance_cb, this);
896         //robottype_subscriber_actuator_status_create(orte, receiveActuatorStatusCallBack, this);
897
898
899         /*createDISubscriber(this, &orteData);*/
900         /*createAccelerometerSubscriber(this, &orteData);*/
901         /*createAccumulatorSubscriber(this, &orteData);*/
902         /* motors */
903         orte.motion_speed.left = 0;
904         orte.motion_speed.right = 0;
905         /* power management */
906         orte.pwr_ctrl.voltage33 = true;
907         orte.pwr_ctrl.voltage50 = true;
908         orte.pwr_ctrl.voltage80 = true;
909         voltage33CheckBox->setChecked(true);
910         voltage50CheckBox->setChecked(true);
911         voltage80CheckBox->setChecked(true);
912
913         act_init(&orte);
914
915         /* set actions to do when we receive data from orte */
916         connect(this, SIGNAL(motionStatusReceivedSignal()), 
917                         this, SLOT(motionStatusReceived()));
918         connect(this, SIGNAL(actualPositionReceivedSignal()), 
919                         this, SLOT(actualPositionReceived()));
920         connect(this, SIGNAL(estimatedPositionReceivedSignal()), 
921                         this, SLOT(estimatedPositionReceived()));
922         connect(this, SIGNAL(diReceivedSignal()), 
923                         this, SLOT(diReceived()));
924         connect(this, SIGNAL(accelerometerReceivedSignal()), 
925                         this, SLOT(accelerometerReceived()));
926         connect(this, SIGNAL(accumulatorReceivedSignal()), 
927                         this, SLOT(accumulatorReceived()));
928         connect(this, SIGNAL(powerVoltageReceivedSignal()), 
929                         this, SLOT(powerVoltageReceived()));
930 }
931
932 void RobomonAtlantis::motionStatusReceived()
933 {
934         WDBG("ORTE received: motion status");
935 }
936
937 void RobomonAtlantis::actualPositionReceived()
938 {
939         actPosX->setText(QString("%1").arg(orte.ref_pos.x, 0, 'f', 3));
940         actPosY->setText(QString("%1").arg(orte.ref_pos.y, 0, 'f', 3));
941         actPosPhi->setText(QString("%1(%2)")
942                         .arg(DEGREES(orte.ref_pos.phi), 0, 'f', 0)
943                         .arg(orte.ref_pos.phi, 0, 'f', 1));
944         robotActPos->moveRobot(orte.ref_pos.x, 
945                 orte.ref_pos.y, orte.ref_pos.phi);
946 }
947
948 void RobomonAtlantis::estimatedPositionReceived()
949 {
950         estPosX->setText(QString("%1").arg(orte.est_pos.x, 0, 'f', 3));
951         estPosY->setText(QString("%1").arg(orte.est_pos.y, 0, 'f', 3));
952         estPosPhi->setText(QString("%1(%2)")
953                         .arg(DEGREES(orte.est_pos.phi), 0, 'f', 0)
954                         .arg(orte.est_pos.phi, 0, 'f', 1));
955         robotEstPos->moveRobot(orte.est_pos.x, 
956                 orte.est_pos.y, orte.est_pos.phi);
957 }
958
959 void RobomonAtlantis::diReceived()
960 {
961         WDBG("ORTE received: DI");
962 }
963
964 void RobomonAtlantis::accelerometerReceived()
965 {
966         WDBG("ORTE received: accelerometer");
967 }
968
969 void RobomonAtlantis::accumulatorReceived()
970 {
971         WDBG("ORTE received: accumulator");
972 }
973
974 void RobomonAtlantis::powerVoltageReceived()
975 {
976         voltage33LineEdit->setText(QString("%1").arg(
977                         orte.pwr_voltage.voltage33, 0, 'f', 3));
978         voltage50LineEdit->setText(QString("%1").arg(
979                         orte.pwr_voltage.voltage50, 0, 'f', 3));
980         voltage80LineEdit->setText(QString("%1").arg(
981                         orte.pwr_voltage.voltage80, 0, 'f', 3));
982         voltageBATLineEdit->setText(QString("%1").arg(
983                         orte.pwr_voltage.voltageBAT, 0, 'f', 3));
984
985 }
986
987 /**********************************************************************
988  * MISCELLANEOUS
989  **********************************************************************/
990 void RobomonAtlantis::openSharedMemory()
991 {
992         int segmentId;
993         int sharedSegmentSize;
994
995         if (sharedMemoryOpened)
996                 return;
997
998         sharedSegmentSize = sizeof(char) * MAP_WIDTH * MAP_HEIGHT;
999         
1000         /* Get segment identificator in a read only mode  */
1001         segmentId = shmget(SHM_MAP_KEY, sharedSegmentSize, S_IRUSR);
1002         if(segmentId == -1) {
1003                 QMessageBox::critical(this, "robomon",
1004                                 "Unable to open shared memory segment!");
1005                 return;
1006         }
1007         
1008         /* Init Shmap */
1009         ShmapInit(0);
1010         
1011         /* Attach the shared memory segment */
1012         //map =  (_Map*)shmat (segmentId, (void*) 0, 0);
1013
1014         sharedMemoryOpened = true;
1015 }
1016
1017 double RobomonAtlantis::distanceToWallHokuyo(int beamnum)
1018 {
1019         double distance=4.0, min_distance=4.0;
1020         int i,j;
1021         Point wall;
1022         struct map *map = ShmapIsMapInit();
1023
1024         if (!map) return min_distance;
1025         
1026         // Simulate obstacles
1027         for(j=0;j<MAP_HEIGHT;j++) {
1028                 for (i=0;i<MAP_WIDTH;i++) {
1029                         struct map_cell *cell = &map->cells[j][i];
1030                         if( cell->flags & MAP_FLAG_SIMULATED_WALL) {
1031                                 // WALL
1032                                 ShmapCell2Point(i, j, &wall.x, &wall.y);
1033                                 
1034                                 distance = distanceToObstacleHokuyo(beamnum, wall, MAP_CELL_SIZE_M);
1035                                 if (distance<min_distance) min_distance = distance;
1036                         }
1037                 }
1038         }
1039
1040         return min_distance;
1041 }
1042
1043 /** 
1044  * Calculation for Hokuyo simulation. Calculates distance that would
1045  * be returned by Hokuyo sensors, if there is only one obstacle (as
1046  * specified by parameters).
1047  *
1048  * @param beamnum Hokuyo's bean number [0..HOKUYO_CLUSTER_CNT]
1049  * @param obstacle Position of the obstacle (x, y in meters).
1050  * @param obstacleSize Size (diameter) of the obstacle in meters.
1051  * 
1052  * @return Distance measured by sensors in meters.
1053  */    
1054 double RobomonAtlantis::distanceToObstacleHokuyo(int beamnum, Point obstacle, double obstacleSize)
1055 {  
1056         struct est_pos_type e = orte.est_pos;
1057         double sensor_a;
1058         struct sharp_pos s;
1059
1060         s.x = HOKUYO_CENTER_OFFSET_M;
1061         s.y = 0.0;
1062         s.ang = HOKUYO_CLUSTER_TO_RAD(beamnum);
1063
1064         Point sensor(e.x + s.x*cos(e.phi) - s.y*sin(e.phi),
1065                      e.y + s.x*sin(e.phi) + s.y*cos(e.phi));
1066         sensor_a = e.phi + s.ang;
1067         
1068         const double sensorRange = 4.0; /*[meters]*/
1069         
1070         double distance, angle;
1071             
1072         angle = sensor.angleTo(obstacle) - sensor_a;
1073         angle = fmod(angle, 2.0*M_PI);
1074         if (angle > +M_PI) angle -= 2.0*M_PI;
1075         if (angle < -M_PI) angle += 2.0*M_PI;
1076         angle = fabs(angle);
1077         distance = sensor.distanceTo(obstacle)-0.11;
1078         if (angle < atan(obstacleSize/2.0 / (distance+0.001))) {
1079                 // We can see the obstackle from here.
1080                 if (angle < M_PI/2.0) {
1081                     distance = distance/cos(angle);
1082                 }
1083                 if (distance > sensorRange) 
1084                         distance = sensorRange;
1085         } else {
1086                 distance = sensorRange;
1087         }
1088
1089         return distance;
1090 }