Skip to main content

batno/
lib.rs

1//! # BatNo
2//!
3//! A battery monitoring library that periodically checks battery status and
4//! sends notifications when the battery reaches a configured threshold.
5//!
6//! ## Extending BatNo
7//!
8//! Platform-specific functionality is isolated behind two traits:
9//!
10//! - [`BatteryProvider`] handles reading battery information.
11//! - [`SystemNotifier`] handles sending notifications.
12//!
13//! To add support for a new operating system:
14//!
15//! 1. Implement [`BatteryProvider`] for the new platform.
16//! 2. Implement [`SystemNotifier`] for the platform's notification system.
17//! 3. Create a constructor that combines those implementations into a
18//!    [`BatteryMonitor`].
19//!
20//! The monitoring logic does not need to change as long as the new types
21//! implement the required traits.
22
23use std::{fmt, fs};
24use std::{io, path::PathBuf};
25use std::{
26    process::Command,
27    thread::sleep,
28    time::{Duration, Instant},
29};
30/// Location where Linux exposes power supply devices.
31///
32/// Every battery, AC adapter, and other power source is represented as a
33/// directory inside this path.
34const LINUX_POWER_SUPPLY_PATH: &str = "/sys/class/power_supply/";
35
36/// Represents the current state of a battery.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum BatteryStatus {
39    /// Battery is currently charging.
40    Charging,
41    /// Battery is currently supplying power to the system.
42    Discharging,
43    /// Battery is neither charging nor discharging.
44    ///
45    /// This can represent states such as a fully charged battery or a temporarily
46    /// inactive charging state.
47    Idle,
48    /// Battery state could not be determined.
49    Unknown,
50}
51
52impl fmt::Display for BatteryStatus {
53    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54        match self {
55            BatteryStatus::Charging => write!(f, "Charging"),
56            BatteryStatus::Discharging => write!(f, "Discharging"),
57            BatteryStatus::Idle => write!(f, "Idle"),
58            BatteryStatus::Unknown => write!(f, "Unknown"),
59        }
60    }
61}
62
63/// Provides access to battery information.
64///
65/// This trait abstracts the source of battery data. The default implementation for Linux
66/// reads information from Linux's `/sys/class/power_supply` filesystem, but
67/// alternative implementations can provide data from another source.
68pub trait BatteryProvider {
69    /// Returns the current battery percentage (0-100).
70    fn get_capacity(&self) -> Result<u8, io::Error>;
71    /// Returns the current charging state of the battery.
72    fn get_battery_status(&self) -> Result<BatteryStatus, io::Error>;
73    /// Returns the battery technology (for example Lithium-Polymer).
74    fn get_technology(&self) -> Result<String, io::Error>;
75    /// Returns the battery manufacturer name.
76    fn get_manufacturer(&self) -> Result<String, io::Error>;
77    /// Returns the battery model name.
78    fn get_model_name(&self) -> Result<String, io::Error>;
79    /// Returns the battery serial number.
80    fn get_serial_number(&self) -> Result<String, io::Error>;
81}
82
83/// Provides a way to send system notifications.
84///
85/// This abstraction allows the battery monitor to work with different
86/// notification systems without depending on a specific implementation.
87pub trait SystemNotifier {
88    /// Sends a notification to the user.
89    ///
90    /// # Arguments
91    ///
92    /// * `title` - Notification title.
93    /// * `message` - Notification body text.
94    /// * `urgency` - Notification importance level.
95    ///
96    /// `urgency` is an implementation-defined hint describing the importance
97    /// of the notification. Individual notifier implementations may interpret
98    /// this value differently or ignore it.
99    fn notify(&self, title: &str, message: &str, urgency: &str) -> Result<(), io::Error>;
100}
101
102/// Searches the Linux power supply directory for a battery device.
103///
104/// Returns the path of the first device whose `type` file contains `Battery`.
105fn find_linux_battery_path() -> Option<PathBuf> {
106    fs::read_dir(LINUX_POWER_SUPPLY_PATH)
107        .ok()?
108        .flatten()
109        .map(|entry| entry.path())
110        .find(|path| {
111            fs::read_to_string(path.join("type"))
112                .map(|t| t.trim() == "Battery")
113                .unwrap_or(false)
114        })
115}
116
117/// Battery provider implementation for Linux systems.
118///
119/// Reads battery information from the Linux sysfs power supply interface.
120pub struct LinuxBattery {
121    path: PathBuf,
122}
123
124impl LinuxBattery {
125    /// Creates a Linux battery provider.
126    ///
127    /// Returns an error if no battery device can be found.
128    fn new() -> Result<Self, io::Error> {
129        match find_linux_battery_path() {
130            Some(path) => Ok(LinuxBattery { path }),
131            _ => Err(io::Error::new(
132                io::ErrorKind::NotFound,
133                "No Linux battery found",
134            )),
135        }
136    }
137}
138
139impl BatteryProvider for LinuxBattery {
140    fn get_capacity(&self) -> Result<u8, io::Error> {
141        fs::read_to_string(self.path.join("capacity"))?
142            .trim()
143            .parse::<u8>()
144            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
145    }
146
147    fn get_battery_status(&self) -> Result<BatteryStatus, io::Error> {
148        let content = fs::read_to_string(self.path.join("status"))?;
149        match content.trim() {
150            "Discharging" => Ok(BatteryStatus::Discharging),
151            "Charging" => Ok(BatteryStatus::Charging),
152            "Full" => Ok(BatteryStatus::Idle),
153            "Not charging" => Ok(BatteryStatus::Idle),
154            _ => Ok(BatteryStatus::Unknown),
155        }
156    }
157
158    fn get_technology(&self) -> Result<String, io::Error> {
159        Ok(fs::read_to_string(self.path.join("technology"))?
160            .trim()
161            .to_string())
162    }
163
164    fn get_manufacturer(&self) -> Result<String, io::Error> {
165        Ok(fs::read_to_string(self.path.join("manufacturer"))?
166            .trim()
167            .to_string())
168    }
169
170    fn get_model_name(&self) -> Result<String, io::Error> {
171        Ok(fs::read_to_string(self.path.join("model_name"))?
172            .trim()
173            .to_string())
174    }
175
176    fn get_serial_number(&self) -> Result<String, io::Error> {
177        Ok(fs::read_to_string(self.path.join("serial_number"))?
178            .trim()
179            .to_string())
180    }
181}
182
183/// Sends desktop notifications using the Linux `notify-send` command.
184///
185/// Supported urgency values:
186///
187/// - `"low"`
188/// - `"normal"`
189/// - `"critical"`
190pub struct LinuxNotifier;
191
192impl SystemNotifier for LinuxNotifier {
193    /// Runs: notify-send --urgency low|normal|critical "<title>" "<message>"
194    fn notify(&self, title: &str, message: &str, urgency: &str) -> Result<(), io::Error> {
195        Command::new("notify-send")
196            .arg("--urgency")
197            .arg(urgency)
198            .arg(title)
199            .arg(message)
200            .status()
201            .and_then(|status| {
202                if status.success() {
203                    Ok(())
204                } else {
205                    Err(io::Error::other("notify-send returned a failure status"))
206                }
207            })
208            .map_err(|e| io::Error::other(format!("Notify-send failed: {e}")))
209    }
210}
211
212/// Coordinates battery monitoring and notification handling.
213///
214/// The monitor periodically checks battery capacity and sends a notification
215/// when the configured threshold is reached. After a notification is sent,
216/// the battery must recharge above the reset threshold before another
217/// notification can occur.
218pub struct BatteryMonitor<S: SystemNotifier, T: BatteryProvider> {
219    provider: T,
220    notifier: S,
221    notify_threshold: u8,
222    reset_threshold: u8,
223    monitor_interval: u32,
224    notification_sent: bool,
225}
226
227impl BatteryMonitor<LinuxNotifier, LinuxBattery> {
228    /// Creates a battery monitor using Linux implementations.
229    ///
230    /// Uses sysfs for battery information and `notify-send` for desktop
231    /// notifications.
232    ///
233    /// # Errors
234    ///
235    /// Returns an error if no battery device can be found.
236    pub fn new_linux(
237        notify_threshold: u8,
238        reset_threshold: u8,
239        monitor_interval: u32,
240    ) -> Result<Self, io::Error> {
241        Ok(BatteryMonitor {
242            provider: LinuxBattery::new()?,
243            notifier: LinuxNotifier,
244            notify_threshold,
245            reset_threshold,
246            monitor_interval,
247            notification_sent: false,
248        })
249    }
250}
251
252/// Converts a `Result` into a displayable string.
253///
254/// Successful values are converted using `Display`. Failed values are replaced
255/// with a human-readable error message for table output.
256fn format_result<T: std::fmt::Display>(result: Result<T, io::Error>, field: &str) -> String {
257    result
258        .map(|v| v.to_string())
259        .unwrap_or_else(|_| format!("Failed to fetch {field}"))
260}
261
262/// Prints battery information as a formatted table.
263///
264/// If a value cannot be read, the table displays an error message in the
265/// corresponding row instead of failing completely.
266pub fn print_battery_info<S: SystemNotifier, T: BatteryProvider>(monitor: &BatteryMonitor<S, T>) {
267    let capacity = monitor.provider.get_capacity();
268    let status = monitor.provider.get_battery_status();
269    let technology = monitor.provider.get_technology();
270    let manufacturer = monitor.provider.get_manufacturer();
271    let model_name = monitor.provider.get_model_name();
272    let serial_number = monitor.provider.get_serial_number();
273
274    let rows = vec![
275        (
276            "Capacity",
277            format_result(capacity.map(|v| format!("{v}%")), "capacity"),
278        ),
279        ("Status", format_result(status, "status")),
280        ("Technology", format_result(technology, "technology")),
281        ("Manufacturer", format_result(manufacturer, "manufacturer")),
282        ("Model", format_result(model_name, "model")),
283        (
284            "Serial Number",
285            format_result(serial_number, "serial number"),
286        ),
287    ];
288
289    let left_width = rows.iter().map(|(k, _)| k.len()).max().unwrap_or(0);
290
291    let right_width = rows.iter().map(|(_, v)| v.len()).max().unwrap_or(0);
292
293    println!(
294        "┌{:─<left$}┬{:─<right$}┐",
295        "",
296        "",
297        left = left_width + 2,
298        right = right_width + 2
299    );
300
301    println!(
302        "│ {:^left$} │ {:^right$} │",
303        "Property",
304        "Value",
305        left = left_width,
306        right = right_width
307    );
308
309    println!(
310        "├{:─<left$}┼{:─<right$}┤",
311        "",
312        "",
313        left = left_width + 2,
314        right = right_width + 2
315    );
316
317    for (key, value) in rows {
318        println!(
319            "│ {:<left$} │ {:<right$} │",
320            key,
321            value,
322            left = left_width,
323            right = right_width
324        );
325    }
326
327    println!(
328        "└{:─<left$}┴{:─<right$}┘",
329        "",
330        "",
331        left = left_width + 2,
332        right = right_width + 2
333    );
334}
335
336/// Continuously monitors battery level and sends notifications when required.
337///
338/// The function runs indefinitely. Temporary failures while reading battery
339/// information or sending notifications are logged and retried during the next
340/// monitoring cycle.
341pub fn monitor_battery<S: SystemNotifier, T: BatteryProvider>(mut monitor: BatteryMonitor<S, T>) {
342    loop {
343        let start = Instant::now();
344        match monitor.provider.get_capacity() {
345            Ok(capacity) => {
346                if capacity <= monitor.notify_threshold && !monitor.notification_sent {
347                    let mut result = Err(io::Error::other("not attempted"));
348                    for _ in 0..5 {
349                        result = monitor.notifier.notify(
350                            "BatNo",
351                            &format!("Your battery capacity is equal to or below your set threshold of {}%. Please plug your computer into a power source to charge it", monitor.notify_threshold ),
352                            "critical",
353                        );
354
355                        if result.is_ok() {
356                            monitor.notification_sent = true;
357                            break;
358                        }
359                    }
360
361                    if let Err(e) = result {
362                        eprintln!("Failed to send notification: {e}");
363                    }
364                } else if capacity >= monitor.reset_threshold && monitor.notification_sent {
365                    monitor.notification_sent = false
366                }
367            }
368            Err(e) => {
369                eprintln!("{e}");
370            }
371        }
372
373        let sleep_time =
374            Duration::from_secs(monitor.monitor_interval.into()).saturating_sub(start.elapsed());
375        sleep(sleep_time);
376    }
377}