1use std::{fmt, fs};
24use std::{io, path::PathBuf};
25use std::{
26 process::Command,
27 thread::sleep,
28 time::{Duration, Instant},
29};
30const LINUX_POWER_SUPPLY_PATH: &str = "/sys/class/power_supply/";
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum BatteryStatus {
39 Charging,
41 Discharging,
43 Idle,
48 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
63pub trait BatteryProvider {
69 fn get_capacity(&self) -> Result<u8, io::Error>;
71 fn get_battery_status(&self) -> Result<BatteryStatus, io::Error>;
73 fn get_technology(&self) -> Result<String, io::Error>;
75 fn get_manufacturer(&self) -> Result<String, io::Error>;
77 fn get_model_name(&self) -> Result<String, io::Error>;
79 fn get_serial_number(&self) -> Result<String, io::Error>;
81}
82
83pub trait SystemNotifier {
88 fn notify(&self, title: &str, message: &str, urgency: &str) -> Result<(), io::Error>;
100}
101
102fn 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
117pub struct LinuxBattery {
121 path: PathBuf,
122}
123
124impl LinuxBattery {
125 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
183pub struct LinuxNotifier;
191
192impl SystemNotifier for LinuxNotifier {
193 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
212pub 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 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
252fn 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
262pub 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
336pub 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}