Skip to content

Correct PowerSupply units on Linux - #3096

Merged
dbwiddis merged 7 commits into
oshi:masterfrom
benplotke:feature/master/linux-power-supply-unit-fix
Mar 26, 2026
Merged

dbwiddis merged 7 commits into
oshi:masterfrom
benplotke:feature/master/linux-power-supply-unit-fix

Conversation

@benplotke

@benplotke benplotke commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

I noticed the units for batteries on Linux were off. I found the incoming units from https://docs.kernel.org/power/power_supply_class.html and added the appropriate conversions to the units specified in the PowerSupply interface.

I checked no tests failed, but I did not add any new tests. Let me know if you want me to add a test or change anything.

Thanks for reviewing my PR!

Summary by CodeRabbit

  • Bug Fixes
    • Improved accuracy of Linux power-source readings via corrected unit conversions, scaling, sign semantics, and fallback computations.
    • Adjusted Mac power-source charging/discharging logic to produce more accurate status reporting.
  • Improvements
    • Better handling of alternative sensor data and remaining-time selection between charge/discharge.
    • Safer parsing behavior for numeric, duration, and UUID inputs when values are missing.
  • Tests
    • Added Linux-focused tests validating parsing, units, sign conventions, fallbacks, and defaults.
  • Chores
    • Updated changelog and test JVM configuration for reflective access.

…ev to the output units specified in the PowerSource interface
@coderabbitai

coderabbitai Bot commented Mar 13, 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: 95b8be21-af63-437e-ab7d-b83900adca6f

📥 Commits

Reviewing files that changed from the base of the PR and between 25c4d73 and 75a0044.

📒 Files selected for processing (3)
  • oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
  • oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
🚧 Files skipped from review as they are similar to previous changes (1)
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.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). (7)
  • GitHub Check: Test JDK 21, macos-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Test JDK 11, macos-latest
  • GitHub Check: Test JDK 11, windows-latest
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Analyze (java)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (3)
oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java (1)

153-153: LGTM! Correct fix for discharging state logic.

The previous logic !psCharging would incorrectly report psDischarging = true when the device is plugged in but not actively charging (e.g., battery at 100% capacity). The new condition correctly identifies discharging only when both not charging AND not connected to external power.

oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java (2)

269-269: Clarify: Was removing the degree symbol intentional?

The temperature unit changed from "°C" to "C", dropping the degree symbol. The degree symbol is the standard notation for temperature. Was this change intentional (e.g., for ASCII compatibility or encoding issues), or was it accidental?

If intentional, consider documenting the rationale. If accidental, restore the degree symbol:

🔧 Suggested fix to restore degree symbol
-            sb.append(getTemperature()).append("C");
+            sb.append(getTemperature()).append("°C");

221-234: LGTM!

The switch case formatting changes are style-only adjustments with no logic changes. The platform dispatching remains correct.


📝 Walkthrough

Walkthrough

Introduces typed Linux power-supply property handling (Prop enum) and a buildPowerSource constructor, refactors parsing/scaling for energy/charge/voltage/current/power (including sign semantics and remaining-time logic), adds tests, tightens ParseUtil null handling, updates module test JVM opens, changelog, and copyright years.

Changes

Cohort / File(s) Summary
Linux Power Source Core
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java
Added nested Prop enum and buildPowerSource(String, Map<Prop,String>); replaced string-literal/uevent lookups with typed Map<Prop,String>; refactored per-device construction; changed parsing/scaling for energy/charge (micro-units → MWH/MAH), voltage (/1_000_000), power/current (/1_000) with P=IV fallback; negates values when discharging; remaining-time uses TIME_TO_FULL_NOW when charging; removed old helper; copyright year bumped.
Parsing Utilities
oshi-core/src/main/java/oshi/util/ParseUtil.java
parse*OrDefault methods now return provided default on null or parse exceptions; parseDHMSOrDefault and parseUuidOrDefault short-circuit on null input.
Linux PowerSource Tests
oshi-core/src/test/java/oshi/hardware/platform/linux/LinuxPowerSourceTest.java
New Linux-only JUnit tests using synthesized property maps verifying name/model/chemistry/manufacturer, unit selection (ENERGY_* → MWH, CHARGE_* → MAH), numeric scaling and sign conventions, P=IV fallback precedence, temperature/manufacture parsing, remaining-time selection, and name fallback.
ParseUtil Tests
oshi-core/src/test/java/oshi/util/ParseUtilTest.java
Added assertions that parse*OrDefault methods return the provided default for null inputs.
Module Test JVM Opens
oshi-core-java11/src/test/java/module-info.test, oshi-core-java25/src/test/java/module-info.test
Added --add-opens for com.github.oshi/oshi.hardware.platform.linux to allow reflective access to org.junit.platform.commons during tests.
Changelog
CHANGELOG.md
Added bullet under 6.11.0 (in progress) noting Linux PowerSupply unit correction (PR #3087).
Minor Formatting/Logic
oshi-core/src/main/java/oshi/hardware/common/AbstractPowerSource.java, oshi-core/src/main/java/oshi/hardware/platform/mac/MacPowerSource.java
Small toString temperature formatting change and discharging logic adjustment; copyright year updates.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hopped through props and units tonight,
Micro values scaled to volts and light,
I flipped a sign when batteries drained,
Built tests to prove each value framed.
Hop, parse, convert — the power feels right!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.67% 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 title accurately reflects the main objective of the changeset: correcting power supply unit conversions on Linux, which is the primary focus across LinuxPowerSource.java and related test updates.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
✨ Simplify code
  • Create PR with simplified code

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.

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java (1)

236-252: ⚠️ Potential issue | 🔴 Critical

Power/current reconciliation zeros valid telemetry.

At Line 250 and Line 251, the else branch clears both values when both are present (or both were already parsed), which drops valid measurements. This should only default to zero when neither signal is available.

💡 Proposed fix
-                        if (psMap.containsKey("POWER_SUPPLY_POWER_NOW")) {
-                            psPowerUsageRate = ParseUtil.parseDoubleOrDefault(psMap.get("POWER_SUPPLY_POWER_NOW"), -1)
-                                    / 1000d;
-                        }
-
-                        if (psMap.containsKey("POWER_SUPPLY_CURRENT_NOW")) {
-                            psAmperage = ParseUtil.parseDoubleOrDefault(psMap.get("POWER_SUPPLY_CURRENT_NOW"), -1)
-                                    / 1000d;
-                        }
-
-                        if (psPowerUsageRate < 0 && psAmperage >= 0) {
-                            psPowerUsageRate = psAmperage * psVoltage;
-                        } else if (psPowerUsageRate >= 0 && psAmperage < 0) {
-                            psAmperage = psPowerUsageRate / psVoltage;
-                        } else {
-                            psAmperage = 0;
-                            psPowerUsageRate = 0;
-                        }
+                        double powerNow = psMap.containsKey("POWER_SUPPLY_POWER_NOW")
+                                ? ParseUtil.parseDoubleOrDefault(psMap.get("POWER_SUPPLY_POWER_NOW"), -1) / 1000d
+                                : -1d;
+                        double currentNow = psMap.containsKey("POWER_SUPPLY_CURRENT_NOW")
+                                ? ParseUtil.parseDoubleOrDefault(psMap.get("POWER_SUPPLY_CURRENT_NOW"), -1) / 1000d
+                                : -1d;
+
+                        if (powerNow >= 0 && currentNow >= 0) {
+                            psPowerUsageRate = powerNow;
+                            psAmperage = currentNow;
+                        } else if (powerNow >= 0) {
+                            psPowerUsageRate = powerNow;
+                            psAmperage = psPowerUsageRate / psVoltage;
+                        } else if (currentNow >= 0) {
+                            psAmperage = currentNow;
+                            psPowerUsageRate = psAmperage * psVoltage;
+                        } else {
+                            psAmperage = 0;
+                            psPowerUsageRate = 0;
+                        }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java`
around lines 236 - 252, The reconciliation logic in LinuxPowerSource that parses
psVoltage, psPowerUsageRate and psAmperage currently zeros both values in the
final else branch even when valid measurements exist; update the conditional
after parsing so that you only default psAmperage = 0 and psPowerUsageRate = 0
when both parsed values are unavailable (e.g., psPowerUsageRate < 0 &&
psAmperage < 0); otherwise, if one is missing compute it from the other
(psPowerUsageRate = psAmperage * psVoltage or psAmperage = psPowerUsageRate /
psVoltage) and leave existing parsed values intact. Ensure you modify the block
referencing psVoltage, psPowerUsageRate and psAmperage in the LinuxPowerSource
class to implement this fix.
🤖 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/linux/LinuxPowerSource.java`:
- Around line 216-227: In LinuxPowerSource, the non-udev parsing mistakenly
assigns POWER_SUPPLY_ENERGY_FULL / _CHARGE_FULL to psCurrentCapacity and
POWER_SUPPLY_ENERGY_FULL_DESIGN / _CHARGE_FULL_DESIGN to psMaxCapacity,
overwriting current and leaving psDesignCapacity wrong; update the assignment so
that POWER_SUPPLY_ENERGY_FULL and POWER_SUPPLY_CHARGE_FULL set psMaxCapacity (or
psCurrentCapacity depending on the intended semantics—use psMaxCapacity for
"full" real capacity) and POWER_SUPPLY_ENERGY_FULL_DESIGN and
POWER_SUPPLY_CHARGE_FULL_DESIGN set psDesignCapacity, ensuring psCurrentCapacity
is set from the correct "remaining" keys (e.g., ENERGY_NOW/CHARGE_NOW) as used
elsewhere in LinuxPowerSource to match udev logic.
- Around line 104-125: The fallback checks are performed after scaling the
parsed values which can turn the -1 sentinel into 0 and skip fallbacks; in
LinuxPowerSource change the logic to first parse raw ints into temporaries using
ParseUtil.parseIntOrDefault(..., -1) (e.g., rawNow, rawFull, rawDesign), test
each raw value for < 0 to decide whether to fall back to the corresponding
CHARGE_* property (and set CapacityUnits when appropriate), and only after
selecting the correct raw value divide by 1000 to assign psCurrentCapacity,
psMaxCapacity, and psDesignCapacity; update uses of device.getPropertyValue and
ParseUtil.parseIntOrDefault accordingly so the fallback behavior works as
intended.

---

Outside diff comments:
In `@oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java`:
- Around line 236-252: The reconciliation logic in LinuxPowerSource that parses
psVoltage, psPowerUsageRate and psAmperage currently zeros both values in the
final else branch even when valid measurements exist; update the conditional
after parsing so that you only default psAmperage = 0 and psPowerUsageRate = 0
when both parsed values are unavailable (e.g., psPowerUsageRate < 0 &&
psAmperage < 0); otherwise, if one is missing compute it from the other
(psPowerUsageRate = psAmperage * psVoltage or psAmperage = psPowerUsageRate /
psVoltage) and leave existing parsed values intact. Ensure you modify the block
referencing psVoltage, psPowerUsageRate and psAmperage in the LinuxPowerSource
class to implement this fix.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6994c12b-73ad-48f8-b1c5-c37cc1361688

📥 Commits

Reviewing files that changed from the base of the PR and between f0d52f2 and 30ff9ea.

📒 Files selected for processing (1)
  • oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.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). (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (2)
oshi-core/src/main/java/oshi/hardware/platform/linux/LinuxPowerSource.java (2)

129-143: Unit normalization here matches the PowerSource contract.

Line 129/Line 130 converts VOLTAGE_NOW from µV to V, and Lines 136/139/142/143 convert current/power from µ-units to milli-units consistently with oshi-core/src/main/java/oshi/hardware/PowerSource.java:91-102.


207-213: Good ENERGY_NOW/CHARGE_NOW scaling and unit tagging in non-udev path.

Line 207-213 correctly normalizes to milli-units and updates CapacityUnits according to source field type.

@codecov

codecov Bot commented Mar 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.22%. Comparing base (f0d52f2) to head (75a0044).
⚠️ Report is 4 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #3096      +/-   ##
==========================================
- Coverage   69.49%   69.22%   -0.27%     
==========================================
  Files          35       36       +1     
  Lines        1839     1875      +36     
  Branches      297      305       +8     
==========================================
+ Hits         1278     1298      +20     
- Misses        461      478      +17     
+ Partials      100       99       -1     

☔ 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.

@dbwiddis dbwiddis left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hey @benplotke thanks for this PR!

This was one of the first classes I wrote a decade ago (yay copyright tombstones) and I'm surprised it took ten years to find this bug! (Technically I left the units "relative" so it wasn't actually a bug, but assigning the correct units is helpful).

There are a few problems with your fix (see below) and some pre-existing bugs we should fix while we're at it.

Also, can you create a changelog entry for this PR?

@dbwiddis

Copy link
Copy Markdown
Member

Also seems TEMP is a valid key (tenths of degrees celsius) that we never read/assign. Would be nice to add that.

@benplotke

Copy link
Copy Markdown
Contributor Author

Hi @dbwiddis, thanks for all the feedback. I am working on the changes you recommended, but I got bogged down trying to setup different platforms to see it working. I hopefully will push the updates tonight.

@dbwiddis

Copy link
Copy Markdown
Member

No worries. Take your time and thanks again for contributing!

@dbwiddis
dbwiddis merged commit 1c083b1 into oshi:master Mar 26, 2026
12 checks passed
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.

2 participants