From 7e7d8d2aa1df1f0c3bd0d0686f523e2724a63141 Mon Sep 17 00:00:00 2001 From: Drath Date: Fri, 3 Oct 2025 16:57:38 +0200 Subject: [PATCH] logging lib --- include/LCDDisplay.hpp | 7 +++++++ include/cpu.hpp | 2 +- include/gpu.hpp | 6 +++--- include/hass.hpp | 2 +- include/log.hpp | 39 +++++++++++++++++++++++++++++++++++++++ include/utils.hpp | 2 +- main.cpp | 13 +++++-------- src/LCDDisplay.cpp | 25 ++++++++----------------- src/cpu.cpp | 6 +++--- src/gpu.cpp | 6 +++--- src/hass.cpp | 18 ++++++++---------- src/utils.cpp | 2 +- 12 files changed, 80 insertions(+), 48 deletions(-) create mode 100644 include/log.hpp diff --git a/include/LCDDisplay.hpp b/include/LCDDisplay.hpp index cc3850e..457e751 100644 --- a/include/LCDDisplay.hpp +++ b/include/LCDDisplay.hpp @@ -4,8 +4,15 @@ #define LCD_LINES 4 #define LCD_COLS 40 +#include +#include +#include + #include #include +#include +#include +#include #include #include diff --git a/include/cpu.hpp b/include/cpu.hpp index 5b49adc..3294896 100644 --- a/include/cpu.hpp +++ b/include/cpu.hpp @@ -3,7 +3,7 @@ #include #include -#include +#include #include #include diff --git a/include/gpu.hpp b/include/gpu.hpp index e2f5f51..de2d9b4 100644 --- a/include/gpu.hpp +++ b/include/gpu.hpp @@ -4,12 +4,12 @@ #include #include #include -#include +#include #include #include -#define REL_METRICS_PATH "/../../gpu_metrics" // gpu_metrics path relative to hwmon path -#define MAX_METRICS_LENGTH 512 // length of the metrics buffer +#define REL_METRICS_PATH "/../../gpu_metrics" // gpu_metrics path relative to hwmon path +#define MAX_METRICS_LENGTH 512 // length of the metrics buffer /* clean abstraction for gpu_metrics or metrics in filesystem in sane units */ diff --git a/include/hass.hpp b/include/hass.hpp index bce36ac..2132e38 100644 --- a/include/hass.hpp +++ b/include/hass.hpp @@ -5,7 +5,7 @@ #include #include -#include +#include #include #define HASS_TOKEN "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI0MzUxMTZiY2VjNTg0MTI3OGI4YmU0NTY4ZGQ5MzIyYiIsImlhdCI6MTc1NzQzMDI0MCwiZXhwIjoyMDcyNzkwMjQwfQ.6wKTlxEA0FLWfv-qW35vewUSvTxdVrZWqFwHT5Khu6E" diff --git a/include/log.hpp b/include/log.hpp new file mode 100644 index 0000000..381ea59 --- /dev/null +++ b/include/log.hpp @@ -0,0 +1,39 @@ +#ifndef LOG_HPP +#define LOG_HPP + +// #define PATTERN "[{}{}{}] " + +#include +#include +#include + +enum class LOG { INF, WRN, ERR, DBG }; +inline std::mutex mtx; + +template +inline void log(LOG level, std::string_view tag, std::format_string str, Args&&... args) { + constexpr std::string_view reset = "\033[0m"; + constexpr std::string_view green = "\033[32m"; + constexpr std::string_view yellow = "\033[33m"; + constexpr std::string_view red = "\033[31m"; + constexpr std::string_view pattern = "[{}{}{}] "; + + std::scoped_lock lock(mtx); + switch (level) { + case LOG::INF: + std::print(pattern, green, tag, reset); + break; + case LOG::WRN: + std::print(pattern, yellow, tag, reset); + break; + case LOG::ERR: + std::print(pattern, red, tag, reset); + break; + default: + std::print(pattern, "", tag, ""); + } + + std::println(str, std::forward(args)...); +} + +#endif \ No newline at end of file diff --git a/include/utils.hpp b/include/utils.hpp index a25d759..f9f2d9f 100644 --- a/include/utils.hpp +++ b/include/utils.hpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include diff --git a/main.cpp b/main.cpp index c440961..d056e4a 100644 --- a/main.cpp +++ b/main.cpp @@ -1,11 +1,8 @@ -// #include #include #include -// #include // this is incorrect, we need to either use stdint.h, use std::uint8_t or put using std::uint_8 #include #include -#include #include #include #include @@ -16,6 +13,7 @@ #include #include #include +#include #include #include @@ -42,13 +40,12 @@ struct Sensors { }; void sighandler(int s) { // can i remove int s - std::println("[Signal] got SIGINT/SIGTERM, exiting..."); + log(LOG::WRN, "Signal", "got SIGINT/SIGTERM, exiting..."); sem::main.release(); sem::display.release(); } void hassThread(std::stop_token st, Sensors* s) { - // std::println("[Thread] Starting hass_thread, pid {}", gettid()); HomeAssistant pc_power("home.drath.win", "sensor.gniazdko_komputer_moc"); pc_power.connect(); @@ -64,7 +61,7 @@ void hassThread(std::stop_token st, Sensors* s) { } void sensorsThread(std::stop_token st, Sensors* s) { - std::println("[Thread] Starting sensors_thread, pid {}, poll interval {} ms", gettid(), LCD_INTERVAL_MS); + log(LOG::INF, "Thread", "Starting sensors_thread, pid {}, poll interval {} ms", gettid(), LCD_INTERVAL_MS); cpu::detectHwmon(&s->cpu, "0000:00:18.3"); gpu::detectHwmon(&s->gpu, "0000:0a:00.0"); @@ -89,7 +86,7 @@ void sensorsThread(std::stop_token st, Sensors* s) { } void displayThread(std::stop_token st, Sensors* s) { - std::println("[Thread] Starting display_thread, pid {}", gettid()); + log(LOG::INF, "Thread", "Starting display_thread, pid {}", gettid()); LCDDisplay lcd(LCD_PORT); lcd.setContrast(LCD_CONTRAST); @@ -144,7 +141,7 @@ int main(int argc, char* argv[]) { std::signal(SIGTERM, sighandler); Sensors* pSensors = new Sensors; - std::println("[main] size of sensor struct is {} bytes", sizeof(Sensors)); + log(LOG::DBG, "main", "size of sensor struct is {} bytes", sizeof(Sensors)); std::function funcs[] = {displayThread, hassThread, sensorsThread}; // array of functions diff --git a/src/LCDDisplay.cpp b/src/LCDDisplay.cpp index fdf6b9a..a3c732f 100644 --- a/src/LCDDisplay.cpp +++ b/src/LCDDisplay.cpp @@ -1,22 +1,13 @@ #include "LCDDisplay.hpp" -#include -#include -#include - -#include -#include -#include -#include - /* lcd size hardcoded to 4x40 idgaf */ LCDDisplay::LCDDisplay(std::string dev, uint32_t baud) { - std::println("[LCDDisplay] Opening LCD at \"{}\"", dev); + log(LOG::INF, "LCDDisplay", "Opening LCD at \"{}\"", dev); struct termios term; int lcd = open(dev.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); if (lcd < 0) { - std::println("[LCDDisplay] Error opening serial port \"{}\"", dev); // err + log(LOG::ERR, "LCDDisplay", "Error opening serial port \"{}\"", dev); // err exit(lcd); } @@ -42,7 +33,7 @@ LCDDisplay::LCDDisplay(std::string dev, uint32_t baud) { LCDDisplay::~LCDDisplay() { close(_lcd); - std::println("[LCDDisplay] LCD port closed"); + log(LOG::INF, "LCDDisplay", "LCD port closed"); } void LCDDisplay::clear() { @@ -51,21 +42,21 @@ void LCDDisplay::clear() { } void LCDDisplay::setContrast(uint8_t contrast) { - std::println("[LCDDisplay::setContrast] Set contrast to {}", contrast); + log(LOG::INF, "LCDDisplay::setContrast", "Set contrast to {}", contrast); uint8_t cmdbuf[] = {254, 80, contrast}; write(_lcd, &cmdbuf, 3); } void LCDDisplay::setBacklight(bool enabled) { - std::println("[LCDDisplay::setBacklight] Set backlight to {}", enabled); + log(LOG::INF, "LCDDisplay::setBacklight", "Set backlight to {}", enabled); uint8_t cmdbuf[] = {254, (uint8_t)(enabled ? 66 : 70), 255}; write(_lcd, &cmdbuf, enabled ? 3 : 2); } /* still doesnt work? */ void LCDDisplay::setBacklight(uint8_t brightness) { - std::println("[LCDDisplay::setBacklight] Set backlight brightness to {}", brightness); - uint8_t cmdbuf[] = {254, (uint8_t)(brightness ? 66 : 70), 255, brightness}; // 3rd char is timer, 4th is brightness + log(LOG::INF, "LCDDisplay::setBacklight", "Set backlight brightness to {}", brightness); + uint8_t cmdbuf[] = {254, (uint8_t)(brightness ? 66 : 70), 255, brightness}; // 3rd char is timer, 4th is brightness write(_lcd, &cmdbuf, brightness ? 4 : 2); } @@ -95,7 +86,7 @@ void LCDDisplay::writeStr(uint8_t row, uint8_t col, std::string str) { void LCDDisplay::writeLines(std::array lines) { for (auto& line : lines) { if (line.size() > LCD_COLS) { - std::println("[LCDDisplay::writeLines] Line {} too long! ({} chars)", line, line.size()); + log(LOG::WRN, "LCDDisplay::writeLines", "Line {} too long! ({} chars)", line, line.size()); continue; } line.insert(line.end(), LCD_COLS - line.size(), ' '); diff --git a/src/cpu.cpp b/src/cpu.cpp index 17f9e41..176daa6 100644 --- a/src/cpu.cpp +++ b/src/cpu.cpp @@ -9,11 +9,11 @@ void detectHwmon(cpuSensors* target, std::string pci) { for (const auto& entry : std::filesystem::directory_iterator(path)) target->hwmon = getFirstDir(path); } catch (...) { - std::println("[cpu::detectHwmon] NO CPU HWMON KERNEL MODULE DETECTED"); + log(LOG::ERR, "cpu::detectHwmon", "NO CPU HWMON KERNEL MODULE DETECTED"); return; } target->zenpower = readFile((target->hwmon + "/name"), 128) == "zenpower"; - std::println("[cpu::detectHwmon] Detected module \"{}\" in path \"{}\"", target->zenpower ? "zenpower" : "k10temp", target->hwmon); + log(LOG::INF, "cpu::detectHwmon", "Detected module \"{}\" in path \"{}\"", target->zenpower ? "zenpower" : "k10temp", target->hwmon); } void update(cpuSensors* c) { @@ -29,7 +29,7 @@ void update(cpuSensors* c) { c->vcore = (double)(std::stoul(readFile(c->hwmon + "/in1_input", 4)) / 1000.0); // cpu.vsoc = (double)(std::stoul(readFile(hw.path + "/in2_input")) / 1000.0); } else { - c->tctl = std::stoi(readFile(c->hwmon+ "/temp1_input", 2)); + c->tctl = std::stoi(readFile(c->hwmon + "/temp1_input", 2)); c->tccd1 = std::stoi(readFile(c->hwmon + "/temp3_input", 2)); } diff --git a/src/gpu.cpp b/src/gpu.cpp index e9bce41..3a9cae7 100644 --- a/src/gpu.cpp +++ b/src/gpu.cpp @@ -8,11 +8,11 @@ namespace gpu { /* takes pointer to a target gpu::sensors struct and updates its hwmon path and detects gpu_metrics */ void detectHwmon(gpuSensors* target, std::string pci) { target->hwmon = getFirstDir("/sys/bus/pci/devices/" + pci + "/hwmon"); - std::println("[gpu::detectHwmon] Detected path \"{}\"", target->hwmon); + log(LOG::INF, "gpu::detectHwmon", "Detected path \"{}\"", target->hwmon); if (FILE* file = fopen((target->hwmon + REL_METRICS_PATH).c_str(), "r")) { fclose(file); - std::println("[gpu::detectHwmon] found metrics file"); + log(LOG::INF, "gpu::detectHwmon", "found metrics file"); target->hasGpuMetrics = true; } } @@ -80,7 +80,7 @@ void updateFromMetrics(gpuSensors* g) { /* werid hardware i probably dont like, maybe fallback to reading from fs? */ default: { - std::println("[gpu::updateFromMetrics] Unsupported gpu_metrics_v{}_{}", header->format_revision, header->content_revision); + log(LOG::WRN, "gpu::updateFromMetrics", "Unsupported gpu_metrics_v{}_{}", header->format_revision, header->content_revision); break; } } diff --git a/src/hass.cpp b/src/hass.cpp index fb40c79..aaa01a9 100644 --- a/src/hass.cpp +++ b/src/hass.cpp @@ -13,14 +13,13 @@ void HomeAssistant::event_handler(struct lws *wsi, enum lws_callback_reasons rea ArduinoJson::JsonDocument json; switch (reason) { case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: { - std::println("[HomeAssistant] websocket conn error: {}", in ? in : "(null)"); + log(LOG::ERR, "HomeAssistant::event_handler", "websocket conn error: {}", in ? in : "(null)"); return; } case LWS_CALLBACK_CLIENT_RECEIVE: { ArduinoJson::deserializeJson(json, in); std::string ha_type = json["type"].as(); - // std::println("[HomeAssistant] got event type: {} ", ha_type); if (ha_type == "auth_required") { json.clear(); @@ -31,7 +30,7 @@ void HomeAssistant::event_handler(struct lws *wsi, enum lws_callback_reasons rea } if (ha_type == "auth_ok") { - std::println("[HomeAssistant] subscribing to entity \"{}\"", entity); + log(LOG::INF, "HomeAssistant::event_handler", "subscribing to entity \"{}\"", entity); json.clear(); json["id"] = id++; json["type"] = "subscribe_entities"; @@ -42,7 +41,7 @@ void HomeAssistant::event_handler(struct lws *wsi, enum lws_callback_reasons rea if (ha_type == "result") { if (json["success"].as() == "false") - std::println("[HomeAssistant] api said success was \"false\" on message id {}", id - 1); + log(LOG::ERR, "HomeAssistant::event_handler", "api said success was \"false\" on message id {}", id - 1); break; } @@ -51,24 +50,23 @@ void HomeAssistant::event_handler(struct lws *wsi, enum lws_callback_reasons rea break; } - std::println("[HomeAssistant] unhandled event: {}", (char *)in); + log(LOG::WRN, "HomeAssistant::event_handler", "unhandled event: {}", (char *)in); break; } case LWS_CALLBACK_CLIENT_ESTABLISHED: { - std::println("[HomeAssistant] Websocket connected"); + log(LOG::INF, "HomeAssistant::event_handler", "Websocket connected"); break; } case LWS_CALLBACK_CLIENT_CLOSED: { - std::println("[HomeAssistant] Websocket closed"); + log(LOG::INF, "HomeAssistant::event_handler", "Websocket closed"); return; } case LWS_CALLBACK_CLIENT_WRITEABLE: { /* skip whole callback if there's no tx to send */ if (tx.size() > 0) { - // std::println("[HomeAssistant] sending {}", tx); size_t msgLen = LWS_PRE + tx.size(); unsigned char *buf = (unsigned char *)malloc(msgLen); if (buf) { @@ -122,7 +120,7 @@ int HomeAssistant::connect() { context = lws_create_context(&info); if (!context) { - std::println("[HomeAssistant] error creating context"); + log(LOG::ERR, "HomeAssistant::connect", "error creating context"); return -1; } @@ -139,7 +137,7 @@ int HomeAssistant::connect() { websock = lws_client_connect_via_info(&i); if (!websock) { - std::println("[HomeAssistant] error creating lws client"); + log(LOG::ERR, "HomeAssistant::connect", "error creating lws client"); return -1; } return 0; diff --git a/src/utils.cpp b/src/utils.cpp index 4787885..1de6b15 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -46,7 +46,7 @@ std::string pBytes(double bytes, bool isKbytes) { ssize_t readFile2(const char* path, char* buffer, size_t maxlen) { int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) { - std::println("[readFile] Error reading {}", path); + log(LOG::ERR, "readFile2", "Error reading {}", path); return 0; } ssize_t len = read(fd, buffer, maxlen - 1);