cppscripts/statustemp.cpp

104 lines
2.6 KiB
C++

// Print hardware temperature for i3 status bar.
/* i3blocks config:
* [temperature]
* label=🌡
* interval=persist
* command=statustemp --file=/sys/devices/platform/…
* markup=pango
*/
#include "helpers.hpp"
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <fmt/core.h>
#include <chrono>
#include <exception>
#include <fstream>
#include <iostream>
#include <locale>
#include <string>
#include <thread>
std::string get_file_path(int argc, char *argv[])
{
namespace po = boost::program_options;
po::options_description options("Options");
// clang-format off
options.add_options()
("help,h", "Display this help and exit.")
("file", po::value<std::string>()->required()->value_name("PATH"),
"The file path the temperature is stored in.");
// clang-format on
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options).run(), vm);
std::ifstream configfile(helpers::get_config_file_path("statustemp.cfg"));
po::store(po::parse_config_file(configfile, options, true), vm);
configfile.close();
if (vm.count("help") != 0)
{
std::cout << options;
std::exit(0); // NOLINT(concurrency-mt-unsafe)
}
po::notify(vm);
return vm["file"].as<std::string>();
}
std::string get_style(const float temperature)
{
if (temperature > 85.0)
{
return R"(background="red" color="black" weight="heavy")";
}
if (temperature > 75.0)
{
return R"(color="#ff4400")";
}
if (temperature > 65.0)
{
return R"(color="#ffff00")";
}
return {};
}
int main(int argc, char *argv[])
{
using fmt::format;
using namespace std::chrono_literals;
std::locale::global(std::locale(""));
try
{
const std::string filepath{get_file_path(argc, argv)};
std::ifstream file;
std::string line;
float temperature{-273.15};
while (true)
{
file.open(filepath);
std::getline(file, line);
file.close();
temperature = static_cast<float>(std::stof(line) / 1000.0);
std::cout << format("<span {:s}>{:.1Lf}°C</span>",
get_style(temperature), temperature)
<< std::endl;
std::this_thread::sleep_for(5s);
}
}
catch (std::exception &e)
{
std::cout << R"(<span color="red">)" << e.what() << "</span>"
<< std::endl;
return 33;
}
}