Lomiri
BatteryMonitor.cpp
1 #include "BatteryMonitor.h"
2 
3 BatteryMonitor::BatteryMonitor()
4 {
5  QDBusConnection::systemBus().connect("org.freedesktop.UPower", "/org/freedesktop/UPower/devices/DisplayDevice", "org.freedesktop.DBus.Properties", "PropertiesChanged", this, SLOT(propertiesChanged(QString, QVariantMap, QStringList)));
6  m_iface = new QDBusInterface("org.freedesktop.UPower", "/org/freedesktop/UPower/devices/DisplayDevice", "org.freedesktop.DBus.Properties", QDBusConnection::systemBus());
7 }
8 
9 bool BatteryMonitor::hasBattery()
10 {
11  QDBusReply<QDBusVariant> reply;
12  uint state;
13 
14  reply = m_iface->call(GET, UPOWER_PROPERTIES, "Type");
15  state = reply.value().variant().toUInt();
16 
17  if (state == ON_BATTERY) {
18  reply = m_iface->call(GET, UPOWER_PROPERTIES, "PowerSupply");
19  if (reply.value().variant().toBool())
20  return true;
21  else
22  return false;
23  } else
24  return false;
25 }
26 
27 uint BatteryMonitor::state()
28 {
29  if (!hasBattery())
30  return UNKNOWN;
31 
32  QDBusReply<QDBusVariant> reply = m_iface->call(GET, UPOWER_PROPERTIES, "State");
33  return reply.value().variant().toUInt();
34 }
35 
36 bool BatteryMonitor::charging()
37 {
38  if (state() == CHARGING)
39  return true;
40  else
41  return false;
42 }
43 
44 qint64 BatteryMonitor::timeToFull()
45 {
46  if (!hasBattery())
47  return -1;
48 
49  QDBusReply<QDBusVariant> reply = m_iface->call(GET, UPOWER_PROPERTIES, "TimeToFull");
50  if (reply.isValid() && charging()) {
51  uint value = reply.value().variant().toUInt();
52  if (value == 0)
53  return -2;
54 
55  return value;
56  }
57 }
58 
59 void BatteryMonitor::propertiesChanged(QString string, QVariantMap map, QStringList list)
60 {
61  if (map.contains("State"))
62  Q_EMIT chargingChanged();
63  else if (map.contains("TimeToFull") && map.contains("Percentage") && charging())
64  Q_EMIT timeToFullChanged();
65 }