$OpenBSD: patch-src_modules_temperature_cpp,v 1.3 2021/02/27 12:03:43 jasper Exp $

Index: src/modules/temperature.cpp
--- src/modules/temperature.cpp.orig
+++ src/modules/temperature.cpp
@@ -8,6 +8,17 @@
 
 #include "modules/meta/base.inl"
 
+#ifdef __OpenBSD__
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#include <sys/sensors.h>
+#include <errno.h>
+#include <err.h>
+
+#define MUKTOC(v) ((v - 273150000) / 1000000.0)
+#endif
+
 POLYBAR_NS
 
 namespace modules {
@@ -26,9 +37,11 @@ namespace modules {
       m_path = string_util::replace(PATH_TEMPERATURE_INFO, "%zone%", to_string(m_zone));
     }
 
+#ifndef __OpenBSD__
     if (!file_util::exists(m_path)) {
       throw module_error("The file '" + m_path + "' does not exist");
     }
+#endif /* !__OpenBSD__ */
 
     m_formatter->add(DEFAULT_FORMAT, TAG_LABEL, {TAG_LABEL, TAG_RAMP});
     m_formatter->add(FORMAT_WARN, TAG_LABEL_WARN, {TAG_LABEL_WARN, TAG_RAMP});
@@ -51,8 +64,54 @@ namespace modules {
   }
 
   bool temperature_module::update() {
+    int temp_f;
+#ifdef __OpenBSD__
+    /*
+     * The following code was copied from i3status/print_cpu_temperature.c
+     */
+    struct sensordev sensordev;
+    struct sensor sensor;
+    size_t sdlen, slen;
+    char device[16];
+    int dev, mib[5] = {CTL_HW, HW_SENSORS, 0, 0, 0};
+
+    sdlen = sizeof(sensordev);
+    slen = sizeof(sensor);
+
+    /*
+     * Construct a sensors MIB by using hwmon-path and thermal-zone such
+     * that hwmon-path represents the device (e.g. acpitz0 or ksmn0) and thermal-zone
+     * the Nth temperature sensor (e.g. temp0).
+     */
+    strlcpy(device, m_path.c_str(), sizeof(device));
+
+    for (dev = 0;; dev++) {
+        mib[2] = dev;
+        if (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) == -1) {
+            if (errno == ENXIO)
+                continue;
+            if (errno == ENOENT)
+                break;
+            return false;
+        }
+
+       if (strncmp(sensordev.xname, device, strlen(device)) == 0) {
+            mib[3] = SENSOR_TEMP;
+            mib[4] = m_zone;
+            if (sysctl(mib, 5, &sensor, &slen, NULL, 0) == -1) {
+                if (errno != ENOENT) {
+                    m_log.warn("sysctl failed");
+                    continue;
+                }
+            }
+        }
+    }
+    m_temp = MUKTOC(sensor.value);
+#else
     m_temp = std::strtol(file_util::contents(m_path).c_str(), nullptr, 10) / 1000.0f + 0.5f;
-    int temp_f = floor(((1.8 * m_temp) + 32) + 0.5);
+#endif
+
+    temp_f = floor(((1.8 * m_temp) + 32) + 0.5);
     m_perc = math_util::unbounded_percentage(m_temp, m_tempbase, m_tempwarn);
 
     string temp_c_string = to_string(m_temp);
