/
battery.cpp
60 lines (53 loc) · 1.56 KB
/
battery.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "util/battery/battery.h"
#include <chrono>
#include "moc_battery.cpp"
// Do not include platform-specific battery implementation unless we are built
// with battery support (__BATTERY__).
#ifdef __BATTERY__
#if defined(Q_OS_WIN)
#include "util/battery/batterywindows.h"
#elif defined(Q_OS_MAC)
#include "util/battery/batterymac.h"
#else
#include "util/battery/batterylinux.h"
#endif
#endif
#include "util/math.h"
using namespace std::chrono_literals;
// interval of the timer which calls update()
static constexpr std::chrono::milliseconds kBatteryUpdateInterval = 5000ms;
Battery::Battery(QObject* parent)
: QObject(parent),
m_chargingState(UNKNOWN),
m_dPercentage(0.0),
m_iMinutesLeft(0),
m_timer(this) {
connect(&m_timer, &QTimer::timeout, this, &Battery::update);
m_timer.start(kBatteryUpdateInterval);
}
Battery* Battery::getBattery(QObject* parent) {
#ifdef __BATTERY__
#if defined(Q_OS_WIN)
return new BatteryWindows(parent);
#elif defined(Q_OS_MAC)
return new BatteryMac(parent);
#else
return new BatteryLinux(parent);
#endif
#else
Q_UNUSED(parent);
return nullptr;
#endif
}
void Battery::update() {
constexpr double kPercentageEpsilon = 0.1;
double lastPercentage = m_dPercentage;
int lastMinutesLeft = m_iMinutesLeft;
ChargingState lastChargingState = m_chargingState;
read();
if (fabs(lastPercentage - m_dPercentage) > kPercentageEpsilon ||
lastChargingState != m_chargingState ||
lastMinutesLeft != m_iMinutesLeft) {
emit stateChanged();
}
}