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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use core::fmt;
use std::collections::HashSet;
use std::convert::TryFrom;
use std::time::Duration;

/// Well-known variable keys for NUT UPS devices.
///
/// List retrieved from: https://networkupstools.org/docs/user-manual.chunked/apcs01.html
pub mod key {
    /// Device model.
    pub const DEVICE_MODEL: &str = "device.model";
    /// Device manufacturer.
    pub const DEVICE_MANUFACTURER: &str = "device.mfr";
    /// Device serial number.
    pub const DEVICE_SERIAL: &str = "device.serial";
    /// Device type.
    pub const DEVICE_TYPE: &str = "device.type";
    /// Device description.
    pub const DEVICE_DESCRIPTION: &str = "device.description";
    /// Device administrator name.
    pub const DEVICE_CONTACT: &str = "device.contact";
    /// Device physical location.
    pub const DEVICE_LOCATION: &str = "device.location";
    /// Device part number.
    pub const DEVICE_PART: &str = "device.part";
    /// Device MAC address.
    pub const DEVICE_MAC_ADDRESS: &str = "device.macaddr";
    /// Device uptime.
    pub const DEVICE_UPTIME: &str = "device.uptime";
}

/// Well-known variables for NUT UPS devices.
///
/// List retrieved from: https://networkupstools.org/docs/user-manual.chunked/apcs01.html
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum Variable {
    /// Device model.
    DeviceModel(String),
    /// Device manufacturer.
    DeviceManufacturer(String),
    /// Device serial number.
    DeviceSerial(String),
    /// Device type.
    DeviceType(DeviceType),
    /// Device description.
    DeviceDescription(String),
    /// Device administrator name.
    DeviceContact(String),
    /// Device physical location.
    DeviceLocation(String),
    /// Device part number.
    DevicePart(String),
    /// Device MAC address.
    DeviceMacAddress(String),
    /// Device uptime.
    DeviceUptime(Duration),

    /// Any other variable. Value is a tuple of (key, value).
    Other((String, String)),
}

impl Variable {
    /// Parses a variable from its key and value.
    pub fn parse(name: &str, value: String) -> Variable {
        use self::key::*;

        match name {
            DEVICE_MODEL => Self::DeviceModel(value),
            DEVICE_MANUFACTURER => Self::DeviceManufacturer(value),
            DEVICE_SERIAL => Self::DeviceSerial(value),
            DEVICE_TYPE => Self::DeviceType(DeviceType::from(value)),
            DEVICE_DESCRIPTION => Self::DeviceDescription(value),
            DEVICE_CONTACT => Self::DeviceContact(value),
            DEVICE_LOCATION => Self::DeviceLocation(value),
            DEVICE_PART => Self::DevicePart(value),
            DEVICE_MAC_ADDRESS => Self::DeviceMacAddress(value),
            DEVICE_UPTIME => Self::DeviceUptime(Duration::from_secs(
                value.parse().expect("invalid uptime value"),
            )),

            _ => Self::Other((name.into(), value)),
        }
    }

    /// Returns the NUT name of the variable.
    pub fn name(&self) -> &str {
        use self::key::*;
        match self {
            Self::DeviceModel(_) => DEVICE_MODEL,
            Self::DeviceManufacturer(_) => DEVICE_MANUFACTURER,
            Self::DeviceSerial(_) => DEVICE_SERIAL,
            Self::DeviceType(_) => DEVICE_TYPE,
            Self::DeviceDescription(_) => DEVICE_DESCRIPTION,
            Self::DeviceContact(_) => DEVICE_CONTACT,
            Self::DeviceLocation(_) => DEVICE_LOCATION,
            Self::DevicePart(_) => DEVICE_PART,
            Self::DeviceMacAddress(_) => DEVICE_MAC_ADDRESS,
            Self::DeviceUptime(_) => DEVICE_UPTIME,
            Self::Other((name, _)) => name.as_str(),
        }
    }

    /// Returns the value of the NUT variable.
    pub fn value(&self) -> String {
        match self {
            Self::DeviceModel(value) => value.clone(),
            Self::DeviceManufacturer(value) => value.clone(),
            Self::DeviceSerial(value) => value.clone(),
            Self::DeviceType(value) => value.to_string(),
            Self::DeviceDescription(value) => value.clone(),
            Self::DeviceContact(value) => value.clone(),
            Self::DeviceLocation(value) => value.clone(),
            Self::DevicePart(value) => value.clone(),
            Self::DeviceMacAddress(value) => value.clone(),
            Self::DeviceUptime(value) => value.as_secs().to_string(),
            Self::Other((_, value)) => value.clone(),
        }
    }
}

impl fmt::Display for Variable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.name(), self.value())
    }
}

/// NUT device type.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DeviceType {
    /// UPS (Uninterruptible Power Supply)
    Ups,
    /// PDU (Power Distribution Unit)
    Pdu,
    /// SCD (Solar Controller Device)
    Scd,
    /// PSU (Power Supply Unit)
    Psu,
    /// ATS (Automatic Transfer Switch)
    Ats,
    /// Other device type.
    Other(String),
}

impl DeviceType {
    /// Convert from string.
    pub fn from(v: String) -> DeviceType {
        match v.as_str() {
            "ups" => Self::Ups,
            "pdu" => Self::Pdu,
            "scd" => Self::Scd,
            "psu" => Self::Psu,
            "ats" => Self::Ats,
            _ => Self::Other(v),
        }
    }
}

impl fmt::Display for DeviceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ups => write!(f, "ups"),
            Self::Pdu => write!(f, "pdu"),
            Self::Scd => write!(f, "scd"),
            Self::Psu => write!(f, "psu"),
            Self::Ats => write!(f, "ats"),
            Self::Other(val) => write!(f, "other({})", val),
        }
    }
}

/// NUT Variable type
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[allow(dead_code)]
pub(crate) enum VariableType {
    /// A mutable variable (`RW`).
    Rw,
    /// An enumerated type, which supports a few specific values (`ENUM`).
    Enum,
    /// A string with a maximum size (`STRING:n`).
    String(usize),
    /// A numeric type, either integer or float, comprised in the range defined by `LIST RANGE`.
    Range,
    /// A simple numeric value, either integer or float.
    Number,
}

impl TryFrom<&str> for VariableType {
    type Error = crate::ClientError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "RW" => Ok(Self::Rw),
            "ENUM" => Ok(Self::Enum),
            "RANGE" => Ok(Self::Range),
            "NUMBER" => Ok(Self::Number),
            other => {
                if other.starts_with("STRING:") {
                    let size = other
                        .splitn(2, ':')
                        .nth(1)
                        .map(|s| s.parse().ok())
                        .flatten()
                        .ok_or_else(|| {
                            crate::ClientError::Nut(crate::NutError::Generic(
                                "Invalid STRING definition".into(),
                            ))
                        })?;
                    Ok(Self::String(size))
                } else {
                    Err(crate::ClientError::Nut(crate::NutError::Generic(format!(
                        "Unrecognized variable type: {}",
                        value
                    ))))
                }
            }
        }
    }
}

/// NUT Variable definition.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct VariableDefinition(String, HashSet<VariableType>);

impl VariableDefinition {
    /// The name of this variable.
    pub fn name(&self) -> &str {
        self.0.as_str()
    }

    /// Whether this variable is mutable.
    pub fn is_mutable(&self) -> bool {
        self.1.contains(&VariableType::Rw)
    }

    /// Whether this variable is an enumerated type.
    pub fn is_enum(&self) -> bool {
        self.1.contains(&VariableType::Enum)
    }

    /// Whether this variable is a String type
    pub fn is_string(&self) -> bool {
        self.1.iter().any(|t| matches!(t, VariableType::String(_)))
    }

    /// Whether this variable is a numeric type,
    /// either integer or float, comprised in a range
    pub fn is_range(&self) -> bool {
        self.1.contains(&VariableType::Range)
    }

    /// Whether this variable is a numeric type, either integer or float.
    pub fn is_number(&self) -> bool {
        self.1.contains(&VariableType::Number)
    }

    /// Returns the max string length, if applicable.
    pub fn get_string_length(&self) -> Option<usize> {
        self.1.iter().find_map(|t| match t {
            VariableType::String(n) => Some(*n),
            _ => None,
        })
    }
}

impl<A: ToString> TryFrom<(A, Vec<&str>)> for VariableDefinition {
    type Error = crate::ClientError;

    fn try_from(value: (A, Vec<&str>)) -> Result<Self, Self::Error> {
        Ok(VariableDefinition(
            value.0.to_string(),
            value
                .1
                .iter()
                .map(|s| VariableType::try_from(*s))
                .collect::<crate::Result<HashSet<VariableType>>>()?,
        ))
    }
}

/// A range of values for a variable.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct VariableRange(pub String, pub String);

#[cfg(test)]
mod tests {
    use std::iter::FromIterator;

    use super::*;

    #[test]
    fn test_parse_variable_definition() {
        assert_eq!(
            VariableDefinition::try_from(("var0", vec![])).unwrap(),
            VariableDefinition("var0".into(), HashSet::new())
        );

        assert_eq!(
            VariableDefinition::try_from(("var1", vec!["RW"])).unwrap(),
            VariableDefinition(
                "var1".into(),
                HashSet::from_iter(vec![VariableType::Rw].into_iter())
            )
        );

        assert_eq!(
            VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"])).unwrap(),
            VariableDefinition(
                "var1".into(),
                HashSet::from_iter(vec![VariableType::Rw, VariableType::String(123)].into_iter())
            )
        );

        assert!(
            VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"]))
                .unwrap()
                .is_mutable()
        );
        assert!(
            VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"]))
                .unwrap()
                .is_string()
        );
        assert!(
            !VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"]))
                .unwrap()
                .is_enum()
        );
        assert!(
            !VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"]))
                .unwrap()
                .is_number()
        );
        assert!(
            !VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"]))
                .unwrap()
                .is_range()
        );
        assert_eq!(
            VariableDefinition::try_from(("var1", vec!["RW", "STRING:123"]))
                .unwrap()
                .get_string_length(),
            Some(123)
        );
    }
}