| 8 | #endif |
| 9 | |
| 10 | waybar::modules::Temperature::Temperature(const std::string& id, const Json::Value& config) |
| 11 | : ALabel(config, "temperature", id, "{temperatureC}°C", 10) { |
| 12 | #if defined(__FreeBSD__) |
| 13 | // FreeBSD uses sysctlbyname instead of read from a file |
| 14 | #else |
| 15 | auto traverseAsArray = [](const Json::Value& value, auto&& check_set_path) { |
| 16 | if (value.isString()) |
| 17 | check_set_path(value.asString()); |
| 18 | else if (value.isArray()) |
| 19 | for (const auto& item : value) |
| 20 | if (check_set_path(item.asString())) break; |
| 21 | }; |
| 22 | |
| 23 | // if hwmon_path is an array, loop to find first valid item |
| 24 | traverseAsArray(config_["hwmon-path"], [this](const std::string& path) { |
| 25 | if (!std::filesystem::exists(path)) return false; |
| 26 | file_path_ = path; |
| 27 | return true; |
| 28 | }); |
| 29 | |
| 30 | if (file_path_.empty() && config_["input-filename"].isString()) { |
| 31 | // fallback to hwmon_paths-abs |
| 32 | traverseAsArray(config_["hwmon-path-abs"], [this](const std::string& path) { |
| 33 | if (!std::filesystem::is_directory(path)) return false; |
| 34 | return std::ranges::any_of( |
| 35 | std::filesystem::directory_iterator(path), [this](const auto& hwmon) { |
| 36 | if (!hwmon.path().filename().string().starts_with("hwmon")) return false; |
| 37 | file_path_ = hwmon.path().string() + "/" + config_["input-filename"].asString(); |
| 38 | return true; |
| 39 | }); |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | if (file_path_.empty()) { |
| 44 | auto zone = config_["thermal-zone"].isInt() ? config_["thermal-zone"].asInt() : 0; |
| 45 | file_path_ = fmt::format("/sys/class/thermal/thermal_zone{}/temp", zone); |
| 46 | } |
| 47 | |
| 48 | // check if file_path_ can be used to retrieve the temperature |
| 49 | std::ifstream temp(file_path_); |
| 50 | if (!temp.is_open()) { |
| 51 | throw std::runtime_error("Can't open " + file_path_); |
| 52 | } |
| 53 | if (!temp.good()) { |
| 54 | temp.close(); |
| 55 | throw std::runtime_error("Can't read from " + file_path_); |
| 56 | } |
| 57 | temp.close(); |
| 58 | #endif |
| 59 | |
| 60 | thread_ = [this] { |
| 61 | dp.emit(); |
| 62 | thread_.sleep_for(interval_); |
| 63 | }; |
| 64 | } |
| 65 | |
| 66 | auto waybar::modules::Temperature::update() -> void { |
| 67 | auto temperature = getTemperature(); |