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
//! Ping, download, and upload speeds
//!
//! This block which requires [`speedtest-cli`](https://github.com/sivel/speedtest-cli).
//!
//! # Configuration
//!
//! Key | Values | Default
//! ----|--------|--------
//! `format` | A string to customise the output of this block. See below for available placeholders. | `" ^icon_ping $ping ^icon_net_down $speed_down ^icon_net_up $speed_up "`
//! `interval` | Update interval in seconds | `1800`
//!
//! Placeholder | Value | Type | Unit
//! -------------|----------------|--------|---------------
//! `ping` | Ping delay | Number | Seconds
//! `speed_down` | Download speed | Number | Bits per second
//! `speed_up` | Upload speed | Number | Bits per second
//!
//! # Example
//!
//! Show only ping (with an icon)
//!
//! ```toml
//! [[block]]
//! block = "speedtest"
//! interval = 1800
//! format = " ^icon_ping $ping "
//! ```
//!
//! Hide ping and display speed in bytes per second each using 4 characters (without icons)
//!
//! ```toml
//! [[block]]
//! block = "speedtest"
//! interval = 1800
//! format = " $speed_down.eng(w:4,u:B) $speed_up(w:4,u:B) "
//! ```
//!
//! # Icons Used
//! - `ping`
//! - `net_down`
//! - `net_up`
use super::prelude::*;
use tokio::process::Command;
#[derive(Deserialize, Debug, SmartDefault)]
#[serde(deny_unknown_fields, default)]
pub struct Config {
pub format: FormatConfig,
#[default(1800.into())]
pub interval: Seconds,
}
pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
let format = config
.format
.with_default(" ^icon_ping $ping ^icon_net_down $speed_down ^icon_net_up $speed_up ")?;
let mut command = Command::new("speedtest-cli");
command.arg("--json");
loop {
let output = command
.output()
.await
.error("failed to run 'speedtest-cli'")?
.stdout;
let output =
std::str::from_utf8(&output).error("'speedtest-cli' produced non-UTF8 output")?;
let output: SpeedtestCliOutput =
serde_json::from_str(output).error("'speedtest-cli' produced wrong JSON")?;
let mut widget = Widget::new().with_format(format.clone());
widget.set_values(map! {
"ping" => Value::seconds(output.ping * 1e-3),
"speed_down" => Value::bits(output.download),
"speed_up" => Value::bits(output.upload),
});
api.set_widget(widget)?;
select! {
_ = sleep(config.interval.0) => (),
_ = api.wait_for_update_request() => (),
}
}
}
#[derive(Deserialize, Debug, Clone, Copy)]
struct SpeedtestCliOutput {
/// Download speed in bits per second
download: f64,
/// Upload speed in bits per second
upload: f64,
/// Ping time in ms
ping: f64,
}