Paste P527

(An Untitled Masterwork)
ActivePublic

Authored by davidedmundson on Jan 24 2020, 11:40 AM.
#include "cpu.h"
#include <KLocalizedString>
#include <QTextStream>
#include <QDebug>
template<typename T>
class Q_DECL_EXPORT SensorProperty2 : public SensorProperty
{
public:
SensorProperty2(const QString &id, SensorObject *parent)
: SensorProperty(id, parent)
{
}
QVariant value() const override {
return QVariant::fromValue(m_data);
}
T data() const {
return m_data;
}
void setData(T newData) {
m_data = newData;
Q_EMIT valueChanged();
}
friend QTextStream &operator>>(QTextStream &textStream, SensorProperty2 &st)
{
QTextStream &stream = textStream >> st.m_data;
Q_EMIT st.valueChanged();
return stream;
}
private:
T m_data;
};
class CPU: public SensorObject //Future Dave could make this an abstract class for the BSD backend
{
public:
CPU(const QString &id, SensorObject *parent);
~CPU() = default;
SensorProperty2<int> user;
SensorProperty2<int> nice;
SensorProperty2<int> sys;
SensorProperty2<int> idle;
SensorProperty2<int> wait;
SensorProperty2<int> totalLoad;
};
class CPUCore : public CPU
{
public:
CPUCore(const QString &id, SensorObject *parent);
~CPUCore() = default;
SensorProperty2<int> clock;
};
CPUManager::CPUManager(SensorObject *parent)
: SensorObject(QStringLiteral("cpu"), parent)
{
m_systemCpu = new CPU(QStringLiteral("system"), this);
for (int i = 0; i < 8; i++) { //FIXME obviously
m_cores << new CPUCore(QStringLiteral("cpu%1").arg(i), this);
}
m_procStat.setFileName("/proc/stat");
}
void CPUManager::update()
{
// if (!isSubscribed()) {
// return;
// }
m_procStat.open(QIODevice::ReadOnly);
QTextStream stream(&m_procStat);
auto processLine = [&stream](CPU* cpu) {
QByteArray tmp;
stream >> tmp;
stream >> cpu->user >> cpu->nice >> cpu->sys >> cpu->totalLoad >> cpu->idle >> cpu->wait;
stream.readLineInto(nullptr); // skip the rest of this line
// update any aggregates
cpu->totalLoad.setData(cpu->user.data() + cpu->sys.data() + cpu->nice.data() + cpu->wait.data());
};
processLine(m_systemCpu);
for (auto it : qAsConst(m_cores)) {
processLine(it);
}
m_procStat.close();
}
CPU::CPU(const QString &id, SensorObject *parent)
: SensorObject(id, parent)
, user("user", this)
, nice("nice", this)
, sys("sys", this)
, idle("idle", this)
, wait("wait", this)
, totalLoad("TotalLoad", this)
{
user.setName(i18n("User Load"));
//etc.
}
CPUCore::CPUCore(const QString &id, SensorObject *parent)
: CPU(id, parent)
, clock("clock", this)
{
}
davidedmundson created this object in space S1 KDE Community.