Rust-battery - Rust crate providing cross-platform information about the notebook batteries.

Overview

battery

Latest Version Latest Version Build Status Minimum rustc version Apache 2.0 OR MIT licensed Backers on Open Collective Sponsors on Open Collective

Rust crate providing cross-platform information about the notebook batteries.

Table of contents

Overview

battery provides a cross-platform unified API to a notebook batteries state.

Its main goal is to wrap the OS-specific interfaces, cover all the hacks and legacy cases and get the batteries information (such as state of charge, energy rate, voltage and temperature) as a typed values, recalculated as necessary to be returned as a SI measurement units.

Supported platforms

  • Linux 2.6.39+
  • MacOS 10.10+
  • iOS
  • Windows 7+
  • FreeBSD
  • DragonFlyBSD

Do note that iOS implementation uses IOKit bindings, your application might be automatically rejected by Apple based on that fact. Use it on your own risk.

Install

As a prerequisite, battery crate requires at least Rustc version 1.36 or greater.

Add the following line into a Cargo.toml:

[dependencies]
battery = "0.7.8"

Examples

fn main() -> Result<(), battery::Error> {
    let manager = battery::Manager::new()?;

    for (idx, maybe_battery) in manager.batteries()?.enumerate() {
        let battery = maybe_battery?;
        println!("Battery #{}:", idx);
        println!("Vendor: {:?}", battery.vendor());
        println!("Model: {:?}", battery.model());
        println!("State: {:?}", battery.state());
        println!("Time to full charge: {:?}", battery.time_to_full());
        println!("");
    }

    Ok(())
}

See the battery/examples/ folder in the repository for additional examples.

FFI bindings

Experimental battery-ffi crate provides the FFI bindings to the battery crate, so it can be used with other languages, such as C, Python or NodeJS.

Check its README and documentation for details.

Users

This an incomplete list of the battery crate users. If you are using it too, send me a message and I'll add your project here!

battop

battop is an interactive viewer, similar to top, htop and other *top utilities, but about the batteries installed in your notebook.
It is using the battery crate API to show the batteries information in your terminal.

starship

starship is a Rust port of the minimalistic, powerful, and extremely customizable prompt Spaceship ZSH.
It is using the battery crate to show the the current battery level and status in a shell prompt.

Here is what @matchai says:

I really appreciate how easily we were able to get your library up and running! Battery APIs were a headache for us in predecessors of this project 😅

And there is this tweet also!

License

Licensed under either of Apache License 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Donations

If you appreciate my work and want to support me, you can do it here or support this project at Open Collective.

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

Comments
  • Termux support

    Termux support

    error: Support for this target OS is not implemented yet!
     You may want to create an issue: https://github.com/svartalf/rust-battery/issues/new
      --> /home/builder/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.7.4/src/platform/mod.rs:27:9
       |
    27 | /         compile_error!("Support for this target OS is not implemented yet!\n \
    28 | |             You may want to create an issue: https://github.com/svartalf/rust-battery/issues/new");
       | |___________________________________________________________________________________________________^
    
    error[E0432]: unresolved import `crate::platform::Device`
     --> /home/builder/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.7.4/src/types/battery.rs:5:5
      |
    5 | use crate::platform::Device;
      |     ^^^^^^^^^^^^^^^^^^^^^^^ no `Device` in `platform`
    
    error[E0432]: unresolved import `crate::platform::Iterator`
     --> /home/builder/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.7.4/src/types/iterator.rs:3:5
      |
    3 | use crate::platform::Iterator as PlatformIterator;
      |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `Iterator` in `platform`
    
    error[E0432]: unresolved import `crate::platform::Iterator`
     --> /home/builder/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.7.4/src/types/manager.rs:5:5
      |
    5 | use crate::platform::Iterator as PlatformIterator;
      |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `Iterator` in `platform`
    
    error[E0432]: unresolved import `crate::platform::Manager`
     --> /home/builder/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.7.4/src/types/manager.rs:6:5
      |
    6 | use crate::platform::Manager as PlatformManager;
      |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ no `Manager` in `platform`
    
    opened by bbigras 14
  • About how to build and battery info scraping

    About how to build and battery info scraping

    Hey,

    I want to use this awesome project in polybar via shell script. But i can't figure it out how to compile cli or ffi. I installed battop via yay battop. It works perfectly.

    Actually, i couldn't see a installation guide or it could be a not-well documented. Simply,

    1. When i run this: cargo install battery-ffi

    Returns:

    Updating crates.io index
      Installing battery-ffi v0.7.0
    error: specified package has no binaries
    
    1. battop is not supporting output args like this:

    battop --time-to-empty

    It may be really really life saver.

    1. cargo build --release

    Returns:

    error: failed to resolve patches for `https://github.com/rust-lang/crates.io-index`
    
    Caused by:
      patch for `battery` in `https://github.com/rust-lang/crates.io-index` did not resolve to any crates. If this is unexpected, you may wish to consult: https://github.com/rust-lang/cargo/issues/4678
    

    The bare-minimum thing I want is looks like:

    $ battery-cli --time-to-empty

    Consequently, I want to write the battery's battery_get_time_to_empty output to the polybar. I am trying to figure it out how to write a script that scrapes about battery informations.

    opened by Dentrax 9
  • Overflow panic when pretty printing Battery struct.

    Overflow panic when pretty printing Battery struct.

    Setup:

    fn main() {
        let batteries = battery::Manager::new().iter().collect::<Vec<_>>();
        println!("{:#?}", batteries);
    }
    

    Error 😨:

    [
        Battery {
            vendor: Some(
                "SMP"
            ),
            model: Some(
                "bq20z451"
            ),
            serial_number: Some(
                "D866466Q2BPFWLKFQ"
            ),
            technology: Unknown,
            state: Full,
            capacity: 0.0,
            temperature: Some(
                30.11
    thread 'main' panicked at 'attempt to multiply with overflow', /Users/a/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.6.0/src/platform/macos/device.rs:128:10
    note: Run with `RUST_BACKTRACE=1` for a backtrace.
            )
    

    OS: macOS High Sierra 10.13.6 17G5019 x86_64 Host: MacBookPro11,4

    C-duplicate O-macos A-battery 
    opened by bddap 7
  • Mac OS version doesn't work correctly

    Mac OS version doesn't work correctly

    https://monosnap.com/file/wSyg3psLsM7m7EsdWBLYm2LcttjbIf compiled just fine but data a lot of error data.

    System Software Overview:
     System Version:	macOS 10.14.3 (18D39a)
      Kernel Version:	Darwin 18.2.0
      Boot Volume:	Macintosh HD
      Boot Mode:	Normal
    
    Hardware Overview:
      Model Name:	MacBook Pro
      Model Identifier:	MacBookPro13,2
      Processor Name:	Intel Core i5
      Processor Speed:	2,9 GHz
      Number of Processors:	1
      Total Number of Cores:	2
      L2 Cache (per Core):	256 KB
      L3 Cache:	4 MB
      Memory:	16 GB
    
    Battery Information:
    
      Model Information:
      Serial Number:	******
      Manufacturer:	SMP
      Device Name:	******
      Pack Lot Code:	0
      PCB Lot Code:	0
      Firmware Version:	901
      Hardware Revision:	1
      Cell Revision:	3922
      Charge Information:
      Charge Remaining (mAh):	4123
      Fully Charged:	Yes
      Charging:	No
      Full Charge Capacity (mAh):	4203
      Health Information:
      Cycle Count:	50
      Condition:	Normal
      Battery Installed:	Yes
      Amperage (mA):	-1037
      Voltage (mV):	12916
    
    System Power Settings:
      AC Power:
      System Sleep Timer (Minutes):	1
      Disk Sleep Timer (Minutes):	10
      Display Sleep Timer (Minutes):	10
      Wake on AC Change:	No
      Wake on Clamshell Open:	Yes
      Wake on LAN:	Yes
      AutoPowerOff Delay:	28800
      AutoPowerOff Enabled:	1
      DarkWakeBackgroundTasks:	1
      Display Sleep Uses Dim:	Yes
      GPUSwitch:	2
      Hibernate Mode:	3
      High Standby Delay:	86400
      PrioritizeNetworkReachabilityOverSleep:	0
      ProximityDarkWake:	1
      Standby Battery Threshold:	50
      Standby Delay:	10800
      Standby Enabled:	1
      TCPKeepAlivePref:	1
      Battery Power:
      System Sleep Timer (Minutes):	1
      Disk Sleep Timer (Minutes):	10
      Display Sleep Timer (Minutes):	2
      Wake on AC Change:	No
      Wake on Clamshell Open:	Yes
      AutoPowerOff Delay:	28800
      AutoPowerOff Enabled:	1
      Current Power Source:	Yes
      DarkWakeBackgroundTasks:	0
      Display Sleep Uses Dim:	Yes
      GPUSwitch:	2
      Hibernate Mode:	3
      High Standby Delay:	86400
      ProximityDarkWake:	0
      Reduce Brightness:	Yes
      Standby Battery Threshold:	50
      Standby Delay:	10800
      Standby Enabled:	1
      TCPKeepAlivePref:	1
    
    Hardware Configuration:
      UPS Installed:	No
    
    AC Charger Information:
      Connected:	No
      Charging:	No
    
    O-macos A-battery P-high 
    opened by non-descriptive 7
  • No license files on crates.io

    No license files on crates.io

    There LICENSE-APACHE and LICENSE-MIT files on github, but no license files on crates.io. Could you add them? This is mandatory for some Linux distros if we want to package rust-battery for official repos.

    opened by tim77 6
  • Update core-foundation requirement from 0.6.4 to 0.7.0

    Update core-foundation requirement from 0.6.4 to 0.7.0

    Updates the requirements on core-foundation to permit the latest version.

    Commits

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language
    • @dependabot badge me will comment on this PR with code to add a "Dependabot enabled" badge to your readme

    Additionally, you can set the following in your Dependabot dashboard:

    • Update frequency (including time of day and day of week)
    • Pull request limits (per update run and/or open at any time)
    • Out-of-range updates (receive only lockfile updates, if desired)
    • Security updates (receive only security updates, if desired)
    C-enhancement 
    opened by dependabot-preview[bot] 4
  • Handle missing energy_full_design value for Linux

    Handle missing energy_full_design value for Linux

    According to https://github.com/starship/starship/issues/613#issuecomment-548873632, there exist a possibility when both energy_full_design and charge_full_design files are missing for the battery device, so fetching fails with an error here: https://github.com/svartalf/rust-battery/blob/08b2ad579d135dbe48d52ff31a35df307c173eb6/battery/src/platform/linux/sysfs/source.rs#L183

    upower just falls back to 0.0 value, but that might affect state_of_health

    https://github.com/svartalf/rust-battery/blob/08b2ad579d135dbe48d52ff31a35df307c173eb6/battery/src/platform/linux/sysfs/source.rs#L137

    and energy parameters:

    https://github.com/svartalf/rust-battery/blob/08b2ad579d135dbe48d52ff31a35df307c173eb6/battery/src/platform/linux/sysfs/source.rs#L168

    C-bug O-linux A-battery P-high 
    opened by svartalf 4
  • Update mach requirement from 0.2.3 to 0.3.2

    Update mach requirement from 0.2.3 to 0.3.2

    Updates the requirements on mach to permit the latest version.

    Commits

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Note: This repo was added to Dependabot recently, so you'll receive a maximum of 5 PRs for your first few update runs. Once an update run creates fewer than 5 PRs we'll remove that limit.

    You can always request more updates by clicking Bump now in your Dependabot dashboard.

    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language
    • @dependabot badge me will comment on this PR with code to add a "Dependabot enabled" badge to your readme

    Additionally, you can set the following in your Dependabot dashboard:

    • Update frequency (including time of day and day of week)
    • Pull request limits (per update run and/or open at any time)
    • Out-of-range updates (receive only lockfile updates, if desired)
    • Security updates (receive only security updates, if desired)
    C-enhancement 
    opened by dependabot-preview[bot] 4
  • Fix overflow and change time to minutes on MacOS

    Fix overflow and change time to minutes on MacOS

    Amperage was returning negative values, so I changed it to read as an isize and then getting the absolute value from it.

    percentage() was also overflowing. I changed it to use the capacity values directly instead of going through the energy functions. The multiplication with voltage should cancel out either way.

    InstantTimeToEmpty is returning the time in minutes, at least on my system. I haven't gotten InstantTimeToFull to report anything yet, instead it's reporting both values through TimeRemaining. (I haven't looked into this, just mentioning it)

    I have only tested this on Mojave (10.14.3)

    opened by martinrlilja 4
  • Fix multiplication overflow for macos

    Fix multiplication overflow for macos

    The multiplication in percentage overflowed the u32 integer type before multiplication. Before, the operator precedence multiplied self.energy() by 100 which overflowed. The fix converts the energy and energy_full to floats and computes the ratio, before multiplying by 100 which prevents the overflow.

    opened by simonrw 3
  • Could not compile `battery`

    Could not compile `battery`

    When i run cargo build --release I am getting this:

    Compiling battery v0.6.0
       Compiling battery v0.6.0 (/home/dentrax/Projects/GitHub/rust-battery/battery)
       Compiling quote v0.6.11
       Compiling rand_chacha v0.1.1
       Compiling rand_pcg v0.1.2
       Compiling rand_os v0.1.2
       Compiling atty v0.2.11
       Compiling termion v1.5.1
    error[E0658]: imports can only refer to extern crate names passed with `--extern` on stable channel (see issue #53130)
      --> /home/dentrax/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.6.0/src/lib.rs:34:9
       |
    31 | mod types;
       | ---------- not an extern crate passed with `--extern`
    ...
    34 | pub use types::{Manager, Batteries, Battery, State, Technology};
       |         ^^^^^
       |
       = help: add #![feature(uniform_paths)] to the crate attributes to enable
    note: this import refers to the module defined here
      --> /home/dentrax/.cargo/registry/src/github.com-1ecc6299db9ec823/battery-0.6.0/src/lib.rs:31:1
       |
    31 | mod types;
       | ^^^^^^^^^^
    
    error[E0658]: imports can only refer to extern crate names passed with `--extern` on stable channel (see issue #53130)
      --> battery/src/lib.rs:34:9
       |
    31 | mod types;
       | ---------- not an extern crate passed with `--extern`
    ...
    34 | pub use types::{Manager, Batteries, Battery, State, Technology};
       |         ^^^^^
       |
       = help: add #![feature(uniform_paths)] to the crate attributes to enable
    note: this import refers to the module defined here
      --> battery/src/lib.rs:31:1
       |
    31 | mod types;
       | ^^^^^^^^^^
    
       Compiling clap v2.32.0
    error: aborting due to previous error
    
    For more information about this error, try `rustc --explain E0658`.
    error: Could not compile `battery`.
    warning: build failed, waiting for other jobs to finish...
    error: aborting due to previous error
    
    For more information about this error, try `rustc --explain E0658`.
    error: Could not compile `battery`.
    warning: build failed, waiting for other jobs to finish...
    error: build failed
    

    OS: Arch Linux

    C-bug A-battery 
    opened by Dentrax 3
Releases(0.7.8)
Owner
svartalf
This guy who loves to make efficient software, building @heim-rs and @actions-rs
svartalf
A cross-platform library for retrieving information about connected devices.

Devices devices is a cross-platform library for retrieving information about connected devices. Combined with a library like sysinfo, a more or less c

Hank Jordan 4 Jan 8, 2023
Cross-platform GameMaker extension for getting system information and resource usage

GM Sysinfo Cross-platform GameMaker extension for getting system information and resource usage Table of Contents Table of Contents Examples Display m

SpikeHD 3 Dec 1, 2023
A Linux laptop battery loggin tool written in Rust.

batt_log A Linux laptop battery logging tool written in Rust. It was built to track power usage of a laptop battery during each session. It keeps trac

Marco Padeiro 3 Apr 4, 2024
First class, scalable rust project generator with batteries included.

amble First class, scalable rust project generator with batteries included. Amble is in beta ??. Install | User Docs | Crate Docs | Reference | Contri

refcell.eth 13 Oct 23, 2023
Batteries included command line interfaces.

CLI Batteries Opinionated batteries-included command line interface runtime utilities. To use it, add it to your Cargo.toml [dependencies] cli-batteri

Remco Bloemen 15 Jan 4, 2023
Rust library crate providing utility functions for diff and patch of slices

This crate provides the Change enum as an abstraction for diff::Result, lcs_diff::DiffResult, and wu_diff::DiffResult; the diff_changes(), diff_diff()

qtfkwk 5 Oct 19, 2022
A truly zero-dependency crate providing quick, easy, reliable, and scalable access to the name "jordin"

jordin Finally! A truly zero-dependency crate providing quick, easy, reliable, and scalable access to the name "jordin". Additionally, this one-of-a-k

jordin 2 Aug 4, 2022
A crate providing a MemoryCell struct, which stores a current and previous value.

memcell What is a MemoryCell? A MemoryCell is a struct containing both a current and optional previous value. Definition #[derive(Debug, Clone)] pub s

Imajin 9 Nov 21, 2022
⚡ An extremely fast cross-compatible system information tool.

Lightfetch A extremely fast command-line system information tool written in Rust ⚡ . Gallery Sadly there isn't much to showcase right now. Download Av

bwtecode 2 Sep 12, 2022
⚡ An extremely fast cross-compatible system information tool.

Lightfetch A extremely fast command-line system information tool written in Rust ⚡ . Gallery Sadly there isn't much to showcase right now. Download Av

bwtecode 2 Sep 12, 2022
Rust crate that allows you to display status & progress information in a terminal

status-line This crate allows you to display status & progress information in a terminal This crate handles the problem of displaying a small amount o

Piotr Kołaczkowski 20 Dec 27, 2022
argmax is a library that allows Rust applications to avoid Argument list too long errors (E2BIG) by providing a std::process::Command wrapper with a

argmax argmax is a library that allows Rust applications to avoid Argument list too long errors (E2BIG) by providing a std::process::Command wrapper w

David Peter 22 Nov 20, 2022
Pure rust library for reading / writing DNG files providing access to the raw data in a zero-copy friendly way.

DNG-rs   A pure rust library for reading / writing DNG files providing access to the raw data in a zero-copy friendly way. Also containing code for re

apertus° - open source cinema 4 Dec 1, 2022
A library providing helpers for various StarkNet fees related tasks.

?? How Much ? ?? Table of Contents About Getting Started Prerequisites Installation Usage Estimate fees on network Authors & contributors Security Lic

Abdel @ StarkWare 4 Dec 15, 2022
Specification for a decomp settings file & library for providing settings to tools

Decomp Settings File There are a lot of decompilation tools. Common metadata like the location of the .map file and target file are often needed by th

Ethan Roseman 3 Aug 19, 2024
Cross-platform Rust library for coloring and formatting terminal output

Coloring terminal output Documentation term-painter is a cross-platform (i.e. also non-ANSI terminals) Rust library for coloring and formatting termin

Lukas Kalbertodt 75 Jul 28, 2022
Cross platform terminal library rust

Cross-platform Terminal Manipulation Library Crossterm is a pure-rust, terminal manipulation library that makes it possible to write cross-platform te

crossterm-rs 2.1k Jan 2, 2023
Cross-platform Rust rewrite of the GNU coreutils

Cross-platform Rust rewrite of the GNU coreutils

null 13k Jan 8, 2023
A cross platform, rust implementation for the Tegra X1 bootROM exploit

Switcheroo A CLI and GUI for the RCM BootRom exploit (Fusée Gelée exploit for Nintendo Switch) Only works on unpatched Switches: https://ismyswitchpat

Ethan Budd 35 Nov 5, 2022