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