Remove debug printfs.
[yandex-traffic] / connection.cpp
index 18a2ee0..07882b0 100644 (file)
@@ -1,4 +1,8 @@
+#include <QtDBus>
+
 #include "connection.hpp"
+#include "icd2_light.h"
+
 
 static ConnectionChecker *_instance = NULL;
 
@@ -15,13 +19,83 @@ ConnectionChecker *ConnectionChecker::instance ()
 
 
 ConnectionChecker::ConnectionChecker ()
+    : _bus (QDBusConnection::systemBus ())
+{
+    _connected = true;
+
+    _itf = new QDBusInterface (ICD_DBUS_API_INTERFACE, ICD_DBUS_API_PATH, ICD_DBUS_API_INTERFACE, _bus);
+    _bus.connect (ICD_DBUS_API_INTERFACE, ICD_DBUS_API_PATH, ICD_DBUS_API_INTERFACE, ICD_DBUS_API_STATE_SIG,
+                  this, SLOT (stateSignal (const QDBusMessage&)));
+    _conn_counter = 0;
+
+    requestState ();
+}
+
+
+void ConnectionChecker::requestState ()
+{
+    QDBusMessage reply = _itf->call (ICD_DBUS_API_STATE_REQ);
+
+    // If there is no connection, we get no reply at all
+    if (!reply.arguments ().value (0).toUInt ())
+        updateState (false);
+}
+
+
+void ConnectionChecker::stateSignal (const QDBusMessage& msg)
+{
+    if (msg.arguments ().count () != 8)
+        return;
+
+    unsigned int state = msg.arguments ().value (7).value<unsigned int>();
+    QString net = msg.arguments ().value (3).toString ();
+
+    if (state == ICD_STATE_CONNECTED)
+        _conn_counter++;
+    if (state == ICD_STATE_DISCONNECTED)
+        _conn_counter--;
+
+    if (state == ICD_STATE_CONNECTED || !_conn_counter)
+        updateState (state == ICD_STATE_CONNECTED, net);
+}
+
+
+void ConnectionChecker::updateState (bool new_state, const QString& net_type)
 {
-    // start timer which will check connection
-    startTimer (15*1000);
+    network_type_t new_net = Net_None;
+
+    if (new_state != _connected) {
+        _connected = new_state;
+        emit connected (_connected);
+    }
+
+    if (_connected) {
+        if (net_type.startsWith ("WLAN"))
+            new_net = Net_WLAN;
+        else if (net_type.startsWith ("GPRS") || net_type.startsWith ("DUN_GSM"))
+            new_net = Net_GSM;
+    }
+
+    if (new_net != _net_type) {
+        _net_type = new_net;
+        type_changed (_net_type);
+    }
 }
 
 
-void ConnectionChecker::timerEvent (QTimerEvent *)
+bool ConnectionChecker::checkConnection (bool allow_gsm, bool allow_wifi)
 {
-    // check for connection
+    if (!_connected)
+        return false;
+
+    switch (_net_type) {
+        case Net_None:
+            return true;
+        case Net_WLAN:
+            return allow_wifi;
+        case Net_GSM:
+            return allow_gsm;
+        default:
+            return true;
+    }
 }