~humaid/hstatus

hstatus/src/main.rs -rw-r--r-- 6.3 KiB
d595479f — Humaid AlQassimi Use chrono-tz for proper timezones that respect DST 6 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
extern crate chrono;
extern crate chrono_tz;
extern crate libc;
extern crate x11;
extern crate signal_hook;

use signal_hook::{iterator::Signals, SIGINT, SIGHUP};

use chrono::prelude::*;
use chrono_tz::Asia::Dubai;
use chrono_tz::Europe::Helsinki;
use libc::{c_int, getloadavg};
use std::ffi::CString;
use std::fs::File;
use std::io::prelude::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::{string, thread, time};

/// System's name
const SYSTEM_NAME: &str = "hsys";

/// DesktopStatus opens the X Display to allow changing the status (root
/// window) name.
#[derive(Debug, Clone, Copy)]
pub struct DesktopStatus {
    disp: *mut x11::xlib::Display,
}

impl DesktopStatus {
    /// Initialises a new DesktopStatus, gets the pointer to the X Display.
    pub fn new() -> Self {
        DesktopStatus {
            disp: unsafe { x11::xlib::XOpenDisplay(std::ptr::null()) },
        }
    }

    /// Sets the name of the root window. This will change the status bar in
    /// dwm.
    pub fn set_status(self, stat: &str) {
        unsafe {
            let s = CString::new(stat).expect("CString::new failed at set_status");
            x11::xlib::XStoreName(
                self.disp,
                x11::xlib::XDefaultRootWindow(self.disp),
                s.as_ptr(),
            );
            x11::xlib::XSync(self.disp, 0);
        }
    }
    
    /// Closes the X Display. This needs to be called once finished using this
    /// structure.
    pub fn close(self) { // TODO destructor
        unsafe {
            x11::xlib::XCloseDisplay(self.disp);
        }
    }
}

/// This represents a function which returns a status item.
type StatusItem = fn() -> Result<String, String>;

/// A StatusItem which displays the system load.
fn load_item() -> Result<String, String> {
    match get_load() {
        Ok(load) => return Ok(format!("L:{}|", load.as_str())),
        Err(why) => Err(format!("Cannot get load: {}", why)),
    }
}

/// A StatusItem which displays the battery percentage.
fn battery_item() -> Result<String, String> {
    match get_battery_with_status() {
        Ok(perc) => return Ok(format!("B:{}|", perc.as_str())),
        Err(why) => Err(format!("Cannot get battery percentage: {}", why)),
    }
}

/// A StatusItem which displays the time and date.
fn time_item() -> Result<String, String> {
    let mut res = String::new();
    let local: DateTime<Local> = Local::now();
    res.push_str("FI:");
    res.push_str(
        Helsinki.from_utc_datetime(&local.naive_utc())
            .format("%I:%M").to_string().as_str(),
    );
    res.push(' ');
    res.push_str("AE:");
    res.push_str(
	Dubai.from_utc_datetime(&local.naive_utc())
        .format("%I:%M %p %d-%m-%Y").to_string().as_str());
    res.push('|');
    Ok(res)
}

fn main() {
    let signals = Signals::new(&[SIGINT, SIGHUP]).unwrap();

    // Register the status items
    let mut stat_items: Vec<StatusItem> = Vec::new();
    stat_items.push(load_item);
    stat_items.push(battery_item);
    stat_items.push(time_item);

    let status: DesktopStatus = DesktopStatus::new();

    let cont = Arc::new(AtomicBool::new(true));
    {
        let c = Arc::clone(&cont);
        thread::spawn(move || {
            for _ in signals.forever() {
                println!("Closing...");
                c.store(false, Ordering::SeqCst);
            }
        });
    }

    while cont.load(Ordering::SeqCst) {
        println!("Updating status");
        // Run the low battery flair
        let bat_num = get_battery_perc();
        if bat_num < 20 {
            let st_res = read_file("/sys/class/power_supply/BAT0/status");
            if let Ok(s) = st_res {
                if s.trim() == "Discharging" {
                    let mut bat_notice = String::new();
                    bat_notice.push_str("==============================");
                    bat_notice.push_str(" !!! Low Battery !!! (");
                    bat_notice.push_str(bat_num.to_string().as_str());
                    bat_notice.push_str("%) ==============================");

                    for i in 0..4 {
                        if i % 2 == 0 {
                            status.set_status(bat_notice.as_str());
                        } else {
                            status.set_status("hey!");
                        }
                        thread::sleep(time::Duration::from_secs(1));
                    }
                }
            }
        }

        let mut stat = String::new();

        for i in &stat_items {
            match i() {
                Ok(s) => stat.push_str(s.as_str()),
                Err(s) => println!("Error: {}", s),
            }
        }

        stat.push_str(SYSTEM_NAME);
        status.set_status(stat.as_str());
        thread::sleep(time::Duration::from_secs(3));
    }
    status.close();
}

/// Reads a file from the system.
fn read_file(file: &str) -> std::io::Result<string::String> {
    let mut file = File::open(file)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents.replace("\n", ""))
}

/// Gets the system load, formatted in a way similar to uptime.
fn get_load() -> Result<string::String, &'static str> {
    let mut avgs = Vec::with_capacity(3_usize);
    match unsafe { getloadavg(avgs.as_mut_ptr(), 3 as c_int) } {
        -1 => Err("returned -1"),
        3 => {
            unsafe {
                avgs.set_len(3_usize);
            }
            Ok(format!("{:.2} {:.2} {:.2}", avgs[0], avgs[1], avgs[2]))
        }
        _ => Err("unknown value"),
    }
}

/// Gets the battery percentage.
fn get_battery_perc() -> i32 {
    let present = read_file("/sys/class/power_supply/BAT0/present").unwrap();
    assert_eq!(present, "1", "Battery not present");

    let full:i32 = read_file("/sys/class/power_supply/BAT0/energy_full_design")
        .unwrap().parse().unwrap();
    let now: i32 = read_file("/sys/class/power_supply/BAT0/energy_now")
        .unwrap().parse().unwrap();

    return ((now as f64 / full as f64) * 100_f64) as i32
}

/// Gets the charging/discharing status.
fn get_battery_with_status() -> std::io::Result<string::String> {
    let status = read_file("/sys/class/power_supply/BAT0/status")?;
    let stat = match status.as_ref() {
        "Discharging" => "-",
        "Charging" => "+",
        _ => "/",
    };

    Ok(format!("{}%{}", get_battery_perc(), stat))
}