Skip to main content

i3status_rs/blocks/
net.rs

1//! Network information
2//!
3//! This block uses `sysfs` and `netlink` and thus does not require any external dependencies.
4//!
5//! # Configuration
6//!
7//! Key | Values | Default
8//! ----|--------|--------
9//! `device` | Network interface to monitor (as specified in `/sys/class/net/`). Supports regex. | If not set, device will be automatically selected every `interval`
10//! `interval` | Update interval in seconds | `2`
11//! `wifi_generation_superscript` | Display `$wifi_generation` using Unicode superscripts (`⁴`, `⁵`, `⁶`, `⁶ᴱ`, `⁷`) | `true`
12//! `format` | A [MultiFormat][MaybeMultiFormatConfig] string to customise the output of this block. See below for available placeholders. | `[" $icon ^icon_net_down $speed_down.eng(prefix:K) ^icon_net_up $speed_up.eng(prefix:K) "]`
13//! `inactive_format` | Same as `format` but for when the interface is inactive | `" $icon Down "`
14//! `missing_format` | Same as `format` but for when the device is missing | `" × "`
15//!
16//! Action          | Description                               | Default button
17//! ----------------|-------------------------------------------|---------------
18//! `toggle_format` **DEPRECATED** | Toggles between `format` and `format_alt` | -
19//! `next_format`  | Switches to the next format in the list     | Left
20//! `prev_format`  | Switches to the previous format in the list | Right
21//!
22//! Placeholder       | Value                       | Type   | Unit
23//! ------------------|-----------------------------|--------|---------------
24//! `icon`            | Icon based on device's type | Icon   | -
25//! `speed_down`      | Download speed              | Number | Bytes per second
26//! `speed_up`        | Upload speed                | Number | Bytes per second
27//! `graph_down`      | Download speed graph        | Text   | -
28//! `graph_up`        | Upload speed graph          | Text   | -
29//! `device`          | The name of device          | Text   | -
30//! `ssid`            | Network SSID (WiFi only)    | Text   | -
31//! `frequency`       | WiFi frequency              | Number | Hz
32//! `signal_strength` | WiFi signal                 | Number | %
33//! `bitrate`         | WiFi connection bitrate     | Number | Bits per second
34//! `wifi_generation` | WiFi generation: `4` (HT), `5` (VHT), `6` (HE on 2.4/5 GHz), `6E` (HE on 6 GHz), `7` (EHT on any band) | Text | -
35//! `ip`              | IPv4 address of the iface   | Text   | -
36//! `ipv6`            | IPv6 address of the iface   | Text   | -
37//! `nameserver`      | Nameserver                  | Text   | -
38//! `enabled`         | Present if the device is switched on (not turned off with `rfkill` or `ip link set down`) | Flag | -
39//!
40//! HT is 802.11n, VHT is 802.11ac, HE is 802.11ax and EHT is 802.11be.
41//! `wifi_generation` uses the associated station's current TX PHY metadata from
42//! nl80211. It does not report a negotiated mode or advertised capabilities.
43//! The dependency does not expose RX PHY metadata. Rate fallback can lower
44//! the reported generation.
45//! Numeric bitrate and channel width are never used to infer a generation;
46//! frequency only distinguishes HE on 6 GHz from HE on 2.4/5 GHz.
47//! The value is absent without a matching association or sufficient TX metadata,
48//! and is refreshed every `interval` without retaining previous values.
49//!
50//! # Example
51//!
52//! Display WiFi info if available
53//!
54//! ```toml
55//! [[block]]
56//! block = "net"
57//! format = " $icon {$signal_strength $ssid $frequency|Wired connection} via $device "
58//! ```
59//!
60//! Display the WiFi generation in plain text, preserving the signal-strength icon
61//!
62//! ```toml
63//! [[block]]
64//! block = "net"
65//! wifi_generation_superscript = false
66//! format = " $icon{ $wifi_generation|} ↓$speed_down ↑$speed_up "
67//! ```
68//!
69//! Display the generation with Unicode superscripts (the default):
70//!
71//! ```toml
72//! [[block]]
73//! block = "net"
74//! format = " $icon{$wifi_generation|} ↓$speed_down ↑$speed_up "
75//! ```
76//!
77//! Display exact device
78//!
79//! ```toml
80//! [[block]]
81//! block = "net"
82//! device = "^wlo0$"
83//! ```
84//!
85//! Tell a WiFi device that is not connected from one that is switched off (with `rfkill` for
86//! example)
87//!
88//! ```toml
89//! [[block]]
90//! block = "net"
91//! device = "^wlan0$"
92//! format = " $icon $signal_strength "
93//! inactive_format = " {$enabled{not connected}|switched off} "
94//! ```
95//!
96//! # Icons Used
97//! - `net_loopback` (`$icon`)
98//! - `net_vpn` (`$icon`)
99//! - `net_wired` (`$icon`)
100//! - `net_wireless` (`$icon`, as a progression)
101//! - `net_up` (`^icon_net_up`)
102//! - `net_down` (`^icon_net_down`)
103
104use super::prelude::*;
105use crate::netlink::NetDevice;
106use crate::util;
107use itertools::Itertools as _;
108use regex::Regex;
109use std::time::Instant;
110
111#[derive(Deserialize, Debug, SmartDefault)]
112#[serde(default)]
113pub struct Config {
114    pub device: Option<String>,
115    #[default(2.into())]
116    pub interval: Seconds,
117    #[default(true)]
118    pub wifi_generation_superscript: bool,
119    #[serde(flatten)]
120    pub formats: MaybeMultiFormatConfig,
121    pub inactive_format: FormatConfig,
122    pub missing_format: FormatConfig,
123}
124
125pub(crate) fn prepare(config: &Config) -> Result<Arc<BlockPlan>> {
126    // Every state that renders a device sets these on every render; the
127    // wifi-only values (ssid, signal_strength, ...) and the addresses are
128    // conditional and stay undeclared.
129    let device_output =
130        |output: OutputPlan| output.icon("icon", IconChoices::fixed(NetDevice::ALL_ICONS));
131    let formats = config.formats.with_default(
132        " $icon ^icon_net_down $speed_down.eng(prefix:K) ^icon_net_up $speed_up.eng(prefix:K) ",
133    )?;
134    // One output per format the user can rotate to, plus the two states that
135    // are not format variants at all: an inactive interface and a missing
136    // device each have their own format and are selected by `run()`.
137    let mut outputs = format_outputs(formats, device_output);
138    outputs.push(device_output(OutputPlan::new(
139        "inactive",
140        config.inactive_format.with_default(" $icon Down ")?,
141    )));
142    // `missing` sets no values at all: nothing to declare.
143    outputs.push(OutputPlan::new(
144        "missing",
145        config.missing_format.with_default(" × ")?,
146    ));
147    BlockPlan::new(outputs)
148}
149
150pub(crate) async fn run(config: &Config, api: &CommonApi, plan: &Arc<BlockPlan>) -> Result<()> {
151    let mut actions = api.get_actions()?;
152    api.set_default_actions(&[
153        (MouseButton::Left, None, "next_format"),
154        (MouseButton::Right, None, "prev_format"),
155    ])?;
156
157    // The plan also holds the `inactive` and `missing` states; the rotation
158    // covers the format outputs alone.
159    let mut formats = FormatRotation::new(plan)?;
160    let output_inactive = plan.output("inactive")?;
161    let output_missing = plan.output("missing")?;
162
163    let mut timer = config.interval.timer();
164
165    let device_re = config
166        .device
167        .as_deref()
168        .map(Regex::new)
169        .transpose()
170        .error("Failed to parse device regex")?;
171
172    // Stats
173    let mut stats = None;
174    let mut stats_timer = Instant::now();
175    let mut tx_hist = [0f64; 8];
176    let mut rx_hist = [0f64; 8];
177
178    loop {
179        match NetDevice::new(device_re.as_ref()).await? {
180            None => {
181                api.set_widget(output_missing.new_widget())?;
182            }
183            Some(device) => {
184                let output = if device.is_up() {
185                    formats.current()
186                } else {
187                    &output_inactive
188                };
189                let mut widget = output.new_widget();
190
191                let mut speed_down: f64 = 0.0;
192                let mut speed_up: f64 = 0.0;
193
194                // Calculate speed
195                match (stats, device.iface.stats) {
196                    // No previous stats available
197                    (None, new_stats) => stats = new_stats,
198                    // No new stats available
199                    (Some(_), None) => stats = None,
200                    // All stats available
201                    (Some(old_stats), Some(new_stats)) => {
202                        let diff = new_stats - old_stats;
203                        let elapsed = stats_timer.elapsed().as_secs_f64();
204                        stats_timer = Instant::now();
205                        speed_down = diff.rx_bytes as f64 / elapsed;
206                        speed_up = diff.tx_bytes as f64 / elapsed;
207                        stats = Some(new_stats);
208                    }
209                }
210                push_to_hist(&mut rx_hist, speed_down);
211                push_to_hist(&mut tx_hist, speed_up);
212
213                let icon = if let Some(signal) = device.signal() {
214                    Value::icon_progression(device.icon, signal / 100.0)
215                } else {
216                    Value::icon(device.icon)
217                };
218
219                widget.set_values(map! {
220                    "icon" => icon,
221                    "speed_down" => Value::bytes(speed_down),
222                    "speed_up" => Value::bytes(speed_up),
223                    "graph_down" => Value::text(util::format_bar_graph(&rx_hist)),
224                    "graph_up" => Value::text(util::format_bar_graph(&tx_hist)),
225                    [if let Some(v) = device.ip] "ip" => Value::text(v.to_string()),
226                    [if let Some(v) = device.ipv6] "ipv6" => Value::text(v.to_string()),
227                    [if let Some(v) = device.ssid()] "ssid" => Value::text(v),
228                    [if let Some(v) = device.frequency()] "frequency" => Value::hertz(v),
229                    [if let Some(v) = device.bitrate()] "bitrate" => Value::bits(v),
230                    [if let Some(v) = device.signal()] "signal_strength" => Value::percents(v),
231                    [if let Some(v) = device.wifi_generation()] "wifi_generation" => Value::text(v.as_str(config.wifi_generation_superscript).into()),
232                    [if !device.nameservers.is_empty()] "nameserver" => Value::text(
233                                                                            device
234                                                                                .nameservers
235                                                                                .into_iter()
236                                                                                .map(|s| s.to_string())
237                                                                                .join(" "),
238                                                                        ),
239                    [if device.iface.enabled] "enabled" => Value::flag(),
240                    "device" => Value::text(device.iface.name),
241                });
242
243                api.set_widget(widget)?;
244            }
245        }
246
247        loop {
248            select! {
249                _ = timer.tick() => break,
250                _ = api.wait_for_update_request() => break,
251                Some(action) = actions.recv() => match action.as_ref() {
252                    "next_format" | "toggle_format" => {
253                        formats.next();
254                        break;
255                    }
256                    "prev_format" => {
257                        formats.prev();
258                        break;
259                    }
260                    _ => ()
261                }
262            }
263        }
264    }
265}
266
267fn push_to_hist<T>(hist: &mut [T], elem: T) {
268    hist[0] = elem;
269    hist.rotate_left(1);
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    #[test]
277    fn wifi_generation_format_uses_configured_style() {
278        use crate::netlink::WifiGeneration::Wifi6E;
279        let template: crate::formatting::template::FormatTemplate =
280            "{$wifi_generation|}".parse().unwrap();
281        for (config, generation, expected) in [
282            ("", Some(Wifi6E), "⁶ᴱ"),
283            ("wifi_generation_superscript = false", Some(Wifi6E), "6E"),
284            ("", None, ""),
285        ] {
286            let config: Config = toml::from_str(config).unwrap();
287            let values = map! {
288                [if let Some(v) = generation] "wifi_generation" => Value::text(v.as_str(config.wifi_generation_superscript).into()),
289            };
290            let text: String = template
291                .render(&values, &Default::default())
292                .unwrap()
293                .into_iter()
294                .map(|fragment| fragment.text)
295                .collect();
296            assert_eq!(text, expected);
297        }
298    }
299
300    #[test]
301    fn plan_declares_device_icon_set_on_every_rendering_state() {
302        let plan = prepare(&Config::default()).unwrap();
303        let ids: Vec<_> = plan.outputs().map(|o| o.id()).collect();
304        assert_eq!(ids, ["format", "inactive", "missing"]);
305
306        for id in ["format", "inactive"] {
307            let output = plan.output(id).unwrap();
308            let choices = output.output().choices_for("icon").unwrap();
309            for icon in NetDevice::ALL_ICONS {
310                assert!(choices.permits(icon), "{id} must permit {icon}");
311            }
312            assert!(!choices.permits("net_up"));
313        }
314
315        // `missing` renders a bare format and sets no values at all.
316        let missing = plan.output("missing").unwrap();
317        assert_eq!(missing.output().icon_placeholders().count(), 0);
318    }
319
320    #[test]
321    fn every_configured_format_becomes_an_output() {
322        let plan = prepare(&Config::default()).unwrap();
323        assert!(plan.output("format2").is_err());
324
325        let config: Config = toml::from_str(r#"format = [" $icon ", " $icon $device "]"#).unwrap();
326        let plan = prepare(&config).unwrap();
327        let ids: Vec<_> = plan.outputs().map(|o| o.id()).collect();
328        // The extra states stay alongside the per-format outputs.
329        assert_eq!(ids, ["format", "format2", "inactive", "missing"]);
330
331        let second = plan.output("format2").unwrap();
332        assert!(second.format().contains_key("device"));
333        let choices = second.output().choices_for("icon").unwrap();
334        assert!(choices.permits("net_wireless"));
335    }
336
337    #[test]
338    fn the_arrows_in_the_default_format_are_part_of_the_icon_surface() {
339        // They are `^icon_*` tokens rather than icon values, so they are not
340        // declared placeholders — but the block still draws them.
341        let plan = prepare(&Config::default()).unwrap();
342        let format = plan.output("format").unwrap();
343        assert_eq!(
344            format.output().static_icons(),
345            ["net_down", "net_up"],
346            "the default format's arrows must be visible to an inspector"
347        );
348        // The states that render no format icons say so.
349        for id in ["inactive", "missing"] {
350            let output = plan.output(id).unwrap();
351            assert!(output.output().static_icons().is_empty(), "{id}");
352        }
353    }
354
355    #[test]
356    fn every_chooser_icon_is_declared() {
357        // Exercise every branch of the runtime icon chooser and check the
358        // result against the declared set, so the two cannot drift apart.
359        let mut seen = Vec::new();
360        for is_wireless in [false, true] {
361            for tun_wg_ppp in [false, true] {
362                for name in ["lo", "eth0", "tun0", "wlan0"] {
363                    let icon = NetDevice::icon_for(is_wireless, tun_wg_ppp, name);
364                    assert!(
365                        NetDevice::ALL_ICONS.contains(&icon),
366                        "chooser returned undeclared icon {icon}"
367                    );
368                    if !seen.contains(&icon) {
369                        seen.push(icon);
370                    }
371                }
372            }
373        }
374        // ...and every declared name is actually reachable.
375        assert_eq!(seen.len(), NetDevice::ALL_ICONS.len());
376    }
377
378    #[test]
379    fn test_push_to_hist() {
380        let mut hist = [0; 4];
381        assert_eq!(&hist, &[0, 0, 0, 0]);
382        push_to_hist(&mut hist, 1);
383        assert_eq!(&hist, &[0, 0, 0, 1]);
384        push_to_hist(&mut hist, 3);
385        assert_eq!(&hist, &[0, 0, 1, 3]);
386        push_to_hist(&mut hist, 0);
387        assert_eq!(&hist, &[0, 1, 3, 0]);
388        push_to_hist(&mut hist, 10);
389        assert_eq!(&hist, &[1, 3, 0, 10]);
390        push_to_hist(&mut hist, 2);
391        assert_eq!(&hist, &[3, 0, 10, 2]);
392    }
393}