2 * CarMainWindow main class
4 * @author Toni Jussila <toni.jussila@fudeco.com>
5 * @author Janne Änäkkälä <janne.anakkala@fudeco.com>
6 * @author Tiina Kivilinna-Korhola <tiina.kivilinna-korhola@fudeco.com>
7 * @author Olavi Pulkkinen <olavi.pulkkinen@fudeco.com>
8 * @author Rikhard Kuutti <rikhard.kuutti@fudeco.com>
9 * @author Kai Rasilainen <kai.rasilainen@fudeco.com>
10 * @copyright (c) 2010 Speed Freak team
11 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
14 #include "carmainwindow.h"
17 #define kAccelerometerSampleRate 40
18 #define kFilteringFactor 0.1
19 #define kSecondsInHour 3600
22 *Constructor of this class.
23 *@param QWidget pointer to parent object. By default the value is NULL.
25 CarMainWindow::CarMainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::CarMainWindow)
28 ui->tabWidget->setCurrentWidget(this->ui->StartTab);
30 //Disable start buttons before calibration
31 ui->autoStartButton->setEnabled(false);
32 ui->manualStartButton->setEnabled(false);
34 result = new ResultDialog();
35 //measure = new MeasureDialog();
36 welcomeDialog = new WelcomeDialog();
37 welcomeDialog->show();
39 initComboBoxStartTabUnits();
40 initListViewStartTabAccelerationCategories();
42 myLogin = new LoginWindow(this);
43 myCategorylist = new CategoryList();
44 myHttpClient = new HttpClient(this);
45 myRegistration = new Registration(this);
46 connect(myRegistration,SIGNAL(sendregistration()),this,SLOT(regUserToServer()));
47 connect(myLogin,SIGNAL(userNameChanged()),this,SLOT(userLogin()));
48 connect(myHttpClient->myXmlreader, SIGNAL(receivedCategoryList()), this, SLOT(setCategoryCompoBox()));
49 connect(myHttpClient->myXmlreader, SIGNAL(receivedTop10List()), this, SLOT(showTop10()));
50 myRoute = new RouteDialog( this);
53 location = new Maemo5Location(this);
54 gpsData = new GPSData(location);
55 connect(location,SIGNAL(agnss()),this,SLOT(gpsStatus()));
56 gpsTime = new QDateTime();
57 gpsTimer = new QTimer();
58 connect(gpsTimer, SIGNAL(timeout()),this, SLOT(gpsTimerTimeout()));
60 gpsSpeedPrevious = 0.0;
61 gpsAcceleration = 0.0;
62 timeFromGps = 0.0; //Measure-tab view.
67 counterForSaveResults = 0;
71 accelerometer = new Accelerometer();
73 reverseAccelerationFlag = false;
74 vehicleStartedMoving = false;
78 accelerationStartThreshold = 0.1;
80 accelerometerTimer = new QTimer(this);
81 connect(accelerometerTimer, SIGNAL(timeout()), this, SLOT(readAccelerometerData()));
82 //accelerometerTimer->start(kAccelerometerSampleRate);
85 calculate = new Calculate();
86 connect(calculate, SIGNAL(checkPointReached()), this, SLOT(handleCheckPoint()));
88 resetAccelerometerMeasurements();
90 measures = new Measures();
91 measures->initializeMembers();
93 this->timer->setInterval(100);
95 connect(this->timer, SIGNAL(timeout()), this, SLOT(after_timeout()));
96 connect(myLogin, SIGNAL( userNameChanged()), this, SLOT(updateUserName()));
98 ui->labelMeasureTabResult->hide();
99 ui->pushButtonShowResultDialog->setEnabled(false);
100 ui->pushButtonShowResultDialog->setEnabled(false);
102 this->setWindowTitle("Speed Freak");
106 *Destructor of this class. Deletes all dynamic objects and sets them to NULL.
108 CarMainWindow::~CarMainWindow()
114 delete myCategorylist;
115 myCategorylist = NULL;
116 delete welcomeDialog;
117 welcomeDialog = NULL;
127 gpsSpeedPrevious = 0.0;
128 gpsAcceleration = 0.0;
135 *This function is used to .
138 void CarMainWindow::changeEvent(QEvent *e)
140 QMainWindow::changeEvent(e);
142 case QEvent::LanguageChange:
143 ui->retranslateUi(this);
151 *This slot function is called when ever list view is update. Start-tab view.
153 void CarMainWindow::on_listViewStartTabAccelerationCategories_clicked(QModelIndex index)
155 QString str = index.data().toString();
156 QStringList list = str.split("-");
157 QStringList list2 = list[1].split(" ");
159 ui->lineEditStartTabMin->setText(list[0]);
160 ui->lineEditStartTabMax->setText(list2[0]);
161 updateComboBoxStartTabUnits(list2[1]);
165 *This slot function is called when ever auto start button clicked. Start-tab view.
166 *@todo Check setDiagramGapStem(100) <- (choiceInt == 2)
168 void CarMainWindow::on_autoStartButton_clicked()
170 measures->initializeMembers();
171 resetAccelerometerMeasurements();
172 ui->pushButtonSendResult->setEnabled(false);
173 ui->pushButtonShowResultDialog->setEnabled(false);
174 choice = ui->listViewStartTabAccelerationCategories->currentIndex();
175 choiceInt = choice.row();
176 //qDebug() << "choiceInt" << choiceInt << " " << catList.at(choiceInt);
179 ui->labelMeasureTabHeader->setText("Accelerate to 40 km/h");
180 result->setDiagramGapStem(75);
182 else if (choiceInt == 1)
184 ui->labelMeasureTabHeader->setText("Accelerate to 100 km/h");
185 result->setDiagramGapStem(30);
187 else if (choiceInt == 2)
189 ui->labelMeasureTabHeader->setText("Accelerate to 10 km/h");
190 result->setDiagramGapStem(100);
194 ui->labelMeasureTabHeader->setText("Accelerate to 80 km/h");
195 result->setDiagramGapStem(37.5);
197 ui->labelMeasureTabResult->setText("");
199 this->accelerometerTimer->start(kAccelerometerSampleRate);
200 this->timer->start();
203 ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
207 *This slot function is called when ever list view is update. Start-tab view.
208 *@param QString unit.
210 void CarMainWindow::updateComboBoxStartTabUnits(QString unit)
212 ui->comboBoxStartTabUnits->setCurrentIndex(ui->comboBoxStartTabUnits->findText(unit, Qt::MatchExactly));
216 *This function is used to init unit combobox. Start-tab view.
218 void CarMainWindow::initComboBoxStartTabUnits()
220 units << "km/h" << "km" << "h" << "m" << "min" << "Mile" << "Mph" << "in" << "ft" << "yrd";
221 ui->comboBoxStartTabUnits->addItems(units);
225 *This function is used to set items to unit combobox. Start-tab view.
226 *@param QStringlist units
228 void CarMainWindow::setComboBoxStartTabUnits(QStringList units)
230 ui->comboBoxStartTabUnits->addItems(units);
234 *This function is used to init listViewStartTabAccelerationCategories. Start-tab view.
235 *@todo During development categories index values that are used for measuring are hardcoded
236 *@todo and accelerationCategoriesStartTab and catList are used instead of using
237 *@todo CategoryList::categoryList and CategoryList::cats.
239 void CarMainWindow::initListViewStartTabAccelerationCategories()
241 //Connect the user`s choice fron GUI to a correct variable name
242 catList.insert(0,"acceleration-0-40");
243 catList.insert(1,"acceleration-0-100");
244 catList.insert(2,"acceleration-0-10");
246 accelerationCategoriesStartTab << "0-40 km/h" << "0-100 km/h" << "0-10 km/h";
247 //<< "0-1/4 Mile" << "0-1/8 Mile" << "50-100 Mile" << "0-60 Mph" << "0-100 m" << "0-50 ft" << "0-50 yrd" << "0-500 in";
248 QAbstractItemModel *model = new StringListModel(accelerationCategoriesStartTab);
249 ui->listViewStartTabAccelerationCategories->setModel(model);
253 *This function is used to set items to listViewStartTabAccelerationCategories. Start-tab view.
254 *@param QStringlist accelerationCategoriesStartTab
256 void CarMainWindow::setListViewStartTabAccelerationCategories(QStringList accelerationCategoriesStartTab)
258 QAbstractItemModel *model = new StringListModel(accelerationCategoriesStartTab);
259 ui->listViewStartTabAccelerationCategories->setModel(model);
262 void CarMainWindow::setLabelInfoToUser(QString infoText)
264 ui->labelInfoToUser->setText(infoText);
268 *This function is used to set items to category combobox. Top-tab view.
271 void CarMainWindow::setCategoryCompoBox()
273 qDebug() << "_setCategoryCompoBox";
274 ui->comboBoxTopCategory->addItems(myHttpClient->myXmlreader->myCategoryList->getCategoryList());
278 *This function prcesses UI updating after a new top10List has been received.
279 *@todo Check where limitNr is taken, fixed or user input, see on_comboBoxTopCategory_currentIndexChanged.
281 void CarMainWindow::showTop10()
284 setListViewTopList(recentCategory, limitNr);
288 *This function is used to set items to labelTopList. Top-tab view.
290 *@param Size, number of results.
292 void CarMainWindow::setListViewTopList(QString category, int size)
294 qDebug() << "_setListViewTopList";
296 topList.append(myHttpClient->myXmlreader->myCategoryList->getTopList(category, size));
297 ui->labelTopList->setText(topList);
301 *This slot function is called when speed is achieved in measure dialog. Opens result dialog.
303 void CarMainWindow::openResultView()
309 *This slot function is called when registrate button is clicked.
311 void CarMainWindow::on_registratePushButton_clicked()
313 myRegistration->show();
317 *This slot function is called when ever refresh button clicked. Top-tab view.
319 void CarMainWindow::on_buttonTopRefresh_clicked()
321 myHttpClient->requestCategories();
325 *This slot function is called when ever category combobox current index changed. Top-tab view.
326 *@param QString category.
327 *@todo Check where limitNr is taken, fixed or user input, see showTop10.
329 void CarMainWindow::on_comboBoxTopCategory_currentIndexChanged(QString category)
331 qDebug() << "_on_comboBoxTopCategory_currentIndexChanged: " << category;
332 recentCategory = category; //for showTop10()
334 QString limit = QString::number(limitNr);
335 myHttpClient->requestTopList(category, limit);
339 *This slot function is called when set/change user button is clicked.
341 void CarMainWindow::on_setUserPushButton_clicked()
347 *@brief Just for development, for the real button is not shown until
348 *measurin started and there are results.
349 *@todo Implement with real code and yet leave sendXml in the bottom in use.
351 void CarMainWindow::on_manualStartButton_clicked()
357 * This slot function is called when timer gives timeout signal. Checks current speed
358 * and stores times in measure class.
360 void CarMainWindow::after_timeout()
362 //IF GPS checkbox is ON
363 if (ui->gpsOnCheckBox->isChecked())
365 if ( gpsSpeed > 1.0 )
373 ui->labelMeasureTabSpeed->setText(QString::number(this->speed)); //Set speed. //Measure-tab view.
374 ui->labelMeasureTabTime->setText(QString::number(this->time)); //Set time. //Measure-tab view.
379 * This slot function is called when Abort button is clicked.
381 void CarMainWindow::on_pushButtonMeasureTabAbort_clicked()
383 ui->pushButtonSendResult->setEnabled(false);
384 ui->pushButtonShowResultDialog->setEnabled(false);
385 ui->labelMeasureTabResult->hide();
386 ui->labelMeasureTabTime->setText("");
387 ui->labelMeasureTabSpeed->setText("");
388 measures->initializeMembers();
389 this->accelerometerTimer->stop();
393 ui->tabWidget->setCurrentWidget(this->ui->StartTab);
402 *This slot function is called when pushButtonSendResult is clicked.
403 *@todo Use real category value.
405 void CarMainWindow::on_pushButtonSendResult_clicked()
407 //Pick up relevant category name and pass it to the server
408 myHttpClient->sendResultXml(catList.at(choiceInt));
409 ui->pushButtonSendResult->setEnabled(false);
412 void CarMainWindow::updateUserName()
416 newUserName = myLogin->getUserName();
417 ui->userNameLabel->setText( "User: " + newUserName);
419 if (newUserName.length())
421 ui->setUserPushButton->setText( "Change User");
422 this->setWindowTitle("Speed Freak - " + newUserName);
426 ui->setUserPushButton->setText( "Set User");
427 this->setWindowTitle("Speed Freak");
431 void CarMainWindow::regUserToServer()
433 myHttpClient->requestRegistration();
437 void CarMainWindow::on_drawRoutePushButton_clicked()
439 QString routeFile = QString("route.txt");
440 if (myRoute->readRouteFromFile( routeFile) == true)
447 * Opens result dialog when show result button is clicked.
448 * Sends measures as parameter to the resultdialogs saveMeasuresToArray-function.
450 void CarMainWindow::on_pushButtonShowResultDialog_clicked()
452 result->saveMeasuresToArray(measures);
453 this->result->show();
456 void CarMainWindow::userLogin()
458 myHttpClient->checkLogin();
462 * Resets Accelerometer measurement variables
464 void CarMainWindow::resetAccelerometerMeasurements()
466 currentAcceleration = 0;
467 currentAccelerationString = "";
470 distanceTraveled = "";
471 //firstAcceleration = 0;
474 //lastScreenUpdateInSeconds = 0;
476 reverseAccelerationFlag = false;
478 //accelerometer->stop();
480 vehicleStartedMoving = false;
485 * This function is called to handle checkpoints
486 *@param totalTime total time elapsed since starting measurements
487 *@param currentSpeed current speed of the device
489 void CarMainWindow::handleCheckPoint(double totalTime, double currentSpeed)
491 switch (counterForSaveResults)
494 measures->setTime10kmh(totalTime);
498 measures->setTime20kmh(totalTime);
502 measures->setTime30kmh(totalTime);
506 measures->setTime40kmh(totalTime);
510 measures->setTime50kmh(totalTime);
514 measures->setTime60kmh(totalTime);
518 measures->setTime70kmh(totalTime);
522 measures->setTime80kmh(totalTime);
526 measures->setTime90kmh(totalTime);
530 measures->setTime100kmh(totalTime);
536 counterForSaveResults++;
538 if (choiceInt == 0 && measures->getTime40kmh() != 0)
540 setTimeAxisGapAndShowResult(measures->getTime40kmh());
542 this->accelerometerTimer->stop();
545 counterForSaveResults = 0;
547 else if (choiceInt == 1 && measures->getTime100kmh() != 0)
549 setTimeAxisGapAndShowResult(measures->getTime100kmh());
551 this->accelerometerTimer->stop();
554 counterForSaveResults = 0;
556 else if (choiceInt == 2 && measures->getTime10kmh() != 0)
558 setTimeAxisGapAndShowResult(measures->getTime10kmh());
560 this->accelerometerTimer->stop();
563 counterForSaveResults = 0;
565 else if (choiceInt != 1 && choiceInt != 0 && measures->getTime80kmh() != 0)
567 setTimeAxisGapAndShowResult(measures->getTime80kmh());
569 this->accelerometerTimer->stop();
572 counterForSaveResults = 0;
576 qDebug() << "something wrong in handleCheckPoint()";
581 *This function is called to read (and process) data from the accelerometer
583 void CarMainWindow::readAccelerometerData()
586 double changeInAcceleration = 0;
589 accelerometer->getAcceleration(x, y, z);
591 // keep the following line as close to the SetKinematicsProperties method as possible
592 currentTime = stopWatch.elapsed();
594 //accelerometer->smoothData(x, y, z);
597 x -= accelerometer->getCalibrationX();
598 y -= accelerometer->getCalibrationY();
599 z -= accelerometer->getCalibrationZ();
601 QString str = QString("acc x: " + QString::number(x) + "\n" +
602 "acc y: " + QString::number(y) + "\n" +
603 "acc z: " + QString::number(z) + "\n");
605 currentAcceleration = z;//sqrt(x*x + y*y + z*z);
606 changeInAcceleration = currentAcceleration;
608 if (((fabs(changeInAcceleration) <= accelerationStartThreshold)
609 && !vehicleStartedMoving))
613 else if(!vehicleStartedMoving)
615 vehicleStartedMoving = true;
621 calculate->calculateParameters(changeInAcceleration, (currentTime - previousTime)/1000);
622 previousTime = currentTime;
624 s.sprintf("%.2f", changeInAcceleration);
625 currentAccelerationString = s;
628 speed = calculate->getCurrentSpeed();
629 speed = speed*3.6;//((speed*1000)/kSecondsInHour);
630 s.sprintf("%.1f", speed);
633 s.sprintf("%.2f", calculate->getDistanceTraveled());
634 distanceTraveled = s;
640 time = calculate->getTotalTime();
642 s.sprintf("%.2f", time);
645 str.append("ca: " + currentAccelerationString + " G\n" );
646 str.append("cspeed: " + currentSpeed + " km/h \n" );
647 str.append("dist: " + distanceTraveled + " m \n" );
648 str.append("time: " + totalTime + " s \n" );
650 if ((stopTime > 0) && (previousTime >= stopTime))
652 // we want to end at a stopping point that the user chose
654 resetAccelerometerMeasurements();
659 *This function is used to calibrate accelerometer
661 void CarMainWindow::calibrateAccelerometer()
663 resetAccelerometerMeasurements();
664 accelerometer->calibrate();
668 *This slot function is called when GPS on checkbox state changed. Route-tab view.
671 void CarMainWindow::on_gpsOnCheckBox_stateChanged(int GPSState)
673 //Stop polling GPS. Route-tab view.
676 ui->labelRouteTabGPSStatus->setText("GPS status: GPS off");
677 location->stopPollingGPS();
681 //Start polling GPS. Route-tab view.
684 ui->labelRouteTabGPSStatus->setText("GPS status: GPS on");
685 location->startPollingGPS();
690 *This slot function is called when GPS status changed. Route- and measure-tab view.
692 void CarMainWindow::gpsStatus()
694 //IF GPS checkbox is ON
695 if (ui->gpsOnCheckBox->isChecked())
697 //If GPS find 4 satellite.
698 if (location->getSatellitesInUse() >= 4)
700 //Set gps status. Route-tab view.
701 ui->labelRouteTabGPSStatus->setText("GPS ready");
703 //Set time. Route-tab view.
704 gpsTime->setTime_t(location->getTime());
705 QString gpsDateNow = gpsTime->toString("dd.MM.yyyy hh:mm:ss");
706 ui->labelRouteTabGPSTime->setText("GPS time: " + gpsDateNow);
708 //Set latitude & longitude. Route-tab view.
709 ui->labelRouteTabLatitude->setText("Latitude: " + QString::number(location->getLatitude()));
710 ui->labelRouteTabLongitude->setText("Longitude: " + QString::number(location->getLongitude()));
712 //Set rec status. Route-tab view.
713 if (ui->startRecPushButton->text() == "Stop recording")
715 ui->labelRouteTabRecStatus->setText("Recorded " + QString::number(gpsData->roundCounter) + " point");
718 //Get speed. Route- and Measure-tab view.
719 gpsSpeed = location->getSpeed();
721 //Set speed. Route-tab view.
722 ui->labelRouteTabSpeed->setText("Speed:" + QString::number(gpsSpeed) + "km/h +/-" + QString::number(location->getEps()) + "km/h");
727 ui->labelMeasureTabSpeed->setText(QString::number(gpsSpeed)); //Set speed. //Measure-tab view.
728 ui->labelMeasureTabTime->setText(QString::number(timeFromGps)); //Set time. //Measure-tab view.
733 timer->stop(); //Measure timer
734 ui->labelMeasureTabResult->setText(QString::number(timeFromGps));
735 ui->labelMeasureTabResult->show();
736 ui->pushButtonShowResultDialog->setEnabled(true);
737 ui->pushButtonShowResultDialog->setEnabled(true);
741 //If GPS find less than 4 satellite.
744 ui->labelRouteTabGPSStatus->setText("GPS status: Waiting for GPS");
754 *This slot function is called when gps timer timeout(10ms).
756 void CarMainWindow::gpsTimerTimeout()
761 //IF time is 1 second
762 if (time1000ms == 1000)
764 //Calculate acceleration 1/s
765 gpsSpeedPrevious = gpsSpeedNow; //Previous speed
766 gpsSpeedNow = (location->getSpeed())/3.6; //Speed now (m/s)
767 gpsAcceleration = (gpsSpeedNow - gpsSpeedPrevious)/1; //Calculate acceleration: speed now - previous speed / 1s.
768 //Set acceleration. Route-tab view.
769 ui->labelRouteTabAcceleration->setText("Acceleration: " + QString::number( gpsAcceleration ) + " m/s2");
773 //Set GPS update time. Route-tab view.
774 ui->labelRouteTabGPSUpdateTime->setText("GPS update time: " + QString::number(gpsUpdateTime) + " ms");
778 *This slot function is called when start rec push button clicked. Route-tab view.
780 void CarMainWindow::on_startRecPushButton_clicked()
782 //Start route recording.
783 if (ui->startRecPushButton->text() == "Start recording")
785 ui->startRecPushButton->setText("Stop recording");
786 ui->labelRouteTabRecStatus->setText("Recording started");
787 gpsData->startRouteRecording(ui->labelRouteTabGPSTime->text());
790 //Stop route recording.
791 else if (ui->startRecPushButton->text() == "Stop recording")
793 ui->startRecPushButton->setText("Start recording");
794 ui->labelRouteTabRecStatus->setText("Recording stopped");
795 gpsData->stopRouteRecording(ui->labelRouteTabGPSTime->text());
800 *Sets time axis right way in result dialog and shows target speed result.
801 *@param double pTime is the target speed result time which is shown to the user.
803 void CarMainWindow::setTimeAxisGapAndShowResult(double pTime)
805 ui->pushButtonShowResultDialog->setEnabled(true);
806 ui->pushButtonSendResult->setEnabled(true);
808 timeInteger.setNum(pTime);
809 ui->labelMeasureTabResult->show();
810 ui->labelMeasureTabResult->setText(timeInteger);
812 if (floor(pTime) <= 5)
814 result->setDiagramGapHorizontal(80);
817 else if (floor(pTime) <= 10)
819 result->setDiagramGapHorizontal(40);
824 result->setDiagramGapHorizontal(20);
828 void CarMainWindow::on_calibrateButton_clicked()
830 ui->autoStartButton->setEnabled(true);
831 ui->manualStartButton->setEnabled(true);
833 this->accelerometer->calibrate();