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