Skip to content
askenderPublic

About

macOS fan control & power survey for Apple Silicon — one dependency-free binary: menu bar app + CLI, smart curve & PI thermostat. 单二进制:菜单栏+CLI,风扇温控与功耗一览

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

fansctl

CI License: AGPL v3 Release Platform

中文文档

Fan and temperature control for Apple Silicon Macs, field-tested on a MacBook Pro 16" M1 Max (MacBookPro18,4). One binary, two faces: run it with no arguments and it becomes a menu-bar app (forks to the background, never occupies your terminal); pass a command and it is a CLI. Zero third-party dependencies — links only system frameworks (IOKit / CoreFoundation / AppKit / Security).

The menu-bar UI is bilingual (English / 中文): it follows your system language and can be switched at any time from the menu. The CLI and the daemons' logs/notifications follow the system UI language: priority is FANSCTL_LANG > System Settings Language & Region (AppleLanguages) > locale variables; override with FANSCTL_LANG=zh|en. The terminal's LANG no longer leaks into sudo/launchd contexts (before v1.8.3 a terminal with LANG=en made sudo fansctl smart log and notify in English). Version: fansctl version (currently 1.8.3).

Build & install

Homebrew (builds from the release source tag):

brew tap askender/tap && brew install fansctl

Or from a checkout:

make                # build ./fansctl
make install        # install to ~/.local/bin (rm-then-cp: AMFI quirk)
make install-root   # install setuid-root helper to /usr/local/bin/fansctl-root (one password)
make test           # smoke test (read-only, never touches fan state)
./fansctl __selftest  # pure-logic unit checks (naming table, JSON, plist) — no SMC needed
make restart        # restart the menu bar (relaunched by the LaunchAgent)

Invariant: after changing privileged logic (__apply/__smart/__hold), make + make install must be followed by make install-root to sync the helper; pure UI/read-only changes do not need it.

CLI

fansctl               start the menu-bar app (forks to background)
fansctl fans          list fan RPMs (read-only)
fansctl status        current/target RPMs and mode (read-only)
fansctl temps [--sort] [--above N]  all temperature sensors, human-readable names where
                      known (SoC, CPU P/E-cores, GPU, memory, NAND, battery, airflow);
                      --sort hottest first, --above filters by °C
fansctl power         power survey (read-only): system draw, input, adapter, USB, top processes
fansctl power --watch [sec]   continuous power monitoring (default 5 s)
fansctl dump          dump all SMC keys (exploration)
fansctl watch [sec]   refresh loop (default 2 s)
sudo fansctl set <rpm> [N]   set RPM (no N = all fans)
sudo fansctl max [N]         full speed
sudo fansctl auto [N]        back to automatic
sudo fansctl smart [lo hi]   smart curve (default 40~80°C; Ctrl+C or smart stop exits and restores;
                             notifies once when the high threshold is hit)
sudo fansctl smart stop      stop smart mode (incl. instances started from the menu bar)
sudo fansctl hold [°C]       thermostat mode, PI closed loop on the hottest sensor (default 70°C,
                             mutually exclusive with smart; notifies if it cannot hold the target)
sudo fansctl hold stop       stop thermostat mode (incl. menu-bar instances)
fansctl bar install|uninstall|status   manage menu-bar auto-start (no sudo)
fansctl doctor        collect diagnostics (incl. load history from the daemon logs)
                      — attach the output when filing issues

Read-only commands accept --json (unknown values are null; keys in English regardless of interface language); temperature entries carry a name field. watch --json and power --json --watch emit one JSON object per line:

fansctl status --json
fansctl watch --json 5 | jq -c '.fans[0].actual_rpm'
fansctl power --json --watch 5 | jq -c '.system_w'

make install (and the Homebrew formula) also install a man page (man fansctl) and zsh/bash completions.

Menu bar

fansctl menu (English) fansctl 菜单 (中文)

  • Status item: hottest°C|max rpm (krpm), refreshed every 2 s
  • "CPU avg" row: arithmetic mean of the CPU P/E-core sensors. Read it next to the hottest value to tell whether the heat comes from the CPU (with a GPU/memory hotspot the CPU average stays clearly lower; same idea as macmon's cpu_temp_avg, but display-only — control still uses the hottest sensor). Auto-hidden on machines without core sensors. status --json outputs the same as cpu_temp_avg (null when unavailable)
  • First row: hottest sensor / curve % or thermostat target + system power draw (SMC key PSTR, same source as ioreg SystemPowerIn; auto-hidden on machines without it). While charging, the battery component (Amperage×Voltage) is subtracted and shown separately, e.g. 34W+10W chg = 34 W system + 10 W going into the battery
  • Max / Auto / Smart / Thermostat — four mutually exclusive states with checkmarks; clicking any control first takes over (stops a running Smart/Thermostat daemon), then applies
  • Smart thresholds submenu: 6095 (default) / 5595 / 4585 / 4080, persisted in NSUserDefaults, hot-updatable while running (SIGUSR1 + pidfile, control never interrupted)
  • Thermostat target submenu: 65 / 70 (default) / 75 / 80°C, likewise hot-updatable
  • Language submenu: 中文 / English — defaults to the system language, switching takes effect immediately and persists
  • The dropdown reopens automatically after an action; the timer keeps refreshing while the menu is open (NSRunLoopCommonModes)
  • Quit (⌘Q): if no daemon is running and fans are in manual mode, auto is restored via the helper before quitting (no orphan RPM); quitting the UI never kills a running daemon
  • Single-instance guard: /tmp/fansctl.bar.pid

Smart mode

Control input = the hottest of all temperature sensors (conservative). T ≤ low threshold → hand control back to the system (fans may stop); between thresholds → linear interpolation from the baseline to full speed; ≥ high threshold → full speed; 1°C hysteresis prevents flapping. Baseline = the system's target RPM at the moment of takeover; if the fan was already in manual mode (stale session), it falls back to the minimum RPM. State pidfile /tmp/fansctl.smart.pid = pid low high, shared between CLI and menu bar. SIGTERM exits gracefully (restores auto); log: /tmp/fansctl.smart.log (one line per tick, stamped with local time; includes the pid that sent the stop signal, useful for debugging unexpected exits). Feedforward ticks carry an extra W ff+rpm segment:

[10-02 16:20:31] [55~95°C] TCMz 70.8°C 曲线47% | 风扇0   3596 rpm (+47%) 手动 风扇1   3878 rpm (+47%) 手动
[10-02 16:20:33] [55~95°C] TCMz 77.8°C 曲线57% | 38W ff+69 | 风扇0   3999 rpm (+88%) 手动 风扇1   4287 rpm (+88%) 手动
[10-02 16:20:35] [55~95°C] TCMz 78.1°C 曲线58% | 39W ff+281 | 风扇0   4476 rpm (+96%) 手动 风扇1   4793 rpm (+95%) 手动

(a real trigger: the fans moved on the power ramp before the temperature peaked at 78.1°C, then the feedforward decayed and the temperature settled back to 71°C.)

Power feedforward (v1.8.0): system power draw ≈ heat output, and the power signal moves seconds before the temperature does. Smart mode reads the SMC key PSTR (second-level real-time) each tick, subtracts the charging component while charging (that energy goes into the battery, not the heatsink) and feeds it through a lead-lag filter (fast/slow EMA difference). On a load ramp (compilation, model loading) the fast line lifts first and the fans spin up immediately — about 6 s earlier than waiting for the die to warm. In steady state the two EMAs reconverge, the feedforward decays to zero, and the temperature curve owns the steady state; on battery or machines without PSTR it steps aside entirely. The boost is rate-limited (250 rpm per second) and capped (1500 rpm); the worst case of a wrong feedforward is a few seconds of extra spinning — the temperature feedback corrects it immediately.

Robustness:

  • Wake handoff — a stretched tick (continuous clock mach_continuous_time, which keeps running during sleep) detects a system wake: control is handed back for 5 s while sensors stabilize, then retaken on a fresh baseline
  • MODE_REASSERT — every tick verifies manual ownership and the target RPM; if an external tool or the system overwrote them (switched back to auto, replaced the target), fansctl retakes control or rewrites the target immediately
  • Write backoff — when the SMC is busy (0x82, thermal controller occupied), retries with exponential backoff for ~1.5 s; if writes keep failing (controller wedged by another tool), the daemon does not exit: it backs off exponentially (5 s → 60 s cap) while still monitoring temperatures and returns to control automatically when writes recover
  • smart stop waits for cleanup — returns only after the daemon has restored auto and cleared its pidfile, so the caller's immediately following set is not overridden; reports failure honestly on timeout. The pid in the pidfile is verified via proc_pidpath before signaling — a recycled pid is never killed
  • SMC read failures reopen the connection and retry 3 times (the connection can be briefly invalid right after wake)

Thermostat mode

The closed-loop counterpart to Smart mode (an open-loop curve): give it a target temperature and a PI controller holds the hottest sensor there.

  • Velocity-form PI: ΔRPM = 25×Δerror + 8×error − 150×temperature trend (per second), increment clamped to ±250 rpm — no integral windup, the trend term damps overshoot
  • Power feedforward (v1.8.2): same source as Smart mode — on a load ramp the fans are pushed up first and the PI follows gently, less overshoot. The boost is added to the output, not into the PI's accumulated state, so its decay never leaves an integration residue. Logs use the same ff+ format, so one set of grep statistics works for both daemons
  • Dead band: holds RPM while |error| < 0.3°C and the temperature is steady
  • Hands back to the system 3°C below target (fans may stop), retakes within 1.5°C (hysteresis)
  • Fully mutually exclusive with Smart mode: starting either takes over the other's control first
  • State pidfile /tmp/fansctl.hold.pid = pid target°C; hold stop waits for cleanup; log /tmp/fansctl.hold.log; wake handoff and MODE_REASSERT identical to Smart mode

Power survey

fansctl power prints the full power picture in one shot (read-only, no root needed):

  • System power — SMC key PSTR (second-level real-time, same source as the menu bar's first row); the charging component is split out while charging
  • Power input — AppleSmartBattery telemetry SystemVoltageIn × SystemCurrentIn: the actual power entering the port. This telemetry refreshes roughly once a minute; trust PSTR for short-term dynamics
  • Adapter — rated watts and PD-negotiated voltage from AdapterDetails
  • USB devices — each device's declared 5V current draw (IOUSBLib reads bMaxPower from the config descriptor; USB2 units are 2 mA, USB3+ are 8 mA); self-powered devices are marked
  • Top power processes — sorted by instantaneous CPU% (two samples 0.4 s apart), plus average% since launch (cumulative ÷ lifetime — a statistical value immune to short-task spikes), cumulative CPU time, memory/%MEM/PID. High now + low average = a transient spike (thumbnail/window rendering); both high = a real drain. macOS limitation: an unprivileged process can only read its own user's processes (system processes like WindowServer need sudo fansctl power); per-process GPU usage has no public API

Limitations: macOS exposes no public API for the actual power drawn by peripherals or for PD negotiation toward them; the USB side only has declared values (for ground truth, use an external power meter).

Passwordless control & security model

/usr/local/bin/fansctl-root (root:wheel 4755) is a copy of this binary; the menu bar runs privileged actions through it without a password. Whitelist only: __apply max|auto|set, __smart lo hi | stop | thresh, __hold °C | stop | target, smart stop. Every argument is range-checked; there is no shell and no environment expansion — the helper cannot be used as a generic privilege-escalation vector. If the helper is not installed, the menu bar falls back to an __ask subprocess using AuthorizationExecuteWithPrivileges (a password prompt each time).

Launch at login

One command, no sudo, no hand-editing (points the LaunchAgent at the actual binary path, handles reload):

fansctl bar install      # install + start now + start at login
fansctl bar status       # installed? loaded? running?
fansctl bar uninstall    # stop and remove

RunAtLoad + automatic restart on crash (SuccessfulExit=false); quitting from the menu does not respawn it.

Boot-time safety net (make install-restore, one password): the system-level LaunchDaemon /Library/LaunchDaemons/local.fansctl.restore.plist runs fansctl-root __apply auto once as root at every boot — if the SMC was left in manual mode after a crash or power loss, fans are restored to auto immediately instead of being stuck at their last RPM.

Known SMC facts (MacBook Pro 16" M1 Max, macOS 15)

  • SMCKeyData must be 80 bytes (Apple Silicon), selector 2
  • FNum=2; Mn=1200, Mx=5779/6241; mode keys F0md/F1md (ui8, 1=manual), target keys F0Tg/F1Tg (flt = f32 little-endian)
  • No Ftst and no FS! key — no unlock procedure needed
  • On Apple Silicon, fans can stop completely when cold: Ac/Tg = 0 is a real state, not a bug

License

AGPL-3.0-or-later (see LICENSE). Anyone may freely use, modify and redistribute this project; products based on it (including deployments as network services that distribute no binaries) must open-source their derivative code under AGPL-3.0. Commercial use is allowed; closed-source commercial use violates the license — if you use it in a commercial product, the author would appreciate hearing from you.

Acknowledgements

Three mechanisms were inspired by TomEageer/fanctl (a Python implementation, MIT-licensed), independently re-implemented in C here:

  • Boot-time restore (LaunchDaemon)
  • Robustness: wake handoff / mode reassert (MODE_REASSERT) / write backoff
  • Thermostat mode: PI closed loop on a target temperature (with trend damping)

Thanks to the original author for open-sourcing their work.

About

macOS fan control & power survey for Apple Silicon — one dependency-free binary: menu bar app + CLI, smart curve & PI thermostat. 单二进制:菜单栏+CLI,风扇温控与功耗一览

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages