vulp  2.2.2
CpuTemperature.cpp
Go to the documentation of this file.
1 // Copyright 2022 Stéphane Caron
2 // SPDX-License-Identifier: Apache-2.0
3 
5 
7 
8 CpuTemperature::CpuTemperature(const char* temp_path) : has_warned_(false) {
9  fd_ = ::open(temp_path, O_RDONLY | O_NONBLOCK);
10  ::memset(buffer_, 0, sizeof(buffer_));
11 }
12 
14  if (fd_ >= 0) {
15  ::close(fd_);
16  }
17 }
18 
19 void CpuTemperature::write(Dictionary& observation) {
20  if (is_disabled_) {
21  return;
22  } else if (fd_ < 0) {
23  spdlog::warn("CPU temperature observation disabled: file not found");
24  is_disabled_ = true;
25  return;
26  }
27 
28  ssize_t size = ::pread(fd_, buffer_, kCpuTemperatureBufferSize, 0);
29  if (size <= 0) {
30  spdlog::warn("Read {} bytes from temperature file", size);
31  return;
32  }
33  const double temperature = std::stol(buffer_) / 1000.;
34  check_temperature_warning(temperature);
35  auto& output = observation(prefix());
36  output = temperature;
37 }
38 
39 void CpuTemperature::check_temperature_warning(
40  const double temperature) noexcept {
41  constexpr double kConcerningTemperature = 75.0;
42  if (temperature > kConcerningTemperature) {
43  if (!has_warned_) {
44  spdlog::warn("CPU temperature > {} °C, thermal throttling may occur",
45  kConcerningTemperature);
46  has_warned_ = true;
47  }
48  }
49 
50  constexpr double kHysteresisFactor = 0.95;
51  if (has_warned_ && temperature < kHysteresisFactor * kConcerningTemperature) {
52  has_warned_ = false;
53  }
54 }
55 
56 } // namespace vulp::observation::sources
std::string prefix() const noexcept final
Prefix of output in the observation dictionary.
CpuTemperature(const char *temp_path="/sys/class/thermal/thermal_zone0/temp")
Open file to query temperature from the kernel.
void write(Dictionary &observation) final
Write output to a dictionary.
constexpr unsigned kCpuTemperatureBufferSize
Characters required to read the temperature in [mC] from the kernel.