Skip to main content

fritz_core/
firmware.rs

1//! The firmware of a device: the installed version, the update the device
2//! offers, automatic updates and the last update, read with the getters of
3//! `DeviceInfo` and `UserInterface` only.
4//!
5//! Checking for a new version (`X_AVM-DE_CheckUpdate`) is a change and not
6//! done here. The download URL of an update is never read into the result,
7//! since it may carry tokens.
8
9use serde::Serialize;
10
11use crate::generic::Error;
12use crate::read::{Reader, Values};
13
14/// The service with the update state.
15const SERVICE: &str = "UserInterface";
16
17/// Whether the device offers an update.
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "lowercase")]
20pub enum State {
21    /// The device offers an update.
22    Available,
23    /// The device says that there is no update.
24    #[serde(rename = "none")]
25    NoUpdate,
26    /// The device does not tell, for example because its last check failed
27    /// or the user may not read the state.
28    #[default]
29    Unknown,
30    /// The device has no service for updates, like some repeaters.
31    Unsupported,
32}
33
34/// The firmware and its updates. Values the device does not report are
35/// `None`.
36#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
37pub struct Firmware {
38    pub state: State,
39    /// The installed version, like `285.08.25`.
40    pub installed: Option<String>,
41    /// The kind of build of the installed version, like `Release`.
42    pub build_type: Option<String>,
43    /// The version the device offers.
44    pub offered: Option<String>,
45    /// The page with the changes of the offered version.
46    pub info_url: Option<String>,
47    /// The state of the update process, like `Stopped`, `UpdateAvailable`
48    /// or `Error`.
49    pub update_state: Option<String>,
50    /// What the device does with new versions by itself: `off`, `check`
51    /// (only notifies), `important` or `all`.
52    pub auto_update: Option<String>,
53    /// When the last update was installed.
54    pub last_update_time: Option<String>,
55    /// Whether the last update worked: `succeeded` or `failed`.
56    pub last_update_result: Option<String>,
57    /// The version before the last update.
58    pub previous_version: Option<String>,
59}
60
61/// Reads the firmware state.
62///
63/// # Errors
64///
65/// The errors of reading other than missing parts, see
66/// [`Reader::try_read`].
67pub async fn firmware(reader: &mut Reader) -> Result<Firmware, Error> {
68    let info = reader.try_read("DeviceInfo1", "GetInfo", &[]).await?;
69    let info = info.unwrap_or_default();
70    if reader.services(SERVICE).is_empty() {
71        return Ok(Firmware {
72            state: State::Unsupported,
73            installed: info.text("NewSoftwareVersion"),
74            ..Firmware::default()
75        });
76    }
77    let interface = reader.try_read("UserInterface1", "GetInfo", &[]).await?;
78    let getter = reader.try_read("UserInterface1", "X_AVM-DE_GetInfo", &[]);
79    let extended = getter.await?.unwrap_or_default();
80    Ok(build(&info, interface.as_ref(), &extended))
81}
82
83/// The firmware from the answers of `DeviceInfo:GetInfo`,
84/// `UserInterface:GetInfo`, if the device gave one, and
85/// `UserInterface:X_AVM-DE_GetInfo`.
86fn build(info: &Values, interface: Option<&Values>, extended: &Values) -> Firmware {
87    let state = interface.map_or(State::Unknown, state);
88    let interface = interface.cloned().unwrap_or_default();
89    let installed = info
90        .text("NewSoftwareVersion")
91        .or_else(|| extended.text("NewX_AVM-DE_CurrentFwVersion"));
92    // Devices that never updated report a time in the year 1.
93    let time = extended.text("NewX_AVM-DE_UpdateTime");
94    let result = extended.text("NewX_AVM-DE_UpdateSuccessful");
95    // Like `285.08.22,129542`: the version and its build number.
96    let previous = extended.text("NewX_AVM-DE_LastFwVersion");
97    Firmware {
98        state,
99        installed,
100        build_type: interface.text("NewX_AVM-DE_BuildType"),
101        offered: interface.text("NewX_AVM-DE_Version"),
102        info_url: interface.text("NewX_AVM-DE_InfoURL"),
103        update_state: interface.text("NewX_AVM-DE_UpdateState"),
104        auto_update: extended.text("NewX_AVM-DE_AutoUpdateMode"),
105        last_update_time: time.filter(|t| !t.starts_with("0001-")),
106        last_update_result: result.filter(|r| r != "unknown"),
107        previous_version: previous.map(|v| v.split(',').next().unwrap_or_default().to_owned()),
108    }
109}
110
111/// Whether an update is offered, by the flag `NewUpgradeAvailable` and the
112/// update state. A failed check makes it unknown, never `none`.
113fn state(interface: &Values) -> State {
114    let flag = interface.flag("NewUpgradeAvailable");
115    let update = interface.get("NewX_AVM-DE_UpdateState");
116    if flag == Some(true) || update == Some("UpdateAvailable") {
117        State::Available
118    } else if matches!(update, Some("Error" | "Unknown")) {
119        State::Unknown
120    } else if flag == Some(false) || update == Some("NoUpdate") {
121        State::NoUpdate
122    } else {
123        State::Unknown
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::read::values;
131
132    #[test]
133    fn tells_the_state() {
134        for (flag, update, expected) in [
135            ("1", "Stopped", State::Available),
136            ("0", "UpdateAvailable", State::Available),
137            ("0", "Stopped", State::NoUpdate),
138            ("", "NoUpdate", State::NoUpdate),
139            ("0", "Error", State::Unknown),
140            ("", "Unknown", State::Unknown),
141            ("", "Stopped", State::Unknown),
142            ("", "", State::Unknown),
143        ] {
144            let interface = values(&[
145                ("NewUpgradeAvailable", flag),
146                ("NewX_AVM-DE_UpdateState", update),
147            ]);
148            assert_eq!(state(&interface), expected, "{flag} {update}");
149        }
150    }
151
152    #[test]
153    fn reports_missing_answers_as_unknown() {
154        let firmware = build(&Values::default(), None, &Values::default());
155        assert_eq!(firmware, Firmware::default());
156        assert_eq!(firmware.state, State::Unknown);
157        let json = serde_json::to_value(&firmware).unwrap();
158        assert_eq!(json["state"], "unknown");
159        // All fields, with explicit nulls.
160        assert_eq!(json.as_object().unwrap().len(), 10);
161        assert!(json["offered"].is_null());
162    }
163
164    #[test]
165    fn leaves_out_placeholders() {
166        let extended = values(&[
167            ("NewX_AVM-DE_CurrentFwVersion", "134.07.32"),
168            ("NewX_AVM-DE_UpdateTime", "0001-01-01T00:00:00"),
169            ("NewX_AVM-DE_UpdateSuccessful", "unknown"),
170            ("NewX_AVM-DE_LastFwVersion", "134.07.31"),
171        ]);
172        let firmware = build(&Values::default(), None, &extended);
173        assert_eq!(firmware.installed.as_deref(), Some("134.07.32"));
174        assert_eq!(firmware.last_update_time, None);
175        assert_eq!(firmware.last_update_result, None);
176        assert_eq!(firmware.previous_version.as_deref(), Some("134.07.31"));
177    }
178
179    #[test]
180    fn names_the_states_in_json() {
181        let names: Vec<String> = [
182            State::Available,
183            State::NoUpdate,
184            State::Unknown,
185            State::Unsupported,
186        ]
187        .iter()
188        .map(|s| serde_json::to_string(s).unwrap())
189        .collect();
190        assert_eq!(
191            names,
192            [
193                "\"available\"",
194                "\"none\"",
195                "\"unknown\"",
196                "\"unsupported\""
197            ]
198        );
199    }
200}