Added code to connect to the XBMC server.
[simple-xmbc-rem] / src / mainwindow.cpp
index 7c7115a..ef57d3b 100644 (file)
 #include "mainwindow.h"
 #include "ui_mainwindow.h"
 
+#include "constants.h"
 #include "setupdialog.h"
 #include "json.h"
 
 #include <QtCore/QCoreApplication>
+#include <QtCore/QSettings>
+#include <QtCore/QTimer>
+#include <QtCore/QTextStream>
 
 #if defined(Q_OS_SYMBIAN) && defined(ORIENTATIONLOCK)
 #include <eikenv.h>
@@ -26,6 +30,13 @@ MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent), ui(new Ui::MainWindow)
 {
     ui->setupUi(this);
+
+    connect(&serverSocket, SIGNAL(connected()), this, SLOT(serverConnected()));
+    connect(&serverSocket, SIGNAL(disconnected()), this, SLOT(serverDisconnected()));
+    connect(&serverSocket, SIGNAL(readyRead()), this, SLOT(serverDataAvailable()));
+    connect(&serverSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(serverError()));
+
+    connectToServer();
 }
 
 MainWindow::~MainWindow()
@@ -90,3 +101,65 @@ void MainWindow::on_actionSetup_triggered()
         dialog.save();
     }
 }
+
+void MainWindow::connectToServer()
+{
+    // TODO: we asume the socket is not already connected
+    // TODO: we should add code to do nothing if the connection is ok, or close and open a new one if the server or port changed
+    QSettings settings;
+
+    serverSocket.connectToHost(settings.value(SETUP_XBMC_SERVER, SETUP_XBMC_SERVER_DEFAULT).toString(),
+                               settings.value(SETUP_XBMC_PORT, SETUP_XBMC_PORT_DEFAULT).toInt());
+}
+
+void MainWindow::disconnectFromServer()
+{
+    serverSocket.disconnectFromHost();
+}
+
+void MainWindow::serverConnected()
+{
+    ui->testButton->setEnabled(true);
+    ui->actionConnect->setChecked(true);
+}
+
+void MainWindow::serverDisconnected()
+{
+    ui->testButton->setEnabled(false);
+    ui->actionConnect->setChecked(false);
+}
+
+void MainWindow::serverDataAvailable()
+{
+    QTextStream stream(&serverSocket);
+    ui->textEdit->setText(stream.readAll());
+}
+
+void MainWindow::serverError()
+{
+    ui->textEdit->setText(serverSocket.errorString());
+    ui->actionConnect->setChecked(serverSocket.state() == QTcpSocket::ConnectedState);
+    // clean the error window after 2 secs
+    QTimer::singleShot(2000, this, SLOT(cleanError()));
+}
+
+void MainWindow::cleanError()
+{
+    ui->textEdit->clear();
+}
+
+void MainWindow::on_testButton_clicked()
+{
+    QTextStream stream(&serverSocket);
+    stream << JsonEngine().playerGetActivePlayers();
+}
+
+void MainWindow::on_actionConnect_triggered(bool checked)
+{
+    qDebug("menu state: %d", checked);
+    if (checked) {
+        connectToServer();
+    } else {
+        disconnectFromServer();
+    }
+}