To create a laptop battery level notifier in Rust for an Arch Linux machine, follow these steps:
Install Rust and required tools:
sh Copy code
sudo pacman -S rustup
rustup-init
source $HOME/.cargo/env
Install libdbus and dunst (if you haven't already):
sh Copy code
sudo pacman -S libdbus dunst
Create a new Rust project:
sh Copy code
cargo new battery_notifier
cd battery_notifier
Add dbus and notify-rust dependencies to your Cargo.toml:
toml Copy code
[dependencies]
dbus = "0.9"
notify-rust = "4.0"
Replace the contents of src/main.rs with the following code:
rust Copy code
use dbus::blocking::Connection;
use notify_rust::Notification;
use std::time::Duration;
fn get_battery_percentage(conn: &Connection) -> Result<u32, Box<dyn std::error::Error>> {
let upower_path = "/org/freedesktop/UPower/devices/battery_BAT0";
let msg = dbus::Message::new_method_call(
"org.freedesktop.UPower",
upower_path,
"org.freedesktop.DBus.Properties",
"Get",
)?
.append2(
"org.freedesktop.UPower.Device",
"Percentage",
);
let response = conn.send_with_reply_and_block(msg, Duration::from_millis(500))?;
let percentage: f64 = response.read1()?;
Ok(percentage as u32)
}
fn show_notification() {
Notification::new()
.summary("Low Battery")
.body("Your battery level is below 30%.")
.icon("battery")
.show()
.expect("Failed to show notification");
}
fn main() {
let conn = Connection::new_system().expect("Failed to connect to D-Bus system.");
loop {
match get_battery_percentage(&conn) {
Ok(percentage) => {
if percentage < 30 {
show_notification();
}
}
Err(e) => eprintln!("Failed to get battery percentage: {}", e),
}
std::thread::sleep(Duration::from_secs(10));
}
}
Compile and run the Rust program:
sh Copy code
cargo build --release
./target/release/battery_notifier
This program will check the battery level every 10 seconds and show a notification using Dunst if the battery level drops below 30%.
To make the notifier start automatically when you log in, you can create a .desktop file in ~/.config/autostart with the following content:
ini Copy code
[Desktop Entry]
Type=Application
Name=Battery Notifier
Exec=/path/to/battery_notifier/target/release/battery_notifier
Hidden=false
NoDisplay=false
Terminal=false
Remember to replace /path/to/battery_notifier with the correct path to your compiled binary.