Add statustemp.

This commit is contained in:
tastytea 2021-08-24 21:31:13 +02:00
parent 4e6e463159
commit 6d3d5b94ad
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 119 additions and 0 deletions

View File

@ -30,3 +30,6 @@ target_link_libraries(statusweather
add_executable(statusip "statusip.cpp" "helpers.cpp")
target_link_libraries(statusip
PRIVATE fmt::fmt Boost::program_options restclient-cpp)
add_executable(statustemp "statustemp.cpp" "helpers.cpp")
target_link_libraries(statustemp PRIVATE fmt::fmt Boost::program_options)

116
statustemp.cpp Normal file
View File

@ -0,0 +1,116 @@
// 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);
const auto path{[]()
{
auto path{helpers::get_env("XDG_CONFIG_HOME")};
if (path.empty())
{
path = helpers::get_env("HOME");
if (!path.empty())
{
path += "/.config";
}
}
return path += "/statustemp.cfg";
}()};
std::ifstream configfile(path);
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;
}
}