fix to power display

This commit is contained in:
alu
2026-08-04 14:17:41 -07:00
parent 04b4f53092
commit 695ed9dd33
4 changed files with 57 additions and 39 deletions
+9 -1
View File
@@ -2,6 +2,7 @@ package app
import ( import (
"finally-a-monolithic-linux-hw-monitor/app/cpu" "finally-a-monolithic-linux-hw-monitor/app/cpu"
"finally-a-monolithic-linux-hw-monitor/app/cpu/proc"
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
@@ -24,11 +25,18 @@ func Run() {
os.Exit(0) os.Exit(0)
}() }()
proc, err := proc.GetProc()
ticker := time.NewTicker(1 * time.Second) ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop() defer ticker.Stop()
for { for {
console := &strings.Builder{} console := &strings.Builder{}
cpu.RenderCPU(console)
if err != nil {
return
}
cpu.RenderCPU(console, &proc)
console.WriteString("\nPress Ctrl+C to exit.\033[K\n") console.WriteString("\nPress Ctrl+C to exit.\033[K\n")
fmt.Print(console.String()) fmt.Print(console.String())
+5 -10
View File
@@ -6,12 +6,7 @@ import (
"strings" "strings"
) )
func RenderCPU(console *strings.Builder) { func RenderCPU(console *strings.Builder, proc *proc.Proc) {
proc, err := proc.GetProc()
if err != nil {
return
}
// Move cursor to top-left (0,0) without clearing full buffer (flicker-free) // Move cursor to top-left (0,0) without clearing full buffer (flicker-free)
console.WriteString("\033[H") console.WriteString("\033[H")
console.WriteString(fmt.Sprintf("=== %s ===\n", proc.Model())) console.WriteString(fmt.Sprintf("=== %s ===\n", proc.Model()))
@@ -20,9 +15,9 @@ func RenderCPU(console *strings.Builder) {
RenderPowerSensors(console, proc) RenderPowerSensors(console, proc)
} }
func RenderTemperatureSensors(console *strings.Builder, proc proc.Proc) { func RenderTemperatureSensors(console *strings.Builder, proc *proc.Proc) {
temps, _ := proc.SensorReader.ReadTemperatureSensors() temps, _ := proc.SensorReader.ReadTemperatureSensors()
console.WriteString("=== Temperature ===\n") console.WriteString("--- Temperature ---\n")
for _, sensor := range temps { for _, sensor := range temps {
tempC := sensor.TempC tempC := sensor.TempC
tempF := (tempC * 9 / 5) + 32 tempF := (tempC * 9 / 5) + 32
@@ -31,8 +26,8 @@ func RenderTemperatureSensors(console *strings.Builder, proc proc.Proc) {
} }
} }
func RenderPowerSensors(console *strings.Builder, proc proc.Proc) { func RenderPowerSensors(console *strings.Builder, proc *proc.Proc) {
console.WriteString("=== Power ===\n") console.WriteString("--- Power ---\n")
power, _ := proc.SensorReader.ReadPowerSensors() power, _ := proc.SensorReader.ReadPowerSensors()
for _, sensor := range power { for _, sensor := range power {
// \033[K clears from cursor to end of line (prevents lingering chars) // \033[K clears from cursor to end of line (prevents lingering chars)
+4
View File
@@ -45,6 +45,10 @@ func GetProc() (Proc, error) {
proc.Info = map[string]string{} proc.Info = map[string]string{}
scanner := bufio.NewScanner(procFile) scanner := bufio.NewScanner(procFile)
if scanner.Err() != nil {
return proc, scanner.Err()
}
for scanner.Scan() { for scanner.Scan() {
line := scanner.Text() line := scanner.Text()
line = strings.ReplaceAll(line, "\t", "") line = strings.ReplaceAll(line, "\t", "")
+36 -25
View File
@@ -2,6 +2,7 @@ package proc
import ( import (
"fmt" "fmt"
"math"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
@@ -12,7 +13,7 @@ import (
type AMDReader struct { type AMDReader struct {
hwmonDir string hwmonDir string
driver string driver string
energyState map[string]EnergyState // tracks (path -> energy state) for energy*_input calculations energyState map[string]EnergyState
} }
type EnergyState struct { type EnergyState struct {
@@ -21,10 +22,9 @@ type EnergyState struct {
} }
func NewAMDReader() (*AMDReader, error) { func NewAMDReader() (*AMDReader, error) {
// Locate AMD k10temp or zenpower hwmon path
matches, err := filepath.Glob("/sys/class/hwmon/hwmon*") matches, err := filepath.Glob("/sys/class/hwmon/hwmon*")
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("glob hwmon failed: %w", err)
} }
for _, dir := range matches { for _, dir := range matches {
@@ -37,6 +37,7 @@ func NewAMDReader() (*AMDReader, error) {
return &AMDReader{ return &AMDReader{
hwmonDir: dir, hwmonDir: dir,
driver: drv, driver: drv,
energyState: make(map[string]EnergyState),
}, nil }, nil
} }
} }
@@ -50,7 +51,7 @@ func (r *AMDReader) ReadTemperatureSensors() ([]TempSensor, error) {
return nil, fmt.Errorf("no temperature inputs found in %s", r.hwmonDir) return nil, fmt.Errorf("no temperature inputs found in %s", r.hwmonDir)
} }
temps := []TempSensor{} temps := make([]TempSensor, 0, len(inputs))
for _, inputPath := range inputs { for _, inputPath := range inputs {
valBytes, err := os.ReadFile(inputPath) valBytes, err := os.ReadFile(inputPath)
@@ -90,7 +91,7 @@ func (r *AMDReader) ReadPowerSensors() ([]PowerSensor, error) {
} }
func (r *AMDReader) readHwmonPower() []PowerSensor { func (r *AMDReader) readHwmonPower() []PowerSensor {
var powerSensors []PowerSensor powerSensors := []PowerSensor{}
getLabel := func(inputPath string) string { getLabel := func(inputPath string) string {
labelPath := strings.TrimSuffix(inputPath, "_input") + "_label" labelPath := strings.TrimSuffix(inputPath, "_input") + "_label"
@@ -127,22 +128,23 @@ func (r *AMDReader) readHwmonPower() []PowerSensor {
} }
func (r *AMDReader) readRaplPower() []PowerSensor { func (r *AMDReader) readRaplPower() []PowerSensor {
var powerSensors []PowerSensor powerSensors := []PowerSensor{}
// Match both top-level and nested RAPL zone directories
patterns := []string{ patterns := []string{
"/sys/class/powercap/intel-rapl*/energy_uj", "/sys/class/powercap/intel-rapl*/energy_uj",
"/sys/class/powercap/intel-rapl/intel-rapl*/energy_uj", "/sys/class/powercap/intel-rapl/intel-rapl*/energy_uj",
"/sys/class/powercap/intel-rapl/intel-rapl*/*/energy_uj", "/sys/class/powercap/intel-rapl/intel-rapl*/*/energy_uj",
"/sys/class/powercap/intel-rapl:*/energy_uj",
"/sys/class/powercap/intel-rapl:*/*/energy_uj",
} }
var energyInputs []string energyInputs := []string{}
seen := make(map[string]bool) seen := make(map[string]bool)
for _, pattern := range patterns { for _, pattern := range patterns {
matches, _ := filepath.Glob(pattern) matches, _ := filepath.Glob(pattern)
for _, match := range matches { for _, match := range matches {
// Resolve symlinks to get real sysfs path
realPath, err := filepath.EvalSymlinks(match) realPath, err := filepath.EvalSymlinks(match)
if err != nil { if err != nil {
realPath = match realPath = match
@@ -172,18 +174,18 @@ func (r *AMDReader) readRaplPower() []PowerSensor {
func (r *AMDReader) calculateEnergyDelta(inputs []string, getLabel func(string) string, out *[]PowerSensor) { func (r *AMDReader) calculateEnergyDelta(inputs []string, getLabel func(string) string, out *[]PowerSensor) {
now := time.Now() now := time.Now()
if r.energyState == nil { if r.energyState == nil {
r.energyState = make(map[string]EnergyState) r.energyState = make(map[string]EnergyState)
} }
for _, inputPath := range inputs { for _, rawPath := range inputs {
// Canonicalize path to resolve symlinks and prevent map key duplication key, err := filepath.EvalSymlinks(rawPath)
realPath, err := filepath.EvalSymlinks(inputPath)
if err != nil { if err != nil {
realPath = inputPath key = filepath.Clean(rawPath)
} }
valBytes, err := os.ReadFile(realPath) valBytes, err := os.ReadFile(key)
if err != nil { if err != nil {
continue continue
} }
@@ -193,26 +195,29 @@ func (r *AMDReader) calculateEnergyDelta(inputs []string, getLabel func(string)
continue continue
} }
prevState, exists := r.energyState[realPath] prevState, exists := r.energyState[key]
r.energyState[realPath] = EnergyState{
if !exists {
r.energyState[key] = EnergyState{
lastEnergy: microJoules, lastEnergy: microJoules,
lastTime: now, lastTime: now,
} }
*out = append(*out, PowerSensor{
// Initial seed step: power delta requires two distinct reads Name: getLabel(key),
if !exists { Watts: 0.0,
})
continue continue
} }
timeDiff := now.Sub(prevState.lastTime).Seconds() timeDiff := now.Sub(prevState.lastTime).Seconds()
if timeDiff <= 0 { if timeDiff < 0.05 {
continue continue
} }
maxRange := uint64(1<<64 - 1) maxRange := uint64(math.MaxUint64)
rangeBytes, err := os.ReadFile(filepath.Join(filepath.Dir(realPath), "max_energy_range_uj")) rangeBytes, err := os.ReadFile(filepath.Join(filepath.Dir(key), "max_energy_range_uj"))
if err == nil { if err == nil {
if parsedMax, err := strconv.ParseUint(strings.TrimSpace(string(rangeBytes)), 10, 64); err == nil { if parsedMax, err := strconv.ParseUint(strings.TrimSpace(string(rangeBytes)), 10, 64); err == nil && parsedMax > 0 {
maxRange = parsedMax maxRange = parsedMax
} }
} }
@@ -221,12 +226,18 @@ func (r *AMDReader) calculateEnergyDelta(inputs []string, getLabel func(string)
if microJoules >= prevState.lastEnergy { if microJoules >= prevState.lastEnergy {
energyDiff = microJoules - prevState.lastEnergy energyDiff = microJoules - prevState.lastEnergy
} else { } else {
energyDiff = maxRange - prevState.lastEnergy + microJoules energyDiff = (maxRange - prevState.lastEnergy) + microJoules
} }
watts := (float64(energyDiff) / 1_000_000.0) / timeDiff watts := (float64(energyDiff) / 1_000_000.0) / timeDiff
r.energyState[key] = EnergyState{
lastEnergy: microJoules,
lastTime: now,
}
*out = append(*out, PowerSensor{ *out = append(*out, PowerSensor{
Name: getLabel(realPath), Name: getLabel(key),
Watts: watts, Watts: watts,
}) })
} }