Added implementation to handleCheckPoint slot function in carmainwindow.cpp. Now...
[speedfreak] / Client / carmainwindow.cpp
index ee146ff..7530361 100644 (file)
@@ -5,6 +5,8 @@
  * @author     Janne Änäkkälä <janne.anakkala@fudeco.com>
  * @author     Tiina Kivilinna-Korhola <tiina.kivilinna-korhola@fudeco.com>
  * @author     Olavi Pulkkinen <olavi.pulkkinen@fudeco.com>
+ * @author     Rikhard Kuutti <rikhard.kuutti@fudeco.com>
+ * @author     Kai Rasilainen <kai.rasilainen@fudeco.com>
  * @copyright  (c) 2010 Speed Freak team
  * @license    http://opensource.org/licenses/gpl-license.php GNU Public License
  */
 #include "carmainwindow.h"
 #include "math.h"
 
+#define kAccelerometerSampleRate    50
+#define kFilteringFactor            0.2
+#define kSecondsInHour              3600
+
 /**
   *Constructor of this class.
   *@param QWidget pointer to parent object. By default the value is NULL.
 CarMainWindow::CarMainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::CarMainWindow)
 {
     ui->setupUi(this);
-    //result = new ResultDialog();
+    ui->tabWidget->setCurrentWidget(this->ui->StartTab);
+    result = new ResultDialog();
     //measure = new MeasureDialog();
-    xmlreader = new XmlReader();
+    welcomeDialog = new WelcomeDialog();
+    welcomeDialog->show();
 
     initComboBoxStartTabUnits();
     initListViewStartTabAccelerationCategories();
 
     myLogin = new LoginWindow(this);
+    categorylist = new CategoryList();
+    myHttpClient = new HttpClient(this);
     myRegistration = new Registration(this);
-    xmlwriter = new XmlWriter();
-    manager = new QNetworkAccessManager(this);
-    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(networkResponse(QNetworkReply*)));
-    connect(myRegistration,SIGNAL(sendregistration()),this,SLOT(registrate()));
-    connect(this,SIGNAL(sendresult()),this,SLOT(sendXml()));
+    connect(myRegistration,SIGNAL(sendregistration()),this,SLOT(regUserToServer()));
+    connect(myLogin,SIGNAL(userNameChanged()),this,SLOT(userLogin()));
+    myRoute = new RouteDialog( this);
+
+    //GPS
+    location = new Maemo5Location(this);
+    gpsData = new GPSData(location);
+    connect(location,SIGNAL(agnss()),this,SLOT(gpsStatus()));
+    gpsTime = new QDateTime();
 
     time = 0;
     speed = 0;
+    counterForSaveResults = 0;
     timer = new QTimer();
 
+    // Accelerometer
     accelerometer = new Accelerometer();
-    accelerometer->setSampleRate(100);
+
+    reverseAccelerationFlag = false;
+    vehicleStartedMoving = false;
+    isNewRun = true;
+    isSetup = false;
+    stopTime = 0;
+    accelerationStartThreshold = 0.02;
+
+    QTimer *accelerometerTimer = new QTimer(this);
+    connect(accelerometerTimer, SIGNAL(timeout()), this, SLOT(readAccelerometerData()));
+    accelerometerTimer->start(kAccelerometerSampleRate);
+
+    // Calculate
+    calculate = new Calculate();
+    connect(calculate, SIGNAL(checkPointReached()), this, SLOT(handleCheckPoint()));
+
+    resetAccelerometerMeasurements();
 
     measures = new Measures();
     this->initializeMeasures();
@@ -47,22 +79,34 @@ CarMainWindow::CarMainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::Ca
     timer->setInterval(300);
 
     connect(this->timer, SIGNAL(timeout()), this, SLOT(after_timeout()));
+    connect(myLogin, SIGNAL( userNameChanged()), this, SLOT(updateUserName()));
 
     ui->labelMeasureTabResult->hide();
+    ui->pushButtonShowResultDialog->setEnabled(false);
+
+    this->setWindowTitle("Speed Freak");
 
 }
 
 /**
-  *Destructor of this class. Should be used to release all allocated resources.
+  *Destructor of this class. Deletes all dynamic objects and sets them to NULL.
   */
 CarMainWindow::~CarMainWindow()
 {
     delete ui;
+    ui = NULL;
     //delete result;
     //delete measure;
-    delete xmlreader;
-    delete xmlwriter;
-    delete manager;
+    delete categorylist;
+    categorylist = NULL;
+    delete welcomeDialog;
+    welcomeDialog = NULL;
+    delete myRoute;
+    myRoute = NULL;
+    delete gpsData;
+    gpsData = NULL;
+    delete gpsTime;
+    gpsTime = NULL;
 }
 
 /**
@@ -100,15 +144,33 @@ void CarMainWindow::on_listViewStartTabAccelerationCategories_clicked(QModelInde
   */
 void CarMainWindow::on_autoStartButton_clicked()
 {
+    initializeMeasures();
+    ui->pushButtonShowResultDialog->setEnabled(false);
+    choice = ui->listViewStartTabAccelerationCategories->currentIndex();
+    choiceInt = choice.row();
+    qDebug() << choiceInt;
+    if (choiceInt == 0)
+    {
+        ui->labelMeasureTabHeader->setText("Accelerate to 40 km/h");
+        result->setDiagramGapStem(75);
+    }
+
+    else if (choiceInt == 1)
+    {
+        ui->labelMeasureTabHeader->setText("Accelerate to 100 km/h");
+        result->setDiagramGapStem(30);
+    }
+
+    else
+    {
+        ui->labelMeasureTabHeader->setText("Accelerate to 80 km/h");
+        result->setDiagramGapStem(37.5);
+    }
+    ui->labelMeasureTabResult->setText("");
 
-    //delete measure;
-    //measure = NULL;
-    //measure = new MeasureDialog();
-   // connect(measure, SIGNAL(speedAchieved()), this, SLOT(openResultView()));
-    accelerometer->start();
     timer->start();
-    // Show measure dialog.
-    //measure->show();
+    time = 0;
+    speed = 0;
     ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
 }
 
@@ -165,31 +227,17 @@ void CarMainWindow::setListViewStartTabAccelerationCategories(QStringList accele
   */
 void CarMainWindow::setCategoryCompoBox()
 {
-    ui->comboBoxTopCategory->addItems(xmlreader->getTop10List());
+    ui->comboBoxTopCategory->addItems(categorylist->getCategoryList());
 }
 
 /**
   *This function is used to set items to labelTopList. Top-tab view.
   *@param QString category
   */
-void CarMainWindow::setListViewTopList(QString category)
+void CarMainWindow::setListViewTopList(QString category, int size)
 {
     QString topList;
-
-    if (category == "acceleration-0-100")
-    {
-        topList.append(xmlreader->getTop10AccelerationList());
-    }
-
-    else if (category == "Speed")
-    {
-        topList.append(xmlreader->getTop10SpeedList());
-    }
-
-    else if (category == "G-force")
-    {
-        topList.append(xmlreader->getTop10GforceList());
-    }
+    topList.append( categorylist->getTopList(category, size));
     ui->labelTopList->setText(topList);
 }
 
@@ -198,45 +246,7 @@ void CarMainWindow::setListViewTopList(QString category)
   */
 void CarMainWindow::openResultView()
 {
-    //result->saveMeasuresToArray(measure->measures);
-    // Show result dialog.
-    //result->show();
-    QString timeInteger;
-    timeInteger.setNum(this->measures->getTime40kmh());
-    //time = "0 - 40 km/h: ";
-    //time.append(timeInteger);
-    //ui->labelResult40kmh->setText(time);
-    ui->labelMeasureTabResult->show();
-    ui->labelMeasureTabResult->setText(timeInteger);
-    //ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
-}
-
-/**
-  *This slot function is called when the server has finished guery.
-  */
-void CarMainWindow::networkResponse(QNetworkReply *reply)
-{
-
-}
-
-/**
-  *This slot function is called when the user will to send data to server.
-  *@todo Where is this callback connected?
-  */
-void CarMainWindow::on_pushButton_clicked()
-{
-     sendXml();
-}
-
-/**
-  *This slot function is called when login/logout button is clicked.
-  */
-void CarMainWindow::on_loginLogoutButton_clicked()
-{
-    //LoginWindow myLogin;
 
-    myLogin->show();
-    //ui->loginLogoutButton->setText("logout");
 }
 
 /**
@@ -252,17 +262,22 @@ void CarMainWindow::on_registratePushButton_clicked()
   */
 void CarMainWindow::on_buttonTopRefresh_clicked()
 {
-    //setCategoryCompoBox();
-    requestTopList();
+    myHttpClient->requestCategories();
+    setCategoryCompoBox();
 }
 
 /**
   *This slot function is called when ever category combobox current index changed. Top-tab view.
   *@param QString category
+  *@todo Check where limitNr is taken.
   */
 void CarMainWindow::on_comboBoxTopCategory_currentIndexChanged(QString category)
 {
-    setListViewTopList(category);
+    int limitNr = 5;                    //replace with real value?
+    QString limit = QString::number(limitNr);
+    category = "acceleration-0-100";    //replace with real value from category list/top window
+    myHttpClient->requestTopList(category, limit);
+    setListViewTopList(category,10);
 }
 
 /**
@@ -271,7 +286,7 @@ void CarMainWindow::on_comboBoxTopCategory_currentIndexChanged(QString category)
   */
 void CarMainWindow::on_comboBoxTopCategory_activated(QString category)
 {
-    setListViewTopList(category);
+    setListViewTopList(category,10);
 }
 
 /**
@@ -280,312 +295,424 @@ void CarMainWindow::on_comboBoxTopCategory_activated(QString category)
 void CarMainWindow::on_setUserPushButton_clicked()
 {
     myLogin->show();
-
-    ui->userNameLabel->setText( "User: " + myLogin->getUserName());
-    ui->setUserPushButton->setText( "Change User");
 }
 
 /**
-  *@brief Sends registration information to the server in xml format.
-  *Reads user name, password and emaol address from resuldialogs internal variables.
-  *@todo Replace msg box with better reaction to server`s responce.
-  *@todo Write error handling.
+  *@brief Just for development, for the real button is not shown until
+  *measurin started and there are results.
+  *@todo Implement with real code and yet leave sendXml in the bottom in use.
   */
-void CarMainWindow::registrate()
+void CarMainWindow::on_manualStartButton_clicked()
 {
-    qDebug() << "_registrate" ;
-    qDebug() << this->myRegistration->getUserName() << "+" << this->myRegistration->getPassword() << "+" << this->myRegistration->getEmail();
-
-    QBuffer *regbuffer = new QBuffer();
-    QNetworkReply *currentDownload;
-
-    QUrl qurl("http://api.speedfreak-app.com/register");
-    QNetworkRequest request(qurl);
 
-    //write also to a file during development, :
-    xmlwriter->writeXml(this->myRegistration->getUserName(),
-                      this->myRegistration->getPassword(),
-                      this->myRegistration->getEmail());
-    xmlwriter->writeRegistering(regbuffer,
-                      this->myRegistration->getUserName(),
-                      this->myRegistration->getPassword(),
-                      this->myRegistration->getEmail());
-    //Tmp msgbox - later server responce
-    QMessageBox::about(this,"Registrate",this->myRegistration->getUserName() + this->myRegistration->getPassword() + this->myRegistration->getEmail());
-
-    currentDownload = manager->post(request, ("data=" + regbuffer->data()));
-
-    //ackFromServer function gets called when HTTP request is completed
-    connect(currentDownload, SIGNAL(finished()),SLOT(ackOfRegistration()));
-    manager->post(request, ("data=" + regbuffer->data()));
-
-    //ackOfRegistration function gets called when HTTP request is completed
-    //connect(currentDownload, SIGNAL(finished()), this, SLOT(ackOfRegistration()));
-    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ackOfRegistration(QNetworkReply*)));
-    connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
 }
 
 /**
-  *@brief Sends result(s) to the server in xml format with authentication information in the header.
-  *@todo Write error handling.
+  * This slot function is called when timer gives timeout signal. Checks current speed
+  * and stores times in measure class.
   */
-void CarMainWindow::sendXml()
+void CarMainWindow::after_timeout()
 {
-    qDebug() << "_sendXml";
-
-    QBuffer *xmlbuffer = new QBuffer();
-    QNetworkReply *currentDownload;
-
-    QString category_name = "acceleration-0-100";    //replace with real value from category list
-
-    QString credentials = this->myRegistration->getUserName() + ":" + this->myRegistration->getPassword();
-    credentials = "Basic " + credentials.toAscii().toBase64();
-
-    QUrl qurl("http://api.speedfreak-app.com/update/category_name");
-    QNetworkRequest request(qurl);
-
-    request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
-
-    xmlwriter->writeResult(xmlbuffer);
-
-    //currentDownload = manager->post(request, ("data=" + xmlbuffer->data()));
-    manager->post(request, ("data=" + xmlbuffer->data()));
-    //QString data("abcdefg");    //testing
-    //currentDownload = manager->post(request,"data=" + QUrl::toPercentEncoding(data));   //testing
-
-    //ackOfResult function gets called when HTTP request is completed
-    //connect(currentDownload, SIGNAL(finished()), this, SLOT(ackOfResult()));
-    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ackOfResult(QNetworkReply*)));
-    connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
+    QString timeString, speedString;
+    //time++;
+    //speed = speed +10;
+    timeString.setNum(time);
+    speedString.setNum(speed);
+    ui->labelMeasureTabTime->setText(timeString);
+    ui->labelMeasureTabSpeed->setText(speedString);
 
+    //handleCheckPoint(time, speed);
 }
 
 /**
-  *@brief Sends request to the server for a top list with authentication information in the header.
-  *@todo Write error handling.
-  *@todo Replace with real value from category list and limit
+  * Initializes measures class's member variables.
   */
-void CarMainWindow::requestTopList()
+void CarMainWindow::initializeMeasures()
 {
-    qDebug() << "_registrate" ;
-
-    QString category_name = "acceleration-0-100";    //replace with real value from category list/top window
-    int limit = 5;
-    //QNetworkReply *currentDownload;
-
-    QString credentials = this->myRegistration->getUserName() + ":" + this->myRegistration->getPassword();
-    credentials = "Basic " + credentials.toAscii().toBase64();
-
-    QUrl qurl("http://api.speedfreak-app.com/results/category_name/limit");
-    QNetworkRequest request(qurl);
-
-    request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
-
-    //currentDownload = manager->post(request, ("data=" ));
-    manager->post(request, ("data=" ));
-
-    //ackOfResult function gets called when HTTP request is completed
-    //connect(currentDownload, SIGNAL(error()),SLOT(errorFromServer()));
-    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(networkResponse(QNetworkReply*)));
-    connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
+    measures->setTime10kmh(0);
+    measures->setTime20kmh(0);
+    measures->setTime30kmh(0);
+    measures->setTime40kmh(0);
+    measures->setTime50kmh(0);
+    measures->setTime60kmh(0);
+    measures->setTime70kmh(0);
+    measures->setTime80kmh(0);
+    measures->setTime90kmh(0);
+    measures->setTime100kmh(0);
 }
 
 /**
-  *@brief React to servers responce after result has been sent.
-  *@todo Implement function and write error handling.
+  * This slot function is called when Abort button is clicked.
   */
-void CarMainWindow::ackOfResult(QNetworkReply* reply)
+void CarMainWindow::on_pushButtonMeasureTabAbort_clicked()
 {
-    qDebug() << "_ackOfResult";
-    QNetworkReply::NetworkError errorcode;
-    errorcode = reply->error();
-    if(errorcode != 0) {
-        qDebug() << errorcode << reply->errorString();
-    }
-    else {
-        qDebug() << errorcode;
-    }
+    measures->setTime10kmh(0);
+    measures->setTime20kmh(0);
+    measures->setTime30kmh(0);
+    measures->setTime40kmh(0);
+    measures->setTime50kmh(0);
+    measures->setTime60kmh(0);
+    measures->setTime70kmh(0);
+    measures->setTime80kmh(0);
+    measures->setTime90kmh(0);
+    measures->setTime100kmh(0);
+    timer->stop();
+    time = 0;
+    speed = 0;
+    ui->tabWidget->setCurrentWidget(this->ui->StartTab);
+    //this->close();
 }
 
-/**
-  *@brief React to servers responce after registration has been sent.
-  *@todo Implement function and write error handling.
-  */
-void CarMainWindow::ackOfRegistration(QNetworkReply* reply)
-{
-    qDebug() << "_ackOfRegistration";
-    qDebug() << reply->readAll();
-    QNetworkReply::NetworkError errorcode;
-    errorcode = reply->error();
-    if(errorcode != 0) {
-        qDebug() << errorcode << reply->errorString();
+void CarMainWindow::on_pushButtonSendResult_clicked()
+{
+    myHttpClient->sendResultXml();
+    ui->pushButtonSendResult->setEnabled(false);
+}
+
+void CarMainWindow::updateUserName()
+{
+    QString newUserName;
+
+    newUserName = myLogin->getUserName();
+    ui->userNameLabel->setText( "User: " + newUserName);
+
+    if (newUserName.length())
+    {
+       ui->setUserPushButton->setText( "Change User");
+       this->setWindowTitle("Speed freak - " + newUserName);
     }
-    else {
-        qDebug() << errorcode;
+    else
+    {
+        ui->setUserPushButton->setText( "Set User");
+        this->setWindowTitle("Speed freak");
     }
 }
 
+void CarMainWindow::regUserToServer()
+{
+    myHttpClient->requestRegistration();
+}
 
 
-void CarMainWindow::errorFromServer(QNetworkReply* reply)
+void CarMainWindow::on_drawRoutePushButton_clicked()
 {
-    qDebug() << "_errorFromServer";
-    QNetworkReply::NetworkError errorcode;
+    myRoute->show();
+}
 
-    errorcode = reply->error();
-    if(errorcode != 0) {
-        qDebug() << errorcode;
-    }
-    else {
-        qDebug() << errorcode;
-    }
+/**
+  * Opens result dialog when show result button is clicked.
+  * Sends measures as parameter to the resultdialogs saveMeasuresToArray-function.
+  */
+void CarMainWindow::on_pushButtonShowResultDialog_clicked()
+{
+    result->saveMeasuresToArray(measures);
+    this->result->show();
+}
 
+void CarMainWindow::userLogin()
+{
+    myHttpClient->checkLogin();
 }
 
 /**
-  *@brief Just for development, for the real button is not shown until
-  *measurin started and there are results.
-  *@todo Implement with real code and yet leave sendXml in the bottom in use.
+  * Resets Accelerometer measurement variables
   */
-void CarMainWindow::on_manualStartButton_clicked()
-{
-    sendXml();
+void CarMainWindow::resetAccelerometerMeasurements()
+{
+    currentAcceleration = 0;
+    currentAccelerationString = "";
+    currentSpeed = "";
+    currentTime = 0;
+    distanceTraveled = "";
+    firstAcceleration = 0;
+    //horsepower = null;
+    isNewRun = true;
+    //lastScreenUpdateInSeconds = 0;
+    previousTime = 0;
+    reverseAccelerationFlag = false;
+    stopWatch.setHMS(0, 0, 0, 0);
+    //accelerometer->stop();
+    totalTime = "";
+    vehicleStartedMoving = false;
+    calculate->reset();
 }
 
 /**
-  * This slot function is called when timer gives timeout signal. Checks current speed
-  * and stores times in measure class.
+  * This function is called to handle checkpoints
+  *@param totalTime total time elapsed since starting measurements
+  *@param currentSpeed current speed of the device
   */
-void CarMainWindow::after_timeout()
+void CarMainWindow::handleCheckPoint(double totalTime, double currentSpeed)
 {
-    QString timeString, speedString;
-    //time++;
-    time = accelerometer->getTotalTime();
-    speed = accelerometer->getCurrentSpeed();
-    //speed = speed +10;
-
-    if (floor(speed) == 10)
+    switch (counterForSaveResults)
     {
-        measures->setTime10kmh(time);
-    }
+    case 0:
+        measures->setTime10kmh(totalTime);
+        break;
 
-    else if (floor(speed) == 20)
-    {
-        measures->setTime20kmh(time);
+    case 1:
+        measures->setTime20kmh(totalTime);
+        break;
+
+    case 2:
+        measures->setTime30kmh(totalTime);
+        break;
+
+    case 3:
+        measures->setTime40kmh(totalTime);
+        break;
+
+    case 4:
+        measures->setTime50kmh(totalTime);
+        break;
+
+    case 5:
+        measures->setTime60kmh(totalTime);
+        break;
+
+    case 6:
+        measures->setTime70kmh(totalTime);
+        break;
+
+    case 7:
+        measures->setTime80kmh(totalTime);
+        break;
+
+    case 8:
+        measures->setTime90kmh(totalTime);
+        break;
+
+    case 9:
+        measures->setTime100kmh(totalTime);
+        break;
+
+    default:
+        break;
     }
+    counterForSaveResults++;
 
-    else if (floor(speed) == 30)
+    if (choiceInt == 0 && measures->getTime40kmh() != 0)
     {
-        measures->setTime30kmh(time);
+        setTimeAxisGapAndShowResult(measures->getTime40kmh());
+        timer->stop();
+        //this->accelerometerTimer->stop();
+        time = 0;
+        speed = 0;
+        counterForSaveResults = 0;
     }
 
-    else if (floor(speed) == 40)
+    else if (choiceInt == 1 && measures->getTime100kmh() != 0)
     {
-        measures->setTime40kmh(time);
+        setTimeAxisGapAndShowResult(measures->getTime100kmh());
+        timer->stop();
+        //this->accelerometerTimer->stop();
+        time = 0;
+        speed = 0;
+        counterForSaveResults = 0;
+
     }
 
-    else if (floor(speed) == 50)
+    else if (choiceInt != 1 && choiceInt != 0 && measures->getTime80kmh() != 0)
     {
-        measures->setTime50kmh(time);
+        setTimeAxisGapAndShowResult(measures->getTime80kmh());
+        timer->stop();
+        //this->accelerometerTimer->stop();
+        time = 0;
+        speed = 0;
+        counterForSaveResults = 0;
     }
 
-    else if (floor(speed) == 60)
+    else
     {
-        measures->setTime60kmh(time);
+
     }
+}
+
+/**
+  *This function is called to read (and process) data from the accelerometer
+  */
+void CarMainWindow::readAccelerometerData()
+{
+    QString s;
+    double changeInAcceleration = 0;
+    qreal x, y, z;
+
+    accelerometer->getAcceleration(x, y, z);
+    accelerometer->smoothData(x, y, z);
+
+    // Apply calibration
+    x -= accelerometer->getCalibrationX();
+    y -= accelerometer->getCalibrationY();
+    z -= accelerometer->getCalibrationZ();
 
-    else if (floor(speed) == 70)
+    QString str = QString("acc x: " + QString::number(x) + "\n" +
+                          "acc y: " + QString::number(y) + "\n" +
+                          "acc z: " + QString::number(z) + "\n");
+
+    if (!vehicleStartedMoving)
     {
-        measures->setTime70kmh(time);
+        if (isNewRun)
+        {
+            firstAcceleration = sqrt(x*x + y*y + z*z);
+            //firstAcceleration = y; // first read
+            isNewRun = false;
+        }
     }
 
-    else if (floor(speed) == 80)
+    currentAcceleration = sqrt(x*x + y*y + z*z);
+    changeInAcceleration = (currentAcceleration - firstAcceleration); // firstAcceleration only gets set once
+
+    if (((abs(changeInAcceleration) <= accelerationStartThreshold)
+                && !vehicleStartedMoving))
     {
-        measures->setTime80kmh(time);
+        return;
     }
 
-    else if (floor(speed) == 90)
+    if (reverseAccelerationFlag)
     {
-        measures->setTime90kmh(time);
+        // will be false until after 1st calculation
+        if ((changeInAcceleration <= 0))
+        {
+            // actually increasing here...
+            changeInAcceleration = abs(changeInAcceleration);
+        }
+        else
+        {
+            // actually decreasing here...
+            changeInAcceleration = (changeInAcceleration * -1);
+        }
     }
-
-    else if (floor(speed) == 100)
+    if (!vehicleStartedMoving)
     {
-        measures->setTime100kmh(time);
+        if ((changeInAcceleration < 0))
+        {
+            // we started to move backwards first time through
+            reverseAccelerationFlag = true;
+            changeInAcceleration = abs(changeInAcceleration);
+        }
+        vehicleStartedMoving = true;
+
+        stopWatch.setHMS(0, 0, 0, 0);
+        stopWatch.start();
     }
+    //  keep the following line as close to the SetKinematicsProperties method as possible
+    currentTime = stopWatch.elapsed();
+    calculate->calculateParameters(changeInAcceleration, (currentTime - previousTime)/1000);
+    previousTime = currentTime;
 
-    else
-    {
+    s.sprintf("%.2f", changeInAcceleration);
+    currentAccelerationString = s;
 
-    }
+    speed = 0.0;
+    speed = calculate->getCurrentSpeed();
+    speed = ((speed*1000)/kSecondsInHour);
+    s.sprintf("%.2f", speed);
+    currentSpeed = s;
 
-    // If speed is over 40 km/h emits speedAchieved() signal and close this dialog.
-    if (speed >= 40.0)
-    {
-        timer->stop();
-        accelerometer->stop();
-        time = 0;
-        speed = 0;
-        //emit this->speedAchieved();
-        this->openResultView();
-        //this->close();
+    s.sprintf("%.2f", calculate->getDistanceTraveled());
+    distanceTraveled = s;
 
-    }
+    // TODO
+    //distanceTraveled;
+    //horsepower;
 
-    // Updates speed and time.
-    else
-    {
-        timeString.setNum(time);
-        speedString.setNum(speed);
-        ui->labelMeasureTabTime->setText(timeString);
-        ui->labelMeasureTabSpeed->setText(speedString);
+    time = calculate->getTotalTime();
+
+    s.sprintf("%.2f", time);
+    totalTime = s;
 
-        timer->start();
+    str.append("ca: " + currentAccelerationString + " G\n" );
+    str.append("cspeed: " + currentSpeed + " km/h \n" );
+    str.append("dist: " + distanceTraveled + " m \n" );
+    str.append("time: " + totalTime + " s \n" );
+
+    if ((stopTime > 0) && (previousTime >= stopTime))
+    {
+        // we want to end at a stopping point that the user chose
+        // output results
+        resetAccelerometerMeasurements();
     }
+}
 
+/**
+  *This function is used to calibrate accelerometer
+  */
+void CarMainWindow::calibrateAccelerometer()
+{
+    resetAccelerometerMeasurements();
+    accelerometer->calibrate();
 }
 
 /**
-  * Initializes measures class's member variables.
+  *This slot function is called when GPS on checkbox state changed.  Route-tab view.
+  *@param int GPSState
   */
-void CarMainWindow::initializeMeasures()
+void CarMainWindow::on_gpsOnCheckBox_stateChanged(int GPSState)
 {
-    measures->setTime10kmh(0);
-    measures->setTime20kmh(0);
-    measures->setTime30kmh(0);
-    measures->setTime40kmh(0);
-    measures->setTime50kmh(0);
-    measures->setTime60kmh(0);
-    measures->setTime70kmh(0);
-    measures->setTime80kmh(0);
-    measures->setTime90kmh(0);
-    measures->setTime100kmh(0);
+    if (GPSState == 0)
+    {
+        ui->labelRouteTabGPSStatus->setText("GPS off");//testing
+        location->stopPollingGPS();
+    }
+    else
+    {
+        ui->labelRouteTabGPSStatus->setText("GPS on");//testing
+        location->startPollingGPS();
+    }
 }
 
 /**
-  * This slot function is called when Abort button is clicked.
+  *This slot function is called when GPS status changed.  Route-tab view.
   */
-void CarMainWindow::on_pushButtonMeasureTabAbort_clicked()
+void CarMainWindow::gpsStatus()
 {
-    measures->setTime10kmh(0);
-    measures->setTime20kmh(0);
-    measures->setTime30kmh(0);
-    measures->setTime40kmh(0);
-    measures->setTime50kmh(0);
-    measures->setTime60kmh(0);
-    measures->setTime70kmh(0);
-    measures->setTime80kmh(0);
-    measures->setTime90kmh(0);
-    measures->setTime100kmh(0);
-    timer->stop();
-    accelerometer->stop();
-    time = 0;
-    speed = 0;
-    ui->tabWidget->setCurrentWidget(this->ui->StartTab);
-    //this->close();
+    if (ui->gpsOnCheckBox->isChecked())
+    {
+        if (location->getSatellitesInUse() >= 4)
+        {
+            //Set status
+            ui->labelRouteTabGPSStatus->setText("GPS ready");
+
+            //Set time
+            gpsTime->setTime_t(location->getTime());
+            ui->labelRouteTabGPSTime->setText(gpsTime->toString());
+
+            //Set latitude & longitude
+            ui->labelRouteTabLatitude->setText("Lat: " + QString::number(location->getLatitude()));
+            ui->labelRouteTabLongitude->setText("Lon: " + QString::number(location->getLongitude()));
+        }
+
+        else
+        {
+            ui->labelRouteTabGPSStatus->setText("Waiting for GPS");
+        }
+    }
 }
 
-void CarMainWindow::on_pushButtonSendResult_clicked()
+/**
+  *Sets time axis right way in result dialog and shows target speed result.
+  *@param double pTime is the target speed result time which is shown to the user.
+  */
+void CarMainWindow::setTimeAxisGapAndShowResult(double pTime)
 {
-    emit sendresult();
+    ui->pushButtonShowResultDialog->setEnabled(true);
+    QString timeInteger;
+    timeInteger.setNum(pTime);
+    ui->labelMeasureTabResult->show();
+    ui->labelMeasureTabResult->setText(timeInteger);
+
+    if (floor(pTime) <= 5)
+    {
+        result->setDiagramGapHorizontal(80);
+    }
+
+    else if (floor(pTime) <= 10)
+    {
+        result->setDiagramGapHorizontal(40);
+    }
+
+    else
+    {
+        result->setDiagramGapHorizontal(20);
+    }
 }