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