Files
finally-a-monolithic-linux-…/app/cpu/drivers/hwmon.go
T
2026-08-04 15:27:55 -07:00

77 lines
1.6 KiB
Go

package drivers
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
type HwmonDriver struct {
hwmonDir string
hwmonDriver string
}
func NewHwmonDriver(expectedDrivers []string) *HwmonDriver {
// Locate hwmon path
dirs, err := filepath.Glob("/sys/class/hwmon/hwmon*")
if err != nil {
return nil
}
for _, dir := range dirs {
nameRaw, err := os.ReadFile(filepath.Join(dir, "name"))
name := strings.TrimSpace(string(nameRaw))
if err == nil {
for _, driver := range expectedDrivers {
if driver == name {
return &HwmonDriver{
hwmonDir: dir,
hwmonDriver: driver,
}
}
}
}
}
return nil
}
func (r *HwmonDriver) ReadTemperatureSensors() ([]TemperatureSensor, error) {
inputs, err := filepath.Glob(filepath.Join(r.hwmonDir, "temp*_input"))
if err != nil || len(inputs) == 0 {
return nil, fmt.Errorf("no temperature inputs found in %s", r.hwmonDir)
}
temps := make([]TemperatureSensor, 0, len(inputs))
for _, inputPath := range inputs {
valBytes, err := os.ReadFile(inputPath)
if err != nil {
continue
}
milliC, err := strconv.ParseFloat(strings.TrimSpace(string(valBytes)), 64)
if err != nil {
continue
}
labelPath := strings.TrimSuffix(inputPath, "_input") + "_label"
label := ""
if lBytes, err := os.ReadFile(labelPath); err == nil {
label = strings.TrimSpace(string(lBytes))
} else {
label = filepath.Base(strings.TrimSuffix(inputPath, "_input"))
}
temps = append(temps, TemperatureSensor{
path: inputPath,
Name: label,
TempC: milliC / 1000.0,
})
}
return temps, nil
}