Introduction to rust-battery
Relevant source files
The following files were used as context for generating this wiki page:
rust-battery is a cross-platform Rust crate designed to provide unified access to notebook battery information. Its primary purpose is to abstract away OS-specific interfaces (such as Linux Sysfs, macOS IOKit, or Windows IOCTL) and provide a consistent, type-safe API. All measurements retrieved from the underlying system are recalculated into SI measurement units using the uom crate.
Sources: README.md:21-25, src/lib.rs:1-5
The library supports a wide range of operating systems, including Linux (2.6.39+), macOS (10.10+), Windows (7+), FreeBSD, DragonFlyBSD, and NetBSD. It is utilized by high-profile projects like the starship prompt to display battery levels and status directly in the shell.
Sources: README.md:27-36, README.md:65-70
Architecture Overview
The architecture of rust-battery relies on a clear separation between a high-level public API and platform-specific implementations governed by a set of traits.
Core Components
The system is structured around three main entities:
- Manager: The entry point for the library, responsible for discovering batteries and managing their lifecycle.
- Batteries Iterator: A wrapper around platform-specific iterators that yields
Batteryobjects. - Battery: Represents an individual battery device, providing methods to query its state, energy levels, and hardware metadata.
Sources: src/types/manager.rs:25-33, src/types/mod.rs:1-12
Platform Abstraction Layer
To support multiple operating systems, rust-battery defines several internal traits that platform-specific modules must implement. These traits ensure that regardless of the backend (e.g., SysFsDevice on Linux or PowerDevice on Windows), the high-level Battery type behaves consistently.
The diagram above illustrates the relationship between the internal traits used to abstract hardware access.
Sources: src/platform/traits.rs:13-39
Data Flow and Refresh Logic
Information retrieval follows a "pull" model where data is preloaded during iteration or explicitly updated.
- Initialization: A
Manageris created, which initializes the underlying platform-specific manager. - Discovery: Calling
manager.batteries()returns an iterator. On many platforms, the iterator preloads the current battery state to ensure that subsequent method calls on theBatteryobject are infallible. - Updating: To get the most recent values (e.g., current charge or energy rate), the
manager.refresh(&mut battery)method must be called. This triggers a platform-specific update, such as re-reading files in/sys/class/power_supply/on Linux.
Sources: src/types/manager.rs:36-58, src/platform/linux/device.rs:56-74, src/platform/traits.rs:37-39
This sequence shows how a user interacts with the Manager to retrieve and update battery data.
Sources: examples/simple.rs:10-25, src/types/manager.rs:55-58
Battery Specifications and Measurements
The Battery type provides a comprehensive set of methods to query battery metrics. All numerical values use the uom crate for type-safe SI units.
| Feature | Method | Unit/Type | Description |
|---|---|---|---|
| State | state() | State | Charging, Discharging, Full, Empty, or Unknown. |
| Charge | state_of_charge() | Ratio | The current charge level (0.0 to 1.0). |
| Health | state_of_health() | Ratio | Percentage of design capacity currently available. |
| Energy | energy() | Energy | Current energy in the battery. |
| Rate | energy_rate() | Power | Current power consumption or charging rate. |
| Voltage | voltage() | ElectricPotential | Current battery voltage. |
| Time | time_to_full() | Option<Time> | Estimated time until fully charged. |
Sources: src/platform/traits.rs:42-132, src/types/state.rs
Technology Types
The Technology enum identifies the chemical composition of the battery, parsed from various platform-specific strings (e.g., "Li-ion", "Pb", "NiMH").
pub enum Technology {
Unknown,
LithiumIon,
LeadAcid,
LithiumPolymer,
NickelMetalHydride,
NickelCadmium,
NickelZinc,
LithiumIronPhosphate,
RechargeableAlkalineManganese,
}
Sources: src/types/technology.rs:9-21
Platform Implementations
Each supported platform implements the BatteryDevice trait to handle specific hardware communication:
- Linux: Uses the
sysfsinterface. It reads files under/sys/class/power_supply/, handling variants likeenergy_nowvscharge_now. - Windows: Uses
DeviceIoControlwithIOCTL_BATTERY_QUERY_INFORMATIONandIOCTL_BATTERY_QUERY_STATUSto fetch battery tags and data. - macOS: Uses the
IOKitframework, specifically queryingAppleSmartBatteryorIORPMPowerSourceobjects. - NetBSD: Uses the
envsys(4)framework viaioctland parsesplistdata.
Sources: src/platform/linux/device.rs:20-54, src/platform/windows/device.rs:50-70, src/platform/netbsd/device.rs:34-90, src/platform/darwin/iokit/power_source.rs:50-100
Conclusion
rust-battery provides a robust, standardized interface for battery monitoring across nearly all major desktop and server operating systems. By abstracting complex kernel-level interfaces into a simple Manager and Battery API with SI-compliant types, it enables developers to build energy-aware applications without worrying about platform-specific implementation details.