2018-08-08 23:54:33 +00:00
|
|
|
#include "modules/cpu.hpp"
|
|
|
|
|
2018-12-18 16:30:54 +00:00
|
|
|
waybar::modules::Cpu::Cpu(const std::string& id, const Json::Value& config)
|
2019-05-22 10:06:24 +00:00
|
|
|
: ALabel(config, "cpu", id, "{usage}%", 10) {
|
2018-11-23 10:57:37 +00:00
|
|
|
thread_ = [this] {
|
2018-08-20 12:50:45 +00:00
|
|
|
dp.emit();
|
2018-11-23 10:57:37 +00:00
|
|
|
thread_.sleep_for(interval_);
|
2018-08-08 23:54:33 +00:00
|
|
|
};
|
2018-08-18 09:43:48 +00:00
|
|
|
}
|
2018-08-08 23:54:33 +00:00
|
|
|
|
2019-04-18 15:52:00 +00:00
|
|
|
auto waybar::modules::Cpu::update() -> void {
|
2019-04-26 19:49:16 +00:00
|
|
|
// TODO: as creating dynamic fmt::arg arrays is buggy we have to calc both
|
|
|
|
auto cpu_load = getCpuLoad();
|
|
|
|
auto [cpu_usage, tooltip] = getCpuUsage();
|
|
|
|
if (tooltipEnabled()) {
|
|
|
|
label_.set_tooltip_text(tooltip);
|
2019-02-22 10:35:26 +00:00
|
|
|
}
|
2019-04-26 19:49:16 +00:00
|
|
|
label_.set_markup(fmt::format(format_, fmt::arg("load", cpu_load), fmt::arg("usage", cpu_usage)));
|
2019-05-03 02:19:47 +00:00
|
|
|
getState(cpu_usage);
|
2020-04-12 16:30:21 +00:00
|
|
|
// Call parent update
|
|
|
|
ALabel::update();
|
2018-11-15 13:44:43 +00:00
|
|
|
}
|
|
|
|
|
2019-04-18 15:52:00 +00:00
|
|
|
uint16_t waybar::modules::Cpu::getCpuLoad() {
|
2019-08-09 09:07:58 +00:00
|
|
|
double load[1];
|
|
|
|
if (getloadavg(load, 1) != -1) {
|
|
|
|
return load[0] * 100 / sysconf(_SC_NPROCESSORS_ONLN);
|
2018-11-15 13:44:43 +00:00
|
|
|
}
|
|
|
|
throw std::runtime_error("Can't get Cpu load");
|
|
|
|
}
|
|
|
|
|
2019-04-18 15:52:00 +00:00
|
|
|
std::tuple<uint16_t, std::string> waybar::modules::Cpu::getCpuUsage() {
|
2018-11-15 13:44:43 +00:00
|
|
|
if (prev_times_.empty()) {
|
|
|
|
prev_times_ = parseCpuinfo();
|
2018-12-26 10:13:36 +00:00
|
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
2018-08-09 10:05:48 +00:00
|
|
|
}
|
2018-11-15 13:44:43 +00:00
|
|
|
std::vector<std::tuple<size_t, size_t>> curr_times = parseCpuinfo();
|
2019-04-18 15:52:00 +00:00
|
|
|
std::string tooltip;
|
|
|
|
uint16_t usage = 0;
|
2018-11-15 13:44:43 +00:00
|
|
|
for (size_t i = 0; i < curr_times.size(); ++i) {
|
|
|
|
auto [curr_idle, curr_total] = curr_times[i];
|
|
|
|
auto [prev_idle, prev_total] = prev_times_[i];
|
|
|
|
const float delta_idle = curr_idle - prev_idle;
|
|
|
|
const float delta_total = curr_total - prev_total;
|
2019-04-18 15:52:00 +00:00
|
|
|
uint16_t tmp = 100 * (1 - delta_idle / delta_total);
|
2018-11-11 02:11:32 +00:00
|
|
|
if (i == 0) {
|
2018-11-15 13:44:43 +00:00
|
|
|
usage = tmp;
|
|
|
|
tooltip = fmt::format("Total: {}%", tmp);
|
2018-11-11 02:11:32 +00:00
|
|
|
} else {
|
2018-11-15 13:44:43 +00:00
|
|
|
tooltip = tooltip + fmt::format("\nCore{}: {}%", i - 1, tmp);
|
|
|
|
}
|
2018-11-11 02:11:32 +00:00
|
|
|
}
|
2018-11-15 13:44:43 +00:00
|
|
|
prev_times_ = curr_times;
|
|
|
|
return {usage, tooltip};
|
2018-11-11 02:11:32 +00:00
|
|
|
}
|