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