8a66c9557062cdadeb6e78245d4188bfb440da96
[ptas] / zouba / qt / httpclient.cpp
1 #include "httpclient.h"
2
3 #include "ui_zouba.h"
4
5 #include <QNetworkAccessManager>
6 #include <QNetworkReply>
7 #include <QUrl>
8 #include <QObject>
9 #include <QDebug>
10 #include <QStringList>
11 #include <QString>
12 #include <QXmlStreamReader>
13
14 namespace {
15   QUrl ytv( "http://api.reittiopas.fi/public-ytv/fi/api/" );
16   QString username( "zouba" );
17   QString password( "caf9r3ee" );
18
19   QString homeKey( "taivaanvuohentie%207%2Chelsinki" );
20   QString workKey( "it%E4merenkatu%2011%2Chelsinki" );
21
22   QString workX( "2551042" );
23   QString workY( "6672829" );
24   QString homeX( "2549183" );
25   QString homeY( "6672570" );
26 }
27   
28 HttpClient::HttpClient( Ui::MainWindow *ui ) :
29   manager( new QNetworkAccessManager(this) ),
30   ui( ui )
31 {
32   connect( manager, SIGNAL( finished(QNetworkReply*) ), this, SLOT( replyFinished(QNetworkReply*) ) );
33 }
34
35 HttpClient::~HttpClient()
36 {
37   delete manager;
38   manager = 0;
39 }
40
41 void HttpClient::get()
42 {
43   QUrl fullUrl( ytv );
44
45   QStringList a;
46   a << workX << workY;
47   QStringList b;
48   b << homeX << homeY;
49
50   fullUrl.addQueryItem( "a", a.join(",") );
51   fullUrl.addQueryItem( "b", b.join(",") );
52   fullUrl.addQueryItem( "user", username );
53   fullUrl.addQueryItem( "pass", password );
54
55   manager->get( QNetworkRequest( fullUrl ) );
56 }
57
58 void HttpClient::replyFinished( QNetworkReply * reply )
59 {
60   QXmlStreamReader xml( reply->readAll() );
61
62   bool inLine = false;
63   bool inStop = false;
64   while ( !xml.atEnd() ) {
65     xml.readNext();
66     //qDebug() << xml.name();
67     if ( xml.isStartElement() && xml.name() == "LINE" ) {
68       QString lineCode( xml.attributes().value("code").toString() );
69
70       qDebug() << "line code" << lineCode;
71       ui->BusNoDisplay->setText( lineCode );
72
73       inLine = true;
74     } else
75     if ( inLine && xml.name() == "STOP" ) {
76       inStop = true;
77     } else
78     if ( inLine && inStop && xml.name() == "ARRIVAL" ) {
79       QString arrivalTime( xml.attributes().value("time").toString() );
80
81       qDebug() << "arrival time" << arrivalTime;
82       ui->TimeDisplay->setText( arrivalTime );
83
84       inLine = false;
85     } else
86     if ( xml.isEndElement() && xml.name() == "STOP" ) {
87       inStop = false;
88     } else
89     if ( xml.isEndElement() && xml.name() == "LINE" ) {
90       inLine = false;
91     }
92   }
93
94   if ( xml.hasError() ) {
95     qDebug() << "xml error";
96   }
97 }