Skip to main content

fritz_core/
powerline.rs

1//! The powerline adapters a device knows, read with the getters of
2//! `X_AVM-DE_Homeplug` only.
3//!
4//! Updating an adapter (`DeviceDoUpdate`) is a change and not done here.
5//! Names are untrusted strings from the device.
6
7use serde::Serialize;
8
9use crate::generic::Error;
10use crate::read::{Reader, Values};
11
12/// The service with the powerline adapters.
13const SERVICE: &str = "X_AVM-DE_Homeplug";
14
15/// The most adapters read.
16pub const MAX_ADAPTERS: u32 = 100;
17
18/// The powerline adapters of a device.
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
20pub struct Powerline {
21    /// Whether the device has the service for powerline adapters.
22    pub supported: bool,
23    pub adapters: Vec<Adapter>,
24}
25
26/// A powerline adapter. Values the device does not report are `None`.
27#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
28pub struct Adapter {
29    pub name: Option<String>,
30    pub model: Option<String>,
31    pub mac: Option<String>,
32    /// Whether the adapter is connected.
33    pub active: bool,
34    /// Whether the device offers a firmware update for the adapter.
35    pub update_available: Option<bool>,
36    /// Whether the last update of the adapter worked: `succeeded` or
37    /// `failed`.
38    pub update_result: Option<String>,
39}
40
41/// Reads the powerline adapters.
42///
43/// # Errors
44///
45/// The errors of reading other than missing parts, see
46/// [`Reader::try_read`].
47pub async fn powerline(reader: &mut Reader) -> Result<Powerline, Error> {
48    if reader.services(SERVICE).is_empty() {
49        return Ok(Powerline::default());
50    }
51    let entries = reader
52        .entries(
53            "X_AVM-DE_Homeplug1",
54            ("GetNumberOfDeviceEntries", "NewNumberOfEntries"),
55            ("GetGenericDeviceEntry", "NewIndex"),
56            MAX_ADAPTERS,
57        )
58        .await?
59        .map_or_else(Vec::new, |(_, entries)| entries);
60    Ok(Powerline {
61        supported: true,
62        adapters: entries.iter().map(adapter).collect(),
63    })
64}
65
66/// An adapter from the answer of `GetGenericDeviceEntry`.
67fn adapter(entry: &Values) -> Adapter {
68    Adapter {
69        name: entry.text("NewName"),
70        model: entry.text("NewModel"),
71        mac: entry.text("NewMACAddress"),
72        active: entry.flag("NewActive").unwrap_or_default(),
73        update_available: entry.flag("NewUpdateAvailable"),
74        update_result: entry.text("NewUpdateSuccessful").filter(|r| r != "unknown"),
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81
82    #[test]
83    fn reads_an_entry() {
84        let entry = Values(
85            [
86                ("NewMACAddress", "AA:BB:CC:00:00:01"),
87                ("NewActive", "1"),
88                ("NewName", "Office"),
89                ("NewModel", "FRITZ!Powerline 1260"),
90                ("NewUpdateAvailable", "0"),
91                ("NewUpdateSuccessful", "unknown"),
92            ]
93            .iter()
94            .map(|(n, v)| ((*n).to_owned(), (*v).to_owned()))
95            .collect(),
96        );
97        assert_eq!(
98            adapter(&entry),
99            Adapter {
100                name: Some("Office".to_owned()),
101                model: Some("FRITZ!Powerline 1260".to_owned()),
102                mac: Some("AA:BB:CC:00:00:01".to_owned()),
103                active: true,
104                update_available: Some(false),
105                update_result: None,
106            }
107        );
108        let json = serde_json::to_value(adapter(&Values::default())).unwrap();
109        // All fields, with explicit nulls.
110        assert_eq!(json.as_object().unwrap().len(), 6);
111        assert!(json["name"].is_null());
112        assert_eq!(json["active"], false);
113    }
114}