#include "SystemInfo.h" #include #include #include SystemInfo::SystemInfo(QObject *parent) : QObject(parent) { m_capacityPath = findBatteryCapacityPath(); updateBattery(); connect(&m_batteryTimer, &QTimer::timeout, this, &SystemInfo::updateBattery); // Battery percentage doesn't need millisecond precision. m_batteryTimer.start(10000); } int SystemInfo::batteryPercent() const { return m_batteryPercent; } QString SystemInfo::findBatteryCapacityPath() const { QDir powerSupply("/sys/class/power_supply"); const QStringList devices = powerSupply.entryList(QDir::Dirs | QDir::NoDotAndDotDot); for (const QString &device : devices) { const QString base = powerSupply.absoluteFilePath(device); QFile typeFile(base + "/type"); if (!typeFile.open(QIODevice::ReadOnly | QIODevice::Text)) continue; const QString type = QString::fromUtf8(typeFile.readAll()).trimmed(); if (type != "Battery") continue; const QString capacityPath = base + "/capacity"; if (QFile::exists(capacityPath)) return capacityPath; } return {}; } void SystemInfo::updateBattery() { if (m_capacityPath.isEmpty()) m_capacityPath = findBatteryCapacityPath(); if (m_capacityPath.isEmpty()) return; QFile capacityFile(m_capacityPath); if (!capacityFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; bool ok = false; int percent = QString::fromUtf8(capacityFile.readAll()) .trimmed() .toInt(&ok); if (!ok) return; percent = qBound(0, percent, 100); if (percent == m_batteryPercent) return; m_batteryPercent = percent; emit batteryPercentChanged(); }