Skip to content

Add Apple Silicon SMC sensor support - #3091

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:smc-update
Mar 12, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:smc-update

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Mar 12, 2026 •

Copy link
Copy Markdown
Member

Adds Apple Silicon (M-series) SMC key support for CPU temperature and voltage
sensors in SmcUtil and MacSensors, with probe-first fallback to Intel keys
for backward compatibility. Also fixes a null-pointer risk in MacSensors when
smcOpen() fails.

Phase 1 of #3090 (comment)


Changes

SmcUtil.java

  • Added SMC_KEYS_CPU_TEMP_AS — ordered array of Apple Silicon CPU die
    temperature keys (Tp09, Tp0T, Tp01, Tp05, Tp0D), derived from live
    SMC enumeration on Apple Silicon hardware
  • Added SMC_KEYS_GPU_TEMP_AS — ordered array of Apple Silicon GPU temperature
    keys (Tg05, Tg0D, Tg0f, Tg0j) for future use
  • Added SMC_KEY_CPU_VOLTAGE_AS — Apple Silicon CPU core voltage key (VP0C),
    type flt, already in volts (no scaling required)
  • Added smcGetFirstFloat(IOConnect conn, String... keys) — iterates a list of
    keys and returns the first value > 0, or 0 if all fail

MacSensors.java

  • queryCpuTemperature(): wrapped in try/finally with null-guard on
    connection; probes Apple Silicon keys first via smcGetFirstFloat, falls back
    to Intel TC0P
  • queryCpuVoltage(): wrapped in try/finally with null-guard on connection;
    probes Apple Silicon VP0C first (no /1000 scaling), falls back to Intel
    VC0C / 1000
  • queryFanSpeeds(): unchanged — FNum and F%dAc keys work correctly on
    both architectures; zero fan speeds on fanless Apple Silicon models are
    accurate
  • Replaced all SmcUtil.SMC_KEY_* qualified references with explicit static
    imports

Motivation

Apple Silicon Macs use entirely different SMC key namespaces from Intel Macs.
The existing code only knew Intel keys (TC0P, VC0C), causing CPU temperature
and voltage to report 0 on all M-series hardware. As Apple Silicon is now the
majority of active Mac hardware, AS keys are probed first with Intel keys as the
fallback.


Testing

Verified on Apple Silicon (M-series) hardware:

Metric Before After
CPU Temperature 0.0°C 65.8°C
Fan Speeds [0, 0] [0, 0]
CPU Voltage 0.0V 0.997V

Fan speeds correctly report [0, 0] on fanless Apple Silicon models. Intel
behaviour is unchanged — the Intel key paths are still exercised when AS keys
return 0.

Summary by CodeRabbit

  • New Features

    • Apple Silicon-specific sensor support added for CPU temperature and voltage.
    • New macOS utility to enumerate and display SMC keys and readable sensor values.
  • Bug Fixes

    • Improved error handling, null-safety, and resource cleanup for SMC sensor access.
    • Added fallback lookups to improve reliability of sensor readings across Mac hardware.

@coderabbitai

coderabbitai Bot commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 30b3fd91-cc54-4cf8-903d-146f6c1ccba1

📥 Commits

Reviewing files that changed from the base of the PR and between ccbe28e and 44d8436.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-demo/src/main/java/oshi/demo/SmcDump.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
📜 Recent review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 21, windows-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (9)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java (4)

14-19: LGTM!

Static imports are appropriate and improve code readability by eliminating the SmcUtil. prefix for frequently used constants.


31-45: LGTM!

The null-guard, try/finally resource management, and Apple Silicon-first probing with Intel fallback are correctly implemented. The condition temp <= 0d properly triggers the fallback since smcGetFirstFloat returns 0d when all keys fail.


48-65: LGTM!

The null-guard and try/finally resource management correctly address the previously flagged NPE risk. The approach of returning a zero-filled array when the connection fails provides graceful degradation, and the fan speed keys work on both Intel and Apple Silicon architectures.


68-84: LGTM!

The voltage retrieval correctly handles the different data formats between Apple Silicon (VP0C as flt in volts) and Intel (VC0C as FPE2 in millivolts requiring /1000 scaling). The inline comments documenting the data type differences are helpful for future maintainability.

oshi-demo/src/main/java/oshi/demo/SmcDump.java (4)

24-30: LGTM!

The utility class pattern with a private constructor and static methods is appropriate for this demo tool. The SMC_CMD_READ_INDEX = 8 constant is correctly defined for SMC key enumeration.


32-64: LGTM!

The main method implements proper resource management with try/finally. The filtering to F (fan), V (voltage), T (temperature) keys and non-zero values is an effective approach for discovering relevant sensor keys on Apple Silicon hardware.


66-86: LGTM!

The method correctly uses try-with-resources for proper native resource management. The SMC command structure (data8 = 8 for READ_INDEX, data32 = index) and key conversion from big-endian int to ASCII string follow the expected SMC protocol.


88-100: LGTM!

The helper method correctly handles null-terminated ASCII strings from the SMC data type field.

CHANGELOG.md (1)

11-11: LGTM!

The changelog entry accurately documents the Apple Silicon SMC sensor support addition and follows the established format for this file.


📝 Walkthrough

Walkthrough

Adds Apple Silicon SMC sensor support: new Apple Silicon SMC key constants and a multi-key float lookup in SmcUtil, MacSensors updated to prefer Apple Silicon keys with fallbacks and improved null/resource handling, plus a SmcDump demo and a CHANGELOG entry.

Changes

Cohort / File(s) Summary
SMC Utility
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
Adds Apple Silicon SMC key constants (SMC_KEYS_CPU_TEMP_AS, SMC_KEYS_GPU_TEMP_AS, SMC_KEY_CPU_VOLTAGE_AS) and smcGetFirstFloat(IOConnect, String... keys) to return the first positive float across multiple keys.
MacSensors (sensor reads & safety)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
Refactors CPU temperature, fan speed, and CPU voltage retrieval to prefer Apple Silicon keys with Intel fallbacks; adds null-connection guards and ensures SmcUtil.smcClose is called in finally blocks.
SMC Dump demo
oshi-demo/src/main/java/oshi/demo/SmcDump.java
New demo utility that opens an SMC connection, enumerates keys, reads values/types/sizes, filters and prints keys, and closes the connection; includes helpers readKeyAtIndex() and asciiType().
Changelog
CHANGELOG.md
Adds entry noting Apple Silicon SMC sensor support under Bug fixes / Improvements.

Sequence Diagram(s)

sequenceDiagram
    participant MacSensors
    participant SmcUtil
    participant SMC as "IOKit / SMC"
    MacSensors->>SmcUtil: smcOpen()
    SmcUtil->>SMC: open connection
    SmcUtil-->>MacSensors: IOConnect (or null)
    MacSensors->>SmcUtil: smcGetFirstFloat(conn, AS_keys..., Intel_key)
    SmcUtil->>SMC: smcReadKey / smcGetFloat (iterate keys)
    SMC-->>SmcUtil: float value (or 0)
    SmcUtil-->>MacSensors: first positive float (or 0)
    MacSensors->>SmcUtil: smcClose(conn)
    SmcUtil->>SMC: close connection
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🐰 I munched the SMC keys in moonlit code,
Found Silicon whispers where old signals flowed.
New keys, neat fallbacks, tidy close at last —
A rabbit's hop through metrics, fast and vast.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main change: adding Apple Silicon SMC sensor support. It is clear, concise, and directly reflects the primary objective of the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Mar 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.98%. Comparing base (4d8586d) to head (44d8436).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3091      +/-   ##
==========================================
+ Coverage   69.38%   69.98%   +0.59%     
==========================================
  Files          35       35              
  Lines        1839     1839              
  Branches      297      297              
==========================================
+ Hits         1276     1287      +11     
+ Misses        467      453      -14     
- Partials       96       99       +3     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)

59-62: Avoid exposing mutable key arrays as public constants.

public static final String[] is still caller-mutable, so external code can change the fallback order or corrupt these defaults for the entire process. Prefer private arrays plus cloning accessors, or an immutable collection type.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java` around lines 59
- 62, The public mutable arrays SMC_KEYS_CPU_TEMP_AS and SMC_KEYS_GPU_TEMP_AS
(and the exposed SMC_KEY_CPU_VOLTAGE_AS if you want consistency) must be made
non-mutable: change them to private (e.g., private static final String[]
SMC_KEYS_CPU_TEMP_AS and SMC_KEYS_GPU_TEMP_AS) and add public accessor methods
in SmcUtil like getSmcKeysCpuTempAs() / getSmcKeysGpuTempAs() that return a
defensive copy (clone) or return an unmodifiable List constructed from
List.of(...) to prevent callers from mutating the originals; keep the single
scalar SMC_KEY_CPU_VOLTAGE_AS as-is or provide a getter for consistency.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java`:
- Around line 48-59: queryFanSpeeds calls SmcUtil.smcOpen() which may return
null but then immediately passes conn into
SmcUtil.smcGetLong/smcGetFloat/smcClose causing NPEs; update queryFanSpeeds to
check if conn is null right after SmcUtil.smcOpen() and if so return a
zero-length int[] (or an array of zeros sized by this.numFans if you prefer),
otherwise proceed to call smcGetLong/smcGetFloat and only call
SmcUtil.smcClose(conn) when conn is non-null; reference the method
queryFanSpeeds and the SmcUtil methods smcOpen, smcGetLong, smcGetFloat, and
smcClose when making the change.

---

Nitpick comments:
In `@oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java`:
- Around line 59-62: The public mutable arrays SMC_KEYS_CPU_TEMP_AS and
SMC_KEYS_GPU_TEMP_AS (and the exposed SMC_KEY_CPU_VOLTAGE_AS if you want
consistency) must be made non-mutable: change them to private (e.g., private
static final String[] SMC_KEYS_CPU_TEMP_AS and SMC_KEYS_GPU_TEMP_AS) and add
public accessor methods in SmcUtil like getSmcKeysCpuTempAs() /
getSmcKeysGpuTempAs() that return a defensive copy (clone) or return an
unmodifiable List constructed from List.of(...) to prevent callers from mutating
the originals; keep the single scalar SMC_KEY_CPU_VOLTAGE_AS as-is or provide a
getter for consistency.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 5e72f0f5-478c-47fa-8d66-d0b16520b934

📥 Commits

Reviewing files that changed from the base of the PR and between 4d8586d and ccbe28e.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java
  • oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java
  • oshi-demo/src/main/java/oshi/demo/SmcDump.java
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 25, ubuntu-latest
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Analyze (java)
🔇 Additional comments (3)
oshi-core/src/main/java/oshi/util/platform/mac/SmcUtil.java (1)

135-149: Nice fallback helper extraction.

Centralizing the “first positive key wins” logic here keeps the Apple Silicon/Intel probe order in one place and avoids duplicating native-read branching in callers.

oshi-core/src/main/java/oshi/hardware/platform/mac/MacSensors.java (1)

31-44: The temperature and voltage paths are much safer now.

The early null return plus finally-based close handles both open failures and fallback branches without leaking the native connection.

Also applies to: 63-78

oshi-demo/src/main/java/oshi/demo/SmcDump.java (1)

33-63: Useful native-debugging demo.

The null-guarded open, finally close, and try-with-resources around the native structs make this safe enough for a diagnostic utility.

Also applies to: 66-85

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant