Skip to content

Report only the batteries present on FreeBSD and DragonFly BSD - #3797

Merged
dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:bsd-power-source
Oct 13, 2026
Merged

dbwiddis merged 1 commit into
oshi:masterfrom
dbwiddis:bsd-power-source

Conversation

@dbwiddis

@dbwiddis dbwiddis commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Fixes getPowerSources() on FreeBSD and DragonFly BSD, which share FreeBsdPowerSource. Found in the ground-truth surveys on cfarm430 (FreeBSD 16-CURRENT) and cfarm152 (DragonFly 6.4): both are VMs with no battery, and both reported a full BAT0 that was not on line power.

No battery, no entry; one entry per battery

  • The kernel creates the hw.acpi.battery sysctls only when a battery driver attaches (acpi_battery_register → acpi_battery_init), so a missing or zero hw.acpi.battery.units now returns an empty list.
  • Each battery is read with acpiconf -i N and named BAT0, BAT1, …; a bay reported as not present is skipped. Previously only BAT0 was ever reported.
  • The hw.acpi.battery.{state,time,life} values are totals across all batteries, so they fill in for acpiconf only when there is a single battery (e.g. when acpiconf cannot open /dev/acpi).

Units and missing fields

  • getVoltage() was mV; it is now V, as documented.
  • getAmperage() was mW / mV, i.e. A; it is now mA. For a battery reporting in mA, acpiconf prints N mA (M mW), whose mA figure was read as mW; both are now read from it.
  • getPowerUsageRate() and getAmperage() are negative while discharging, as documented.
  • isPowerOnLine() now reads hw.acpi.acline (it was always false); cycle count is read from acpiconf; current capacity is the remaining percentage of the last full capacity, since acpiconf prints the remaining charge only as a percentage.

The parser follows the printf formats in acpi_battinfo() in FreeBSD's usr.sbin/acpi/acpiconf/acpiconf.c. DragonFly's acpiconf prints the same labels and rate format, without Cycle Count, which is optional here.

Testing

  • Fixture tests: an mW battery discharging, an mA battery charging, a not present bay, acpiconf failing with the sysctl totals as fallback, and no battery.
  • cfarm430 (FreeBSD 16-CURRENT) and cfarm152 (DragonFly 6.4), JDK 25: JNA and FFM reports now list no power source.
  • macOS: full gate and -Perror-prone green.
  • Not verified on real battery hardware: neither box has a battery, so the battery fields are covered by the fixture tests only.

A battery-less machine still logs one WARN per call, for the missing hw.acpi.battery.units sysctl (down from three).

Summary by CodeRabbit

  • Bug Fixes
    • Improved battery reporting on FreeBSD and DragonFly BSD: systems no longer show a phantom battery when none is present, and multiple batteries are detected.
    • Corrected reported voltage, current, and power usage, including negative values while discharging.
    • Added or improved reporting for online status, current capacity, and battery cycle count.

FreeBsdPowerSource always returned one battery named BAT0, so a machine
with no battery, including every VM, reported a full battery that was
not on line power, and a machine with two reported one.

The kernel creates the hw.acpi.battery sysctls only when a battery
driver attaches, so a missing or zero hw.acpi.battery.units now means
no power sources. Each battery is read with acpiconf -i N, skipping
any reported as not present. The hw.acpi.battery values are totals
across all batteries, so they fill in for acpiconf only when there is
a single battery.

Also fixes the units: voltage was reported in mV instead of V, and
amperage as mW / mV, which is A rather than mA. A battery reporting in
mA prints "N mA (M mW)", whose mA figure was read as mW. Power usage
and amperage are now negative while discharging, as documented. Line
power (hw.acpi.acline), cycle count and current capacity, which were
never read, are now reported; acpiconf prints the remaining charge
only as a percentage, so current capacity is that share of the last
full capacity.

DragonFly BSD uses this class and its acpiconf prints the same labels,
without the cycle count.
@coderabbitai

coderabbitai Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 051d98ac-566c-4867-b32f-f6b91f082b16
📥 Commits

Reviewing files that changed from the base of the PR and between 486e68c and 4c387d3.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSource.java
  • oshi-common/src/test/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSourceTest.java
  • oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceFFM.java
  • oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceJNA.java

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

📜 Recent review details
⏰ Context from checks skipped due to timeout. (12)
  • GitHub Check: Test JDK 25, NetBSD
  • GitHub Check: Test JDK 25, FreeBSD
  • GitHub Check: Test JDK 25, OpenIndiana
  • GitHub Check: Test JDK 25, OpenBSD
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Test JDK 25, ubuntu-latest
  • GitHub Check: Error Prone
  • GitHub Check: Test JDK 25, windows-latest
  • GitHub Check: Test JDK 25, macos-latest
  • GitHub Check: Lint (ForbiddenAPIs, Javadoc, SLF4J)
  • GitHub Check: Lint (Spotless, Checkstyle)
  • GitHub Check: Analyze (java)
🧰 Additional context used
📚 Code guidelines (2)
AGENTS.md — auto-discovered
CONTRIBUTING.md — auto-discovered
📓 Path-based instructions (3)
Source excerpt: **Banned APIs** (`config/forbidden-apis.txt` and friends, enforced by `forbiddenapis:check`): `oshi-core-ffm` may not reference `com.sun.jna.**`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceFFM.java
Source excerpt: **Banned APIs** (`config/forbidden-apis.txt` and friends, enforced by `forbiddenapis:check`): `oshi-common` may not reference `com.sun.jna.**`, `java.lang.foreign.**`, or any `System.load`/`loadLibrary`.

📄 CodeRabbit inference engine (AGENTS.md)

Files:

  • oshi-common/src/test/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSourceTest.java
  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSource.java
Source excerpt: The Changelog lets users know what's changed.

📄 CodeRabbit inference engine (CONTRIBUTING.md)

Files:

  • CHANGELOG.md
🧠 Learnings (1)
📚 Learning: 2026-08-15T15:43:29.296Z
Learnt from: dbwiddis
Repo: oshi/oshi PR: 3628
File: oshi-core-ffm/src/main/java/oshi/driver/windows/registry/HkeyUserDataFFM.java:108-108
Timestamp: 2026-08-15T15:43:29.296Z
Learning: In the OSHI Java codebase, use the sentinel-over-null convention at public API boundaries. Private helpers may return an explicitly JSpecify-annotated nullable value when the caller handles the missing result clearly and locally; callers must check for null before accessing the result. For example, methods such as lookupAccountBySid(String) may return String Nullable [] when queryUserSessions() performs the required null check.

Applied to files:

  • oshi-common/src/main/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSource.java
🔇 Additional comments (6)
oshi-common/src/main/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSource.java (2)

178-187: Report "critical" or idle states without forcing them to charging or discharging.

acpiconf can print a combined state such as "discharging critical" or a bare "critical". The contains checks handle the combined case correctly. A bare "critical" state sets both flags to false, and that result is acceptable. A state of "high" also sets both flags to false. No change is required here.

249-260: Read maxCapacity from Last full capacity even when Design capacity is missing.

The capacity units come only from Design capacity. Some firmware reports Design capacity: unknown, and the parser drops that line. In that case, a valid Last full capacity in mWh or mAh is ignored. maxCapacity then stays 1 and the units stay RELATIVE. The battery still reports a percentage, so the impact is limited.

oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceJNA.java (1)

46-46: LGTM!

oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceFFM.java (1)

46-46: LGTM!

oshi-common/src/test/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSourceTest.java (1)

1-180: LGTM!

CHANGELOG.md (1)

11-11: LGTM!

📝 Walkthrough

Walkthrough

FreeBSD power-source queries now enumerate reported battery units and parse battery state and metrics. The JNA and FFM adapters use the updated query. Tests cover charging, discharging, absent batteries, sysctl fallbacks, and missing battery-unit configuration.

Changes

FreeBSD battery reporting

Layer / File(s) Summary
Battery discovery and parsing
oshi-common/src/main/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSource.java
The common implementation queries each reported battery unit and returns an unmodifiable list. Parsing omits absent batteries, uses sysctl values as fallbacks, interprets charging and discharging state, and reports signed rates while discharging.
Adapter integration and parser tests
oshi-core/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceJNA.java, oshi-core-ffm/src/main/java/oshi/hardware/platform/unix/freebsd/FreeBsdPowerSourceFFM.java, oshi-common/src/test/java/oshi/hardware/common/platform/unix/freebsd/FreeBsdPowerSourceTest.java, CHANGELOG.md
The JNA and FFM adapters call queryBatteries. Tests cover charging and discharging fixtures, absent batteries, sysctl fallback values, and missing battery-unit configuration. The changelog records the FreeBSD and DragonFly BSD battery-reporting changes.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant FreeBsdPowerSourceJNA
  participant queryBatteries
  participant sysctlInt
  participant acpiconf
  participant parseBattery
  participant PowerSourceFactory
  FreeBsdPowerSourceJNA->>queryBatteries: Request power sources
  queryBatteries->>sysctlInt: Read battery count and status values
  queryBatteries->>acpiconf: Query each battery unit
  acpiconf-->>queryBatteries: Return unit output
  queryBatteries->>parseBattery: Parse output with AC-line and sysctl values
  parseBattery->>PowerSourceFactory: Construct a present battery
  parseBattery-->>queryBatteries: Return battery or null
  queryBatteries-->>FreeBsdPowerSourceJNA: Return an unmodifiable list
Loading

Merge Risk: ⚪ Minimal · up to 4c387

The reviewed battery-reporting changes have no identified issue requiring a fix before merge. Real battery hardware was not available for validation.

Pre-merge checks · Passed 4 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks (4 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: reporting only batteries that are present on FreeBSD and DragonFly BSD.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 38.46% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 13 functions across 4 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks each battery’s glow
And counts the units in a row
It marks the charge and power’s flow
When currents drain, their signs show
Then bounds away through volts of snow

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

@dbwiddis
dbwiddis merged commit c27a750 into oshi:master Oct 13, 2026
17 of 18 checks passed
@dbwiddis
dbwiddis deleted the bsd-power-source branch October 13, 2026 00:54
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