From 10958450bacf7996822a17c8b4f35fc20aea5d3c Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Sat, 11 Jul 2026 19:48:23 -0400 Subject: [PATCH] getting temp under control --- bin/TEMP_MONITOR_README.md | 101 +++++++++ bin/temp-monitor | 202 ++++++++++++++++++ hosts/fwbook.nix | 1 + .../nixos/common/hardware/laptop-power.nix | 124 ++++++++++- 4 files changed, 427 insertions(+), 1 deletion(-) create mode 100644 bin/TEMP_MONITOR_README.md create mode 100755 bin/temp-monitor diff --git a/bin/TEMP_MONITOR_README.md b/bin/TEMP_MONITOR_README.md new file mode 100644 index 0000000..421fb73 --- /dev/null +++ b/bin/TEMP_MONITOR_README.md @@ -0,0 +1,101 @@ +# Temperature Monitor Script + +A nushell script for monitoring your laptop's CPU/GPU temperatures, storing them with timestamps, and visualizing them as a graph. + +## Features + +- **Real-time monitoring**: Collects temperature readings at configurable intervals +- **Persistent storage**: Saves all readings to a CSV file with timestamps +- **Multiple sources**: Tries multiple methods to read temperature data (lm_sensors, acpi, sysfs) +- **ASCII graphs**: Displays temperature data as an ASCII bar graph +- **Flexible configuration**: Customize duration, interval, and output location + +## Requirements + +The script automatically detects and uses available tools. It will try these in order: +1. `sensors` (from `lm_sensors`) - **Recommended** - Most reliable +2. `acpi` - Fallback option +3. `/sys/class/thermal/thermal_zone0/temp` - Linux sysfs fallback + +On NixOS, you can add these to your environment with: +```nix +environment.systemPackages = with pkgs; [ + lm_sensors + acpi +]; +``` + +## Usage + +### Basic usage (60-second collection with 2-second intervals) +```bash +./bin/temp-monitor +``` + +### Collect for 5 minutes with 5-second intervals +```bash +./bin/temp-monitor --duration 300 --interval 5 +``` + +### Collect and display graph +```bash +./bin/temp-monitor --duration 60 --graph +``` + +### Custom output file location +```bash +./bin/temp-monitor --output ~/my-temps.csv --duration 120 --graph +``` + +### View stored data +```bash +cat ~/.cache/temp-data.csv +``` + +## Command-line Options + +- `--duration ` - How long to collect data (default: 60) +- `--interval ` - Seconds between readings (default: 2) +- `--output ` - CSV file location (default: ~/.cache/temp-data.csv) +- `--graph` - Display ASCII graph after collection completes + +## Output Format + +The script stores data in CSV format with columns: +``` +timestamp,cpu_temp,gpu_temp,max_temp +2024-07-11 14:30:45,65.5,N/A,65.5 +2024-07-11 14:30:47,66.2,N/A,66.2 +``` + +## Graph Example + +``` +2024-07-11 14:30:45: ████████████ 65.5°C +2024-07-11 14:30:47: ██████████████ 66.2°C +2024-07-11 14:30:49: ████████████████ 68.1°C + +Min: 65.5°C | Max: 68.1°C | Range: 2.6°C +``` + +## Tips + +- Run multiple instances with different `--output` files to track different time periods +- Use cron to collect continuous background data: `*/5 * * * * ~/nixos-setup/bin/temp-monitor --duration 1 --interval 1` +- High temperatures may indicate a need for thermal paste replacement or fan cleaning +- The graph is great for spotting thermal throttling or fan ramp-ups during workloads + +## Troubleshooting + +**No temperature readings (showing "N/A")**: +- Check if `sensors` is installed and working: `sensors` +- Check thermal zone: `cat /sys/class/thermal/thermal_zone0/temp` +- Run `sudo sensors-detect` to configure lm_sensors on first use + +**Permission denied reading temperatures**: +- Some systems require sudo for detailed sensor access +- Try: `sudo ./bin/temp-monitor` + +**CSV file grows too large**: +- Archive old data: `mv ~/.cache/temp-data.csv ~/.cache/temp-data-$(date +%s).csv` +- Or use `--output` with a date-stamped filename diff --git a/bin/temp-monitor b/bin/temp-monitor new file mode 100755 index 0000000..51a5a50 --- /dev/null +++ b/bin/temp-monitor @@ -0,0 +1,202 @@ +#!/usr/bin/env nu + +# Temperature monitoring script for laptop +# Collects CPU/GPU temperatures, stores them with timestamps, and displays a graph + +def main [ + --duration: int = 60 # Duration to collect data in seconds (default: 60) + --interval: int = 2 # Interval between readings in seconds (default: 2) + --output: string = "~/.cache/temp-data.csv" # Output file for temperature data + --graph # Show graph at the end + --show-graph # Just show graph from existing data (don't collect) +] { + let data_file = ($output | path expand) + + if $show_graph { + show-graph $data_file + return + } + + let cache_dir = ($data_file | path dirname) + + # Create cache directory if it doesn't exist + if not ($cache_dir | path exists) { + mkdir $cache_dir + } + + # Initialize or append to CSV file with headers if empty + if not ($data_file | path exists) or (open $data_file | is-empty) { + "timestamp,cpu_temp,gpu_temp,max_temp" | save -f $data_file + } + + print $"🌡️ Temperature Monitor - Collecting data for ($duration)s with ($interval)s intervals..." + print $"📊 Data will be saved to: ($data_file)\n" + + let iterations = (($duration / $interval) | math round) + + for i in 1..$iterations { + let timestamp = (date now | format date '%Y-%m-%d %H:%M:%S') + + # Get temperature reading + let temp_info = (get-temperature) + + let cpu_temp = $temp_info.cpu + let gpu_temp = $temp_info.gpu + + let max_temp = ( + if ($cpu_temp != "N/A") and ($gpu_temp != "N/A") { + [($cpu_temp | into float) ($gpu_temp | into float)] | math max + } else if ($cpu_temp != "N/A") { + $cpu_temp | into float + } else if ($gpu_temp != "N/A") { + $gpu_temp | into float + } else { + "N/A" + } + ) + + let row = $"($timestamp),($cpu_temp),($gpu_temp),($max_temp)" + + # Append to CSV file + let content = (open $data_file --raw) + ($content | str trim) + "\n" + $row | save -f $data_file + + print $"✓ ($timestamp) | CPU: ($cpu_temp)°C | GPU: ($gpu_temp)°C | Max: ($max_temp)°C" + + if $i < $iterations { + sleep ($interval | into duration -u sec) + } + } + + print $"\n✅ Data collection complete!" + + # Always show the graph at the end + show-graph $data_file + + print $"📁 Data saved to: ($data_file)" +} + +def get-temperature [] { + # Try lm_sensors first (most reliable) + if (which sensors | is-not-empty) { + get-temp-sensors + } else if (which acpi | is-not-empty) { + get-temp-acpi + } else if ("/sys/class/thermal/thermal_zone0/temp" | path exists) { + get-temp-sysfs + } else { + { cpu: "N/A", gpu: "N/A" } + } +} + +def get-temp-sensors [] { + try { + # Try to get CPU temp from k10temp (AMD) + let cpu_temp = ( + try { + sensors k10temp-pci-00c3 | grep "Tctl" | grep -oE "[0-9]+\\.[0-9]+" | head -1 + } catch { + # Fallback: look in all sensors output + sensors | grep -i "Tctl\|Package" | head -1 | grep -oE "[0-9]+\\.[0-9]+" | head -1 + } + ) + + # Try to get GPU temp from amdgpu + let gpu_temp = ( + try { + sensors amdgpu-pci-c100 | grep "edge" | grep -oE "[0-9]+\\.[0-9]+" | head -1 + } catch { + "N/A" + } + ) + + { cpu: $cpu_temp, gpu: $gpu_temp } + } catch { + { cpu: "N/A", gpu: "N/A" } + } +} + +def get-temp-acpi [] { + try { + let temp = (acpi -t | head -1 | grep -oE "[0-9]+\\.[0-9]+" | first) + { cpu: $temp, gpu: "N/A" } + } catch { + { cpu: "N/A", gpu: "N/A" } + } +} + +def get-temp-sysfs [] { + try { + let raw_temp = (open /sys/class/thermal/thermal_zone0/temp | str trim | into float) + let temp = ($raw_temp / 1000) + { cpu: $temp, gpu: "N/A" } + } catch { + { cpu: "N/A", gpu: "N/A" } + } +} + +def show-graph [file: string] { + print "\n📈 Temperature Graph:\n" + + try { + # Read the CSV file as a regular table + let data = (open $file) + + # Filter out rows where max_temp is not a number + let temps = ( + $data + | where { $in.max_temp != "N/A" } + | select timestamp max_temp + | rename time temp + | each { |row| + { + time: $row.time + temp: ($row.temp | into float) + } + } + ) + + if ($temps | is-empty) { + print "No valid temperature data to display." + return + } + + # Find min/max for scaling + let min_temp = ($temps | get temp | math min) + let max_temp = ($temps | get temp | math max) + let temp_range = ($max_temp - $min_temp) + let graph_height = 20 + + # Create simple ASCII graph + let graph = ( + $temps + | each { |item| + let normalized = ( + if ($temp_range == 0) { + 0.5 + } else { + (($item.temp - $min_temp) / $temp_range) + } + ) + let bar_height = (($normalized * $graph_height) | math round) + let bar = ( + if $bar_height > 0 { + 0..<$bar_height | each { "█" } | str join "" + } else { + "." + } + ) + let time_only = ($item.time | str substring 11..19) + $"($time_only): ($bar) ($item.temp)°C" + } + | str join "\n" + ) + + print $graph + print $"\nMin: ($min_temp | math round -p 1)°C | Max: ($max_temp | math round -p 1)°C | Range: ($temp_range | math round -p 1)°C" + } catch { |err| + print $"Error displaying graph: ($err)" + } +} + +main diff --git a/hosts/fwbook.nix b/hosts/fwbook.nix index 50ceba7..ad616cf 100644 --- a/hosts/fwbook.nix +++ b/hosts/fwbook.nix @@ -29,6 +29,7 @@ in laptop-power-mgr = { enable = true; enableLidMonitorMode = true; + enableTempMonitor = true; disableLidSwitch = true; }; amdgpu.enable = true; diff --git a/modules/nixos/common/hardware/laptop-power.nix b/modules/nixos/common/hardware/laptop-power.nix index 3b4a8ef..3c4fab8 100644 --- a/modules/nixos/common/hardware/laptop-power.nix +++ b/modules/nixos/common/hardware/laptop-power.nix @@ -6,6 +6,79 @@ let cfg = config.skyg.nixos.common.hardware.laptop-power-mgr; + # Script that logs CPU/GPU temps to journal and fires desktop + # notifications when temperatures cross warning / critical thresholds. + temp-monitor-script = pkgs.writeShellScript "temp-monitor" '' + ${pkgs.python3}/bin/python3 << 'EOFPYTHON' + import subprocess, time, os, re, sys + + WARN_TEMP = 80.0 # °C — sends a normal notification + CRIT_TEMP = 90.0 # °C — sends an urgent notification + INTERVAL = 30 # seconds between readings + COOLDOWN = 300 # seconds before repeating the same alert level + + def read_temp(chip, label): + try: + r = subprocess.run(["${pkgs.lm_sensors}/bin/sensors", chip], + capture_output=True, text=True, timeout=5) + for line in r.stdout.splitlines(): + if label in line: + m = re.search(r"\+?([0-9]+\.[0-9]+)", line) + if m: + return float(m.group(1)) + except Exception: + pass + return None + + def notify(urgency, title, body): + """Send a desktop notification to every logged-in user session.""" + try: + for entry in os.scandir("/run/user"): + bus = os.path.join(entry.path, "bus") + if os.path.exists(bus): + env = os.environ.copy() + env["DBUS_SESSION_BUS_ADDRESS"] = f"unix:path={bus}" + try: + subprocess.run( + ["${pkgs.libnotify}/bin/notify-send", + "--urgency", urgency, title, body], + env=env, timeout=5, capture_output=True) + except Exception as e: + print(f"notify-send failed: {e}", file=sys.stderr, flush=True) + except Exception as e: + print(f"Could not scan /run/user: {e}", file=sys.stderr, flush=True) + + print(f"Temp monitor started warn={WARN_TEMP}°C crit={CRIT_TEMP}°C interval={INTERVAL}s", + flush=True) + + last_warn = 0 + last_crit = 0 + + while True: + now = time.time() + cpu = read_temp("k10temp-pci-00c3", "Tctl") + gpu = read_temp("amdgpu-pci-c100", "edge") + + cpu_s = f"{cpu:.1f}°C" if cpu is not None else "N/A" + gpu_s = f"{gpu:.1f}°C" if gpu is not None else "N/A" + print(f"CPU: {cpu_s} GPU: {gpu_s}", flush=True) + + if cpu is not None: + if cpu >= CRIT_TEMP and (now - last_crit) > COOLDOWN: + notify("critical", + "🔥 CPU Critical Temperature", + f"CPU is at {cpu:.0f}°C — above {CRIT_TEMP:.0f}°C!") + last_crit = now + elif cpu >= WARN_TEMP and (now - last_warn) > COOLDOWN: + notify("normal", + "⚠️ CPU High Temperature", + f"CPU is at {cpu:.0f}°C — above {WARN_TEMP:.0f}°C") + last_warn = now + + time.sleep(INTERVAL) + EOFPYTHON + ''; + # Script to monitor lid events and send notifications lid-monitor-script = pkgs.writeShellScript "lid-event-monitor" '' ${pkgs.python3}/bin/python3 << 'EOFPYTHON' @@ -68,6 +141,16 @@ in options.skyg.nixos.common.hardware.laptop-power-mgr = with lib; { enable = mkEnableOption "Settings for laptop power management"; + enableTempMonitor = mkOption { + type = types.bool; + default = false; + description = '' + Enable a background service that logs CPU and GPU temperatures to the + journal every 30 seconds and sends a desktop notification when the CPU + crosses 80 °C (warning) or 90 °C (critical). + ''; + }; + enableLidMonitorMode = mkOption { type = types.bool; default = false; @@ -95,8 +178,31 @@ in # Advance Power Management powerManagement.powertop.enable = true; powerManagement.enable = true; - services.thermald.enable = true; + # thermald is Intel-only; it exits immediately on AMD machines and + # provides no thermal protection there. Do not enable it. + services.thermald.enable = false; services.power-profiles-daemon.enable = true; + + # power-profiles-daemon remembers the last selected profile across + # reboots, so a one-time switch to "performance" would otherwise stick + # forever and cause constant overheating. Reset to "balanced" at boot + # and also set a conservative CPU energy policy (balance_power) so the + # chassis stays cooler when idle. + systemd.services.reset-power-profile = { + description = "Reset power profile to balanced + conservative EPP at boot"; + wantedBy = [ "multi-user.target" ]; + after = [ "power-profiles-daemon.service" ]; + wants = [ "power-profiles-daemon.service" ]; + serviceConfig = { + Type = "oneshot"; + ExecStart = "${pkgs.writeShellScript "reset-power-and-epp" '' + ${pkgs.power-profiles-daemon}/bin/powerprofilesctl set balanced + for f in /sys/devices/system/cpu/cpu*/cpufreq/energy_performance_preference; do + echo balance_power > "$f" 2>/dev/null || true + done + ''}"; + }; + }; services.tlp = { enable = false; settings = { @@ -156,6 +262,22 @@ in libnotify ]; + # Background temperature monitor — logs to journal, alerts when hot + systemd.services.temp-monitor = lib.mkIf cfg.enableTempMonitor { + description = "CPU/GPU temperature monitor"; + wantedBy = [ "multi-user.target" ]; + after = [ "multi-user.target" ]; + + serviceConfig = { + Type = "simple"; + ExecStart = "${temp-monitor-script}"; + Restart = "on-failure"; + RestartSec = 10; + StandardOutput = "journal"; + StandardError = "journal"; + }; + }; + # System service to monitor lid events and send notifications # Only enabled if enableLidMonitorMode is true systemd.services.lid-event-monitor = lib.mkIf cfg.enableLidMonitorMode {