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
//! Implements sensor reading value.

use crate::Result;
use failure::format_err;
use serde::{Deserialize, Serialize};
use std::fmt::{Display, Formatter};

/// Sensor reading value.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
pub enum Value {
    /// Generic counter.
    Counter(u64),
    /// Size in [bytes](https://en.wikipedia.org/wiki/Byte).
    Size(u64),
    /// [Plain text](https://en.wikipedia.org/wiki/Plain_text).
    Text(String),
    /// [Celsius](https://en.wikipedia.org/wiki/Celsius) temperature.
    Celsius(f64),
    /// [Beaufort](https://en.wikipedia.org/wiki/Beaufort_scale) wind speed.
    Bft(u32),
    /// Wind direction.
    WindDirection(PointOfTheCompass),
    /// Length in [metres](https://en.wikipedia.org/wiki/Metre).
    Metres(f64),
    /// [Relative humidity](https://en.wikipedia.org/wiki/Relative_humidity) in percents.
    Rh(f64),
    /// Image URL.
    ImageUrl(String),
}

impl markup::Render for Value {
    /// Render value in HTML.
    fn render(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{} {}", self.icon().unwrap_or(""), self)
    }
}

impl Value {
    /// Get [CSS color class](https://bulma.io/documentation/modifiers/color-helpers/).
    pub fn class(&self) -> &str {
        match *self {
            Value::Text(_) | Value::Counter(_) | Value::Size(_) | Value::Metres(_) | Value::ImageUrl(_) => "is-light",
            Value::Bft(number) => match number {
                0 => "is-light",
                1..=3 => "is-success",
                4..=5 => "is-warning",
                _ => "is-danger",
            },
            Value::Celsius(value) => match value {
                _ if value < -5.0 => "is-link",
                _ if value < 5.0 => "is-info",
                _ if value < 15.0 => "is-primary",
                _ if value < 25.0 => "is-success",
                _ if value < 30.0 => "is-warning",
                _ => "is-danger",
            },
            Value::WindDirection(_) => "is-light",
            Value::Rh(value) => match value {
                _ if value < 25.0 => "is-link",
                _ if value < 30.0 => "is-info",
                _ if value < 45.0 => "is-primary",
                _ if value < 55.0 => "is-success",
                _ if value < 60.0 => "is-warning",
                _ => "is-danger",
            },
        }
    }

    /// Get [Font Awesome](https://fontawesome.com) icon tag.
    pub fn icon(&self) -> Result<&'static str> {
        match *self {
            Value::Counter(_) => Ok(r#"<i class="fas fa-sort-numeric-up-alt"></i>"#),
            Value::Size(_) => Ok(r#"<i class="far fa-save"></i>"#),
            Value::Text(_) => Ok(r#"<i class="fas fa-quote-left"></i>"#),
            Value::Celsius(_) => Ok(r#"<i class="fas fa-thermometer-half"></i>"#),
            Value::Bft(_) => Ok(r#"<i class="fas fa-wind"></i>"#),
            Value::WindDirection(_) => Ok(r#"<i class="fas fa-wind"></i>"#),
            Value::Rh(_) => Ok(r#"<i class="fas fa-water"></i>"#),
            Value::Metres(_) => Ok(r#"<i class="fas fa-ruler"></i>"#),
            _ => Err(format_err!("value has no icon")),
        }
    }

    /// Get whether value could be rendered inline.
    pub fn is_inline(&self) -> bool {
        match self {
            Value::ImageUrl(_) => false,
            _ => true,
        }
    }
}

impl std::fmt::Display for Value {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            Value::Counter(count) => write!(f, r"{} times", count),
            Value::Size(size) => f.write_str(&human_format(*size as f64, "B")),
            Value::Text(ref string) => write!(f, r"{}", string),
            Value::Celsius(degrees) => write!(f, r"{:.1} ℃", degrees),
            Value::Bft(bft) => write!(f, r"{} BFT", bft),
            Value::WindDirection(point) => write!(f, r"{}", point),
            Value::Rh(percent) => write!(f, r"{}%", percent),
            Value::Metres(metres) => f.write_str(&human_format(*metres, "m")),
            Value::ImageUrl(url) => write!(f, r#"<img src="{}">"#, url),
        }
    }
}

/// [Points of the compass](https://en.wikipedia.org/wiki/Points_of_the_compass).
#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq)]
pub enum PointOfTheCompass {
    /// N
    North,
    /// NNE
    NorthNortheast,
    /// NE
    Northeast,
    /// ENE
    EastNortheast,
    /// E
    East,
    /// ESE
    EastSoutheast,
    /// SE
    Southeast,
    /// SSE
    SouthSoutheast,
    /// S
    South,
    /// SSW
    SouthSouthwest,
    /// SW
    Southwest,
    /// WSW
    WestSouthwest,
    /// W
    West,
    /// WNW
    WestNorthwest,
    /// NW
    Northwest,
    /// NNW
    NorthNorthwest,
}

impl Display for PointOfTheCompass {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            PointOfTheCompass::North => write!(f, "North"),
            PointOfTheCompass::NorthNortheast => write!(f, "North-northeast"),
            PointOfTheCompass::Northeast => write!(f, "Northeast"),
            PointOfTheCompass::EastNortheast => write!(f, "East-northeast"),
            PointOfTheCompass::East => write!(f, "East"),
            // TODO
            PointOfTheCompass::SouthSouthwest => write!(f, "South-southwest"),
            // TODO
            _ => write!(f, "{:?}", self),
        }
    }
}

/// Format value to keep only 3 digits before the decimal point.
fn human_format(value: f64, unit: &str) -> String {
    match value {
        _ if value < 1e-21 => format!("{:.1} y{}", value * 1e24, unit),
        _ if value < 1e-18 => format!("{:.1} z{}", value * 1e21, unit),
        _ if value < 1e-15 => format!("{:.1} a{}", value * 1e18, unit),
        _ if value < 1e-12 => format!("{:.1} f{}", value * 1e15, unit),
        _ if value < 1e-9 => format!("{:.1} p{}", value * 1e12, unit),
        _ if value < 1e-6 => format!("{:.1} n{}", value * 1e9, unit),
        _ if value < 1e-3 => format!("{:.1} µ{}", value * 1e6, unit),
        _ if value < 1.0 => format!("{:.1} m{}", value * 1e3, unit),
        _ if value < 1e3 => format!("{:.1} {}", value, unit),
        _ if value < 1e6 => format!("{:.1} k{}", value * 1e-3, unit),
        _ if value < 1e9 => format!("{:.1} M{}", value * 1e-6, unit),
        _ if value < 1e12 => format!("{:.1} G{}", value * 1e-9, unit),
        _ if value < 1e15 => format!("{:.1} T{}", value * 1e-12, unit),
        _ if value < 1e18 => format!("{:.1} P{}", value * 1e-15, unit),
        _ if value < 1e21 => format!("{:.1} E{}", value * 1e-18, unit),
        _ if value < 1e24 => format!("{:.1} Z{}", value * 1e-21, unit),
        _ => format!("{:.1} Y{}", value * 1e-24, unit),
    }
}

#[cfg(test)]
mod tests {
    use crate::value::human_format;

    #[test]
    fn metres() {
        assert_eq!(human_format(100.0, "m"), "100.0 m");
    }

    #[test]
    fn megametres() {
        assert_eq!(human_format(12.756e6, "m"), "12.8 Mm");
    }

    #[test]
    fn millimetres() {
        assert_eq!(human_format(0.005, "m"), "5.0 mm");
    }
}