-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbatteryHandler.cpp
More file actions
102 lines (88 loc) · 2.88 KB
/
Copy pathbatteryHandler.cpp
File metadata and controls
102 lines (88 loc) · 2.88 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include "batteryHandler.h"
#include <QDir>
#include <QFile>
#include <QTextStream>
BatteryHandler::BatteryHandler(QObject *parent)
: QObject(parent), m_level("--%")
{
// battery folder
QDir powerSupplyDir("/sys/class/power_supply");
if (powerSupplyDir.exists()) {
QStringList entries = powerSupplyDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const QString &entry : entries) {
if (entry.contains("BAT") || entry.contains("battery", Qt::CaseInsensitive)) {
m_batteryPath = powerSupplyDir.absoluteFilePath(entry) + "/capacity";
m_statusPath = powerSupplyDir.absoluteFilePath(entry) + "/status";
break;
}
}
}
if (m_batteryPath.isEmpty()) {
qDebug() << "[BatteryReader] No battery found. Falling back to VM Test mode.";
} else {
qDebug() << "[BatteryReader] Battery capacity file detected at:" << m_batteryPath;
qDebug() << "[BatteryReader] Battery status file detected at:" << m_statusPath;
}
// update every 4min
connect(&m_timer, &QTimer::timeout, this, &BatteryHandler::updateBattery);
m_timer.start(240000);
updateBattery();
}
QString BatteryHandler::level() const
{
return m_level;
}
bool BatteryHandler::isCharging() const
{
return m_isCharging;
}
void BatteryHandler::updateBattery()
{
if (m_batteryPath.isEmpty()) {
if (m_level != "VM Test") {
m_level = "VM Test";
emit levelChanged();
}
if (!m_isCharging) {
m_isCharging = false;
emit isChargingChanged();
}
return;
}
QFile file(m_batteryPath);
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
QString rawValue = in.readLine().trimmed();
bool ok;
int intLevel = rawValue.toInt(&ok);
if (ok) {
if (intLevel > 100) {
intLevel = 100;
}
QString currentLevel = QString::number(intLevel) + "%";
if (m_level != currentLevel) {
m_level = currentLevel;
emit levelChanged();
}
}
file.close();
} else {
if (m_level != "Error") {
m_level = "Error";
emit levelChanged();
}
}
if (!m_statusPath.isEmpty()) {
QFile statusFile(m_statusPath);
if (statusFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&statusFile);
QString status = in.readLine().trimmed();
bool currentlyCharging = (status == "Charging" || status == "Full");
if (m_isCharging != currentlyCharging) {
m_isCharging = currentlyCharging;
emit isChargingChanged();
}
statusFile.close();
}
}
}