a3aa67a8d8523088983af3274384d0080e96e490
[speedfreak] / Client / carmainwindow.cpp
1 /*
2  * CarMainWindow main class
3  *
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  * @copyright  (c) 2010 Speed Freak team
9  * @license    http://opensource.org/licenses/gpl-license.php GNU Public License
10  */
11
12 #include "carmainwindow.h"
13 #include "math.h"
14
15 /**
16   *Constructor of this class.
17   *@param QWidget pointer to parent object. By default the value is NULL.
18   */
19 CarMainWindow::CarMainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::CarMainWindow)
20 {
21     ui->setupUi(this);
22     //result = new ResultDialog();
23     //measure = new MeasureDialog();
24     xmlreader = new XmlReader();
25
26     initComboBoxStartTabUnits();
27     initListViewStartTabAccelerationCategories();
28
29     myLogin = new LoginWindow(this);
30     myRegistration = new Registration(this);
31     xmlwriter = new XmlWriter();
32     manager = new QNetworkAccessManager(this);
33     connect(myRegistration,SIGNAL(sendregistration()),this,SLOT(registrate()));
34
35     time = 0;
36     speed = 0;
37     timer = new QTimer();
38
39     accelerometer = new Accelerometer();
40     accelerometer->setSampleRate(100);
41
42     measures = new Measures();
43     this->initializeMeasures();
44
45     timer->setInterval(300);
46
47     connect(this->timer, SIGNAL(timeout()), this, SLOT(after_timeout()));
48     connect(myLogin, SIGNAL( userNameChanged()), this, SLOT(updateUserName()));
49
50     ui->labelMeasureTabResult->hide();
51
52     this->setWindowTitle("Speed freak");
53
54 }
55
56 /**
57   *Destructor of this class. Should be used to release all allocated resources.
58   */
59 CarMainWindow::~CarMainWindow()
60 {
61     delete ui;
62     //delete result;
63     //delete measure;
64     delete xmlreader;
65     delete xmlwriter;
66     delete manager;
67 }
68
69 /**
70   *This function is used to .
71   *@param
72   */
73 void CarMainWindow::changeEvent(QEvent *e)
74 {
75     QMainWindow::changeEvent(e);
76     switch (e->type()) {
77     case QEvent::LanguageChange:
78         ui->retranslateUi(this);
79         break;
80     default:
81         break;
82     }
83 }
84
85 /**
86   *This slot function is called when ever list view is update. Start-tab view.
87   */
88 void CarMainWindow::on_listViewStartTabAccelerationCategories_clicked(QModelIndex index)
89 {
90     QString str = index.data().toString();
91     QStringList list = str.split("-");
92     QStringList list2 = list[1].split(" ");
93
94     ui->lineEditStartTabMin->setText(list[0]);
95     ui->lineEditStartTabMax->setText(list2[0]);
96     updateComboBoxStartTabUnits(list2[1]);
97 }
98
99 /**
100   *This slot function is called when ever auto start button clicked. Start-tab view.
101   */
102 void CarMainWindow::on_autoStartButton_clicked()
103 {
104
105     //delete measure;
106     //measure = NULL;
107     //measure = new MeasureDialog();
108    // connect(measure, SIGNAL(speedAchieved()), this, SLOT(openResultView()));
109     accelerometer->start();
110     timer->start();
111     // Show measure dialog.
112     //measure->show();
113     ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
114 }
115
116 /**
117   *This slot function is called when ever list view is update. Start-tab view.
118   *@param QString unit.
119   */
120 void CarMainWindow::updateComboBoxStartTabUnits(QString unit)
121 {
122     ui->comboBoxStartTabUnits->setCurrentIndex(ui->comboBoxStartTabUnits->findText(unit, Qt::MatchExactly));
123 }
124
125 /**
126   *This function is used to init unit combobox. Start-tab view.
127   */
128 void CarMainWindow::initComboBoxStartTabUnits()
129 {
130     units << "km/h" << "km" << "h" << "m" << "min" << "Mile" << "Mph" << "in" << "ft" << "yrd";
131     ui->comboBoxStartTabUnits->addItems(units);
132 }
133
134 /**
135   *This function is used to set items to unit combobox. Start-tab view.
136   *@param QStringlist units
137   */
138 void CarMainWindow::setComboBoxStartTabUnits(QStringList units)
139 {
140     ui->comboBoxStartTabUnits->addItems(units);
141 }
142
143 /**
144   *This function is used to init listViewStartTabAccelerationCategories. Start-tab view.
145   */
146 void CarMainWindow::initListViewStartTabAccelerationCategories()
147 {
148     accelerationCategoriesStartTab << "0-40 km/h" << "0-100 km/h"; //<< "0-1/4 Mile" << "0-1/8 Mile" << "0-50 km" << "50-100 Mile" << "0-60 Mph" << "0-100 m" << "0-50 ft" << "0-50 yrd" << "0-500 in";
149     QAbstractItemModel *model = new StringListModel(accelerationCategoriesStartTab);
150     ui->listViewStartTabAccelerationCategories->setModel(model);
151 }
152
153 /**
154   *This function is used to set items to listViewStartTabAccelerationCategories. Start-tab view.
155   *@param QStringlist accelerationCategoriesStartTab
156   */
157 void CarMainWindow::setListViewStartTabAccelerationCategories(QStringList accelerationCategoriesStartTab)
158 {
159     QAbstractItemModel *model = new StringListModel(accelerationCategoriesStartTab);
160     ui->listViewStartTabAccelerationCategories->setModel(model);
161 }
162
163 /**
164   *This function is used to set items to category combobox. Top-tab view.
165   *@param
166   */
167 void CarMainWindow::setCategoryCompoBox()
168 {
169     ui->comboBoxTopCategory->addItems(xmlreader->getTop10List());
170 }
171
172 /**
173   *This function is used to set items to labelTopList. Top-tab view.
174   *@param QString category
175   */
176 void CarMainWindow::setListViewTopList(QString category)
177 {
178     QString topList;
179
180     if (category == "acceleration-0-100")
181     {
182         topList.append(xmlreader->getTop10AccelerationList());
183     }
184
185     else if (category == "Speed")
186     {
187         topList.append(xmlreader->getTop10SpeedList());
188     }
189
190     else if (category == "G-force")
191     {
192         topList.append(xmlreader->getTop10GforceList());
193     }
194     ui->labelTopList->setText(topList);
195 }
196
197 /**
198   *This slot function is called when speed is achieved in measure dialog. Opens result dialog.
199   */
200 void CarMainWindow::openResultView()
201 {
202     //result->saveMeasuresToArray(measure->measures);
203     // Show result dialog.
204     //result->show();
205     QString timeInteger;
206     timeInteger.setNum(this->measures->getTime40kmh());
207     //time = "0 - 40 km/h: ";
208     //time.append(timeInteger);
209     //ui->labelResult40kmh->setText(time);
210     ui->labelMeasureTabResult->show();
211     ui->labelMeasureTabResult->setText(timeInteger);
212     //ui->tabWidget->setCurrentWidget(this->ui->tabMeasureResult);
213 }
214
215
216 /**
217   *This slot function is called when login/logout button is clicked.
218   */
219 void CarMainWindow::on_loginLogoutButton_clicked()
220 {
221     myLogin->show();
222 }
223
224 /**
225   *This slot function is called when registrate button is clicked.
226   */
227 void CarMainWindow::on_registratePushButton_clicked()
228 {
229     myRegistration->show();
230 }
231
232 /**
233   *This slot function is called when ever refresh button clicked. Top-tab view.
234   */
235 void CarMainWindow::on_buttonTopRefresh_clicked()
236 {
237     //setCategoryCompoBox();
238     requestTopList();
239 }
240
241 /**
242   *This slot function is called when ever category combobox current index changed. Top-tab view.
243   *@param QString category
244   */
245 void CarMainWindow::on_comboBoxTopCategory_currentIndexChanged(QString category)
246 {
247     setListViewTopList(category);
248 }
249
250 /**
251   *This slot function is called when ever category combobox activated. Top-tab view.
252   *@param QString category
253   */
254 void CarMainWindow::on_comboBoxTopCategory_activated(QString category)
255 {
256     setListViewTopList(category);
257 }
258
259 /**
260   *This slot function is called when set/change user button is clicked.
261   */
262 void CarMainWindow::on_setUserPushButton_clicked()
263 {
264     myLogin->show();
265
266     ui->userNameLabel->setText( "User: " + myLogin->getUserName());
267     ui->setUserPushButton->setText( "Change User");
268 }
269
270 /**
271   *@brief Sends registration information to the server in xml format.
272   *Reads user name, password and emaol address from resuldialogs internal variables.
273   *@todo Replace msg box with better reaction to server`s responce.
274   *@todo Write error handling.
275   */
276 void CarMainWindow::registrate()
277 {
278     qDebug() << "_registrate" ;
279     qDebug() << this->myRegistration->getUserName() << "+" << this->myRegistration->getPassword() << "+" << this->myRegistration->getEmail();
280
281     QBuffer *regbuffer = new QBuffer();
282     QUrl qurl("http://api.speedfreak-app.com/api/register");
283     QNetworkRequest request(qurl);
284     qDebug() << qurl.toString();
285
286     regbuffer->open(QBuffer::ReadWrite);
287     xmlwriter->writeRegistering(regbuffer,
288                       this->myRegistration->getUserName(),
289                       this->myRegistration->getPassword(),
290                       this->myRegistration->getEmail());
291     //Tmp msgbox - later server responce
292     QMessageBox::about(this,"Registrate",this->myRegistration->getUserName() + this->myRegistration->getPassword() + this->myRegistration->getEmail());
293
294     manager->post(request, ("data=" + regbuffer->data()));
295     qDebug() << "carmainwindow: regbuffer->data(): " << regbuffer->data();
296
297     //ackOfRegistration function gets called when HTTP request is completed
298     connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ackOfRegistration(QNetworkReply*)));
299     //connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
300     regbuffer->close();
301 }
302
303 /**
304   *@brief Sends result(s) to the server in xml format with authentication information in the header.
305   *@todo Write error handling.
306   */
307 void CarMainWindow::sendXml()
308 {
309     qDebug() << "_sendXml";
310
311     QBuffer *xmlbuffer = new QBuffer();
312     QString category_name = "acceleration-0-100";    //replace with real value from category list
313
314     QString credentials = this->myRegistration->getUserName() + ":" + this->myRegistration->getPassword();
315     credentials = "Basic " + credentials.toAscii().toBase64();
316
317     QUrl qurl("http://api.speedfreak-app.com/api/update/" + category_name);
318     qDebug() << qurl.toString();
319     QNetworkRequest request(qurl);
320     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
321
322     xmlbuffer->open(QBuffer::ReadWrite);
323     xmlwriter->writeResult(xmlbuffer);
324     qDebug() << "carmainwindow: xmlbuffer->data(): " << xmlbuffer->data();
325
326     manager->post(request, ("data=" + xmlbuffer->data()));
327     //connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(ackOfResult(QNetworkReply*)));
328     //connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
329
330     //QNetworkReply *currentDownload;
331     //QString data("abcdefg");
332     //currentDownload = manager->post(request,"data=" + QUrl::toPercentEncoding(data));   //testing
333     //currentDownload = manager->post(request, ("data=" + xmlbuffer->data()));
334     //ackOfResult function gets called when HTTP request is completed
335     //connect(currentDownload, SIGNAL(finished()), SLOT(ackOfResult()));
336
337     xmlbuffer->close();
338 }
339
340 /**
341   *@brief Sends request to the server for a top list with authentication information in the header.
342   *@todo Write error handling.
343   *@todo Replace with real value from category list and limitNr
344   */
345 void CarMainWindow::requestTopList()
346 {
347     qDebug() << "_requestTopList" ;
348
349     QString urlBase = "http://api.speedfreak-app.com/api/results/";
350     QString category_name = "acceleration-0-100";    //replace with real value from category list/top window
351     int limitNr = 5;
352     QString limit = QString::number(limitNr);
353
354     QString credentials = this->myRegistration->getUserName() + ":" + this->myRegistration->getPassword();
355     credentials = "Basic " + credentials.toAscii().toBase64();
356
357     QUrl qurl(urlBase + category_name + "/" + limit);
358     qDebug() << qurl.toString();
359     QNetworkRequest request(qurl);
360
361     request.setRawHeader(QByteArray("Authorization"),credentials.toAscii());
362     manager->post(request, ("data=" ));
363     //connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(networkResponse(QNetworkReply*)));
364     //connect(manager,SIGNAL(sslErrors(QNetworkReply*)),this,SLOT(errorFromServer(QNetworkReply*)));
365
366     //QNetworkReply *currentDownload;
367     //currentDownload = manager->post(request, ("data=" ));
368     //ackOfResult function gets called when HTTP request is completed
369     //connect(currentDownload, SIGNAL(error()),SLOT(errorFromServer()));
370 }
371
372 /**
373   *@brief React to servers responce after result has been sent.
374   *@todo Implement function and write error handling.
375   */
376 void CarMainWindow::ackOfResult(QNetworkReply* reply)
377 {
378     qDebug() << "_ackOfResult";
379     qDebug() << reply->readAll();
380     QNetworkReply::NetworkError errorcode;
381     errorcode = reply->error();
382     if(errorcode != 0) {
383         qDebug() << errorcode << reply->errorString();
384     }
385     else {
386         qDebug() << "errorcode=0";
387     }
388 }
389
390 /**
391   *@brief React to servers responce after registration has been sent.
392   *@todo Implement function and write error handling.
393   */
394 void CarMainWindow::ackOfRegistration(QNetworkReply* reply)
395 {
396     qDebug() << "_ackOfRegistration";
397     qDebug() << reply->readAll();
398     QNetworkReply::NetworkError errorcode;
399     errorcode = reply->error();
400     if(errorcode != 0) {
401         qDebug() <<  "errorcode:" << errorcode << reply->errorString();
402     }
403     else {
404         qDebug() << "errorcode=0";
405     }
406 }
407
408 void CarMainWindow::errorFromServer(QNetworkReply* reply)
409 {
410     qDebug() << "_errorFromServer";
411     QNetworkReply::NetworkError errorcode;
412
413     errorcode = reply->error();
414     if(errorcode != 0) {
415         qDebug() << errorcode;
416     }
417     else {
418         qDebug() << errorcode;
419     }
420 }
421
422 /**
423   *This slot function is called when the server has finished guery.
424   */
425 void CarMainWindow::networkResponse(QNetworkReply *reply)
426 {
427     qDebug() << "_networkResponse";
428     xmlreader->xmlRead(reply);
429     qDebug() << reply->readAll();
430     QNetworkReply::NetworkError errorcode;
431     errorcode = reply->error();
432     if(errorcode != 0) {
433         qDebug() << errorcode << reply->errorString();
434     }
435     else {
436         qDebug() << "errorcode=0";
437     }
438 }
439
440 /**
441   *@brief Just for development, for the real button is not shown until
442   *measurin started and there are results.
443   *@todo Implement with real code and yet leave sendXml in the bottom in use.
444   */
445 void CarMainWindow::on_manualStartButton_clicked()
446 {
447     sendXml();
448 }
449
450 /**
451   * This slot function is called when timer gives timeout signal. Checks current speed
452   * and stores times in measure class.
453   */
454 void CarMainWindow::after_timeout()
455 {
456     QString timeString, speedString;
457     //time++;
458     time = accelerometer->getTotalTime();
459     speed = accelerometer->getCurrentSpeed();
460     //speed = speed +10;
461
462     if (floor(speed) == 10)
463     {
464         measures->setTime10kmh(time);
465     }
466
467     else if (floor(speed) == 20)
468     {
469         measures->setTime20kmh(time);
470     }
471
472     else if (floor(speed) == 30)
473     {
474         measures->setTime30kmh(time);
475     }
476
477     else if (floor(speed) == 40)
478     {
479         measures->setTime40kmh(time);
480     }
481
482     else if (floor(speed) == 50)
483     {
484         measures->setTime50kmh(time);
485     }
486
487     else if (floor(speed) == 60)
488     {
489         measures->setTime60kmh(time);
490     }
491
492     else if (floor(speed) == 70)
493     {
494         measures->setTime70kmh(time);
495     }
496
497     else if (floor(speed) == 80)
498     {
499         measures->setTime80kmh(time);
500     }
501
502     else if (floor(speed) == 90)
503     {
504         measures->setTime90kmh(time);
505     }
506
507     else if (floor(speed) == 100)
508     {
509         measures->setTime100kmh(time);
510     }
511
512     else
513     {
514
515     }
516
517     // If speed is over 40 km/h emits speedAchieved() signal and close this dialog.
518     if (speed >= 40.0)
519     {
520         timer->stop();
521         accelerometer->stop();
522         time = 0;
523         speed = 0;
524         //emit this->speedAchieved();
525         this->openResultView();
526         //this->close();
527
528     }
529
530     // Updates speed and time.
531     else
532     {
533         timeString.setNum(time);
534         speedString.setNum(speed);
535         ui->labelMeasureTabTime->setText(timeString);
536         ui->labelMeasureTabSpeed->setText(speedString);
537
538         timer->start();
539     }
540
541 }
542
543 /**
544   * Initializes measures class's member variables.
545   */
546 void CarMainWindow::initializeMeasures()
547 {
548     measures->setTime10kmh(0);
549     measures->setTime20kmh(0);
550     measures->setTime30kmh(0);
551     measures->setTime40kmh(0);
552     measures->setTime50kmh(0);
553     measures->setTime60kmh(0);
554     measures->setTime70kmh(0);
555     measures->setTime80kmh(0);
556     measures->setTime90kmh(0);
557     measures->setTime100kmh(0);
558 }
559
560 /**
561   * This slot function is called when Abort button is clicked.
562   */
563 void CarMainWindow::on_pushButtonMeasureTabAbort_clicked()
564 {
565     measures->setTime10kmh(0);
566     measures->setTime20kmh(0);
567     measures->setTime30kmh(0);
568     measures->setTime40kmh(0);
569     measures->setTime50kmh(0);
570     measures->setTime60kmh(0);
571     measures->setTime70kmh(0);
572     measures->setTime80kmh(0);
573     measures->setTime90kmh(0);
574     measures->setTime100kmh(0);
575     timer->stop();
576     accelerometer->stop();
577     time = 0;
578     speed = 0;
579     ui->tabWidget->setCurrentWidget(this->ui->StartTab);
580     //this->close();
581 }
582
583 void CarMainWindow::on_pushButtonSendResult_clicked()
584 {
585     sendXml();
586
587 }
588
589 void CarMainWindow::updateUserName()
590 {
591     QString newUserName;
592
593     newUserName = myLogin->getUserName();
594     ui->userNameLabel->setText( "User: " + newUserName);
595
596     if (newUserName.length())
597     {
598        ui->setUserPushButton->setText( "Change User");
599        this->setWindowTitle("Speed freak - " + newUserName);
600     }
601     else
602     {
603         ui->setUserPushButton->setText( "Set User");
604         this->setWindowTitle("Speed freak");
605     }
606 }