Linux Implementation (sysfs)
Relevant source files
The following files were used as context for generating this wiki page:
The Linux implementation of the battery crate relies on the sysfs virtual filesystem, specifically the interface provided by the kernel under /sys/class/power_supply/. This module parses device attributes presented as files to provide standardized battery information such as state of charge, energy rates, and health metrics.
The implementation is designed to handle various kernel driver inconsistencies, legacy file naming conventions, and edge cases where certain data points might be missing or reported in different units (e.g., Energy in µWh vs. Charge in µAh).
Architecture Overview
The Linux implementation is structured into three primary layers: the filesystem abstraction, the data builder, and the device representation.
- Filesystem Layer (
fs.rs): Provides low-level utilities to read and parse specificsysfsfiles, converting raw string data into typed SI units. - Data Collection Layer (
source.rs): Implements aDataBuilderthat usesLazyCellto lazily fetch and calculate battery metrics, handling fallbacks between differentsysfsattributes. - Device Layer (
device.rs): Implements theBatteryDevicetrait, serving as the high-level interface for users to interact with a specific Linux battery device.
Component Relationship
The following diagram illustrates how these components interact to transform sysfs file data into a SysFsDevice.
Data Collection and Normalization
Data collection is managed by the DataBuilder struct. It is responsible for the "heavy lifting" of normalization, such as calculating Energy (Joules) from Electric Charge (Ampere-hours) when the kernel does not provide energy files directly.
Energy and Power Calculations
The implementation prioritizes energy_now and energy_full files. If these are missing, it attempts to calculate energy by multiplying charge_now or charge_full with the design_voltage.
Logic Flow for Energy Retrieval
The following flowchart describes the fallback logic used by DataBuilder to determine the current energy value.
Key Data Structures
| Structure | Purpose | Source File |
|---|---|---|
InstantData | A snapshot of battery metrics at a specific point in time. | source.rs:16-29 |
DataBuilder | Handles the lazy fetching and cross-calculation of metrics. | source.rs:31-43 |
SysFsDevice | The primary implementation of the BatteryDevice trait for Linux. | device.rs:11-21 |
SysFs Attribute Mapping
The library maps specific Linux kernel sysfs attributes to internal types. The fs.rs module handles the conversion from micro-units (µV, µW, µAh, µWh) used by the kernel to the standard units used by the crate.
Attribute Table
| sysfs Filename | Unit in Kernel | Target Type | Conversion Function |
|---|---|---|---|
energy_now | µWh | Energy | fs::energy |
charge_now | µAh | ElectricCharge | fs::charge |
voltage_now | µV | ElectricPotential | fs::voltage |
power_now | µW | Power | fs::power |
temp | 0.1 °C | ThermodynamicTemperature | DataBuilder::temperature |
Sources: src/platform/linux/sysfs/fs.rs:16-70, src/platform/linux/sysfs/source.rs:219-224
Edge Case Handling
The Linux implementation includes several "hacks" and safety checks to handle non-compliant or buggy drivers:
- Invalid UTF-8/Empty Files: The
get_stringfunction usesfrom_utf8_lossyand trims trailing newlines. It also treatsENODEV(Error 19) as a missing file (None) because some drivers create files that cannot be read. - Cycle Count: A
cycle_countof0is treated asNone. This is because some drivers initialize this field to zero even for old batteries, making the data unreliable. - Power Rate Sanity: Power rates exceeding 100W or appearing as
0xffff(ACPI "Ones" value indicating unstable calculation) are normalized to0.0W.
Device Lifecycle
A SysFsDevice is initialized by validating that the sysfs path represents a "System" scope "Battery".
Sources: src/platform/linux/device.rs:35-72
Summary
The Linux implementation via sysfs provides a robust, unit-aware interface to system batteries. By abstracting the complexities of the /sys/class/power_supply interface—including fallback calculations for energy and extensive sanity checks for driver-specific quirks—it ensures that the rest of the crate can operate on reliable, normalized data.