Skip to main content

i3status_rs/blocks/
nvidia_gpu.rs

1//! Display the stats of your NVidia GPU
2//!
3//! By default `show_temperature` shows the used memory. Clicking the left mouse on the
4//! "temperature" part of the block will alternate it between showing used or total available
5//! memory.
6//!
7//! Clicking the left mouse button on the "fan speed" part of the block will cause it to enter into
8//! a fan speed setting mode. In this mode you can scroll the mouse wheel over the block to change
9//! the fan speeds, and left click to exit the mode.
10//!
11//! Requires `nvidia-smi` for displaying info and `nvidia_settings` for setting fan speed.
12//!
13//! On laptops with switchable graphics, `nvidia-smi` powers on the dedicated GPU every time it
14//! runs, which keeps the GPU awake and raises power consumption. Increase `interval` or avoid this
15//! block if that matters on battery.
16//!
17//! # Configuration
18//!
19//! Key | Values | Default
20//! ----|--------|--------
21//! `gpu_id` | GPU id in system. | `0`
22//! `format` | A string to customise the output of this block. See below for available placeholders. | `" $icon $utilization $vram_used $temperature "`
23//! `interval` | Update interval in seconds. | `1`
24//! `idle` | Maximum temperature, below which state is set to idle | `50`
25//! `good` | Maximum temperature, below which state is set to good | `70`
26//! `info` | Maximum temperature, below which state is set to info | `75`
27//! `warning` | Maximum temperature, below which state is set to warning | `80`
28//!
29//! Placeholder   | Type   | Unit
30//! --------------|--------|---------------
31//! `icon`        | Icon   | -
32//! `name`        | Text   | -
33//! `utilization` | Number | Percents
34//! `memory`      | Number *DEPRECATED* | Bytes
35//! `vram_total`  | Number | Bytes
36//! `vram_used`   | Number | Bytes
37//! `vram_used_percents` | Number | Percents
38//! `temperature` | Number | Degrees
39//! `fan_speed`   | Number | Percents
40//! `clocks`      | Number | Hertz
41//! `power`       | Number | Watts
42//!
43//! `memory` has been deprecated in favor of `vram_used` and `vram_total`.
44//!
45//! Widget    | Placeholder
46//! ----------|-------------
47//! `mem_btn` | `$memory`
48//! `fan_btn` | `$fan_speed`
49//!
50//! Action                  | Default button
51//! ------------------------|----------------
52//! `toggle_mem_total` *DEPRECATED* | Left on `mem_btn`
53//! `toggle_fan_controlled` | Left on `fan_btn`
54//! `fan_speed_up`          | Wheel Up on `fan_btn`
55//! `fan_speed_down`        | Wheel Down on `fan_btn`
56//!
57//! # Example
58//!
59//! ```toml
60//! [[block]]
61//! block = "nvidia_gpu"
62//! interval = 1
63//! format = " $icon GT 1030 $utilization $temperature $clocks "
64//! ```
65//!
66//! # Icons Used
67//! - `gpu` (`$icon`)
68//!
69//! # TODO
70//! - Provide a `mappings` option similar to `keyboard_layout`'s  to map GPU names to labels?
71
72use std::process::Stdio;
73use std::str::FromStr;
74
75use tokio::io::{BufReader, Lines};
76use tokio::process::Command;
77
78const MEM_BTN: &str = "mem_btn";
79const FAN_BTN: &str = "fan_btn";
80const QUERY: &str = "--query-gpu=name,memory.total,utilization.gpu,memory.used,temperature.gpu,fan.speed,clocks.current.graphics,power.draw,";
81const FORMAT: &str = "--format=csv,noheader,nounits";
82
83use super::prelude::*;
84
85#[derive(Deserialize, Debug, SmartDefault)]
86#[serde(deny_unknown_fields, default)]
87pub struct Config {
88    pub format: FormatConfig,
89    #[default(1.into())]
90    pub interval: Seconds,
91    #[default(0)]
92    pub gpu_id: u64,
93    #[default(50)]
94    pub idle: u32,
95    #[default(70)]
96    pub good: u32,
97    #[default(75)]
98    pub info: u32,
99    #[default(80)]
100    pub warning: u32,
101}
102
103pub(crate) fn prepare(config: &Config) -> Result<Arc<BlockPlan>> {
104    BlockPlan::new(vec![
105        OutputPlan::new(
106            "main",
107            config
108                .format
109                .with_default(" $icon $utilization $vram_used $temperature ")?,
110        )
111        .icon("icon", IconChoices::one(icons::GPU)),
112    ])
113}
114
115pub(crate) async fn run(config: &Config, api: &CommonApi, plan: &Arc<BlockPlan>) -> Result<()> {
116    let mut actions = api.get_actions()?;
117    api.set_default_actions(&[
118        (MouseButton::Left, Some(MEM_BTN), "toggle_mem_total"),
119        (MouseButton::Left, Some(FAN_BTN), "toggle_fan_controlled"),
120        (MouseButton::WheelUp, Some(FAN_BTN), "fan_speed_up"),
121        (MouseButton::WheelDown, Some(FAN_BTN), "fan_speed_down"),
122    ])?;
123
124    let output_main = plan.output("main")?;
125
126    // Run `nvidia-smi` command
127    let mut child = Command::new("nvidia-smi")
128        .args([
129            "-l",
130            &config.interval.seconds().to_string(),
131            "-i",
132            &config.gpu_id.to_string(),
133            QUERY,
134            FORMAT,
135        ])
136        .stdout(Stdio::piped())
137        .kill_on_drop(true)
138        .spawn()
139        .error("Failed to execute nvidia-smi")?;
140    let mut reader = BufReader::new(child.stdout.take().unwrap()).lines();
141
142    // Read the initial info
143    let mut info = GpuInfo::from_reader(&mut reader).await?;
144    let mut show_mem_total = false;
145    let mut fan_controlled = false;
146
147    loop {
148        let mut widget = output_main.new_widget();
149
150        widget.state = match info.temperature {
151            t if t <= config.idle => State::Idle,
152            t if t <= config.good => State::Good,
153            t if t <= config.info => State::Info,
154            t if t <= config.warning => State::Warning,
155            _ => State::Critical,
156        };
157
158        widget.set_values(map! {
159            "icon" => Value::icon(icons::GPU),
160            "name" => Value::text(info.name.clone()),
161            "utilization" => Value::percents(info.utilization),
162            "memory" => Value::bytes(if show_mem_total {info.mem_total} else {info.mem_used}).with_instance(MEM_BTN),
163            "vram_total" => Value::bytes(info.mem_total),
164            "vram_used" => Value::bytes(info.mem_used),
165            "vram_used_percents" => Value::percents(info.mem_used / info.mem_total * 100.0),
166            "temperature" => Value::degrees_c(info.temperature),
167            "fan_speed" => Value::percents(info.fan_speed).with_instance(FAN_BTN).underline(fan_controlled).italic(fan_controlled),
168            "clocks" => Value::hertz(info.clocks),
169            "power" => Value::watts(info.power_draw),
170        });
171
172        api.set_widget(widget)?;
173
174        select! {
175            new_info = GpuInfo::from_reader(&mut reader) => {
176                info = new_info?;
177            }
178            code = child.wait() => {
179                let code = code.error("failed to check nvidia-smi exit code")?;
180                return Err(Error::new(format!("nvidia-smi exited with code {code}")));
181            }
182            Some(action) = actions.recv() => match action.as_ref() {
183                "toggle_mem_total" => {
184                    show_mem_total = !show_mem_total;
185                }
186                "toggle_fan_controlled" => {
187                    fan_controlled = !fan_controlled;
188                    set_fan_speed(config.gpu_id, fan_controlled.then_some(info.fan_speed)).await?;
189                }
190                "fan_speed_up" if fan_controlled && info.fan_speed < 100 => {
191                    info.fan_speed += 1;
192                    set_fan_speed(config.gpu_id, Some(info.fan_speed)).await?;
193                }
194                "fan_speed_down" if fan_controlled && info.fan_speed > 0 => {
195                    info.fan_speed -= 1;
196                    set_fan_speed(config.gpu_id, Some(info.fan_speed)).await?;
197                }
198                _ => (),
199            }
200        }
201    }
202}
203
204#[derive(Debug)]
205struct GpuInfo {
206    name: String,
207    mem_total: f64,   // bytes
208    mem_used: f64,    // bytes
209    utilization: f64, // percents
210    temperature: u32, // degrees
211    fan_speed: u32,   // percents
212    clocks: f64,      // hertz
213    power_draw: f64,  // watts
214}
215
216impl GpuInfo {
217    /// Read a line from provided reader and parse it
218    ///
219    /// # Cancel safety
220    ///
221    /// This method should be cancellation safe, because it has only one `.await` and it is on `next_line`, which is cancellation safe.
222    async fn from_reader<B: AsyncBufRead + Unpin>(reader: &mut Lines<B>) -> Result<Self> {
223        const ERR_MSG: &str = "failed to read from nvidia-smi";
224        reader
225            .next_line()
226            .await
227            .error(ERR_MSG)?
228            .error(ERR_MSG)?
229            .parse::<GpuInfo>()
230            .error("failed to parse nvidia-smi output")
231    }
232}
233
234impl FromStr for GpuInfo {
235    type Err = Error;
236
237    fn from_str(s: &str) -> Result<Self, Self::Err> {
238        macro_rules! parse {
239            ($s:ident -> $($part:ident : $t:ident $(* $mul:expr)?),*) => {{
240                let mut parts = $s.trim().split(", ");
241                let info = GpuInfo {
242                    $(
243                    $part: {
244                        let $part = parts
245                            .next()
246                            .error(concat!("missing property: ", stringify!($part)))?
247                            .parse::<$t>()
248                            .unwrap_or_default();
249                        $(let $part = $part * $mul;)?
250                        $part
251                    },
252                    )*
253                };
254                Ok(info)
255            }}
256        }
257        // `memory` and `clocks` are initially in MiB and MHz, parse them accordingly
258        parse!(s -> name: String, mem_total: f64 * 1024.0 * 1024.0, utilization: f64, mem_used: f64 * 1024.0 * 1024.0, temperature: u32, fan_speed: u32, clocks: f64 * 1e6, power_draw: f64)
259    }
260}
261
262async fn set_fan_speed(id: u64, speed: Option<u32>) -> Result<()> {
263    const ERR_MSG: &str = "Failed to execute nvidia-settings";
264    let mut cmd = Command::new("nvidia-settings");
265    if let Some(speed) = speed {
266        cmd.args([
267            "-a",
268            &format!("[gpu:{id}]/GPUFanControlState=1"),
269            "-a",
270            &format!("[fan:{id}]/GPUTargetFanSpeed={speed}"),
271        ]);
272    } else {
273        cmd.args(["-a", &format!("[gpu:{id}]/GPUFanControlState=0")]);
274    }
275    if cmd
276        .spawn()
277        .error(ERR_MSG)?
278        .wait()
279        .await
280        .error(ERR_MSG)?
281        .success()
282    {
283        Ok(())
284    } else {
285        Err(Error::new(ERR_MSG))
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    #[test]
294    fn plan_declares_single_output_with_gpu_icon() {
295        let plan = prepare(&Config::default()).unwrap();
296        let ids: Vec<_> = plan.outputs().map(|o| o.id()).collect();
297        assert_eq!(ids, ["main"]);
298        let main = plan.output("main").unwrap();
299        assert_eq!(main.single_icon("icon").unwrap(), "gpu");
300        assert!(main.format().contains_key("utilization"));
301    }
302
303    #[test]
304    fn plan_uses_configured_format() {
305        let config = Config {
306            format: " $icon $fan_speed ".parse().unwrap(),
307            ..Config::default()
308        };
309        let plan = prepare(&config).unwrap();
310        let main = plan.output("main").unwrap();
311        assert!(main.format().contains_key("fan_speed"));
312        assert!(!main.format().contains_key("utilization"));
313    }
314}