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