Skip to main content

fritz_core/
smarthome.rs

1//! Smart Home devices, read through the REST API of the web interface
2//! (FRITZ!OS 8.20 and later) with a [`Session`].
3//!
4//! The API describes devices, like a plug, and their units, like the switch
5//! and the thermometer of the plug. Each unit has interfaces with the
6//! values. [`devices`] turns this into a compact list: each device with its
7//! units and their current values, in common units of measurement. Values
8//! the device does not report as valid are left out.
9
10use serde::{Deserialize, Serialize};
11
12use crate::session::{Error, Session};
13
14pub mod history;
15
16/// The overview of all devices, units and groups.
17pub const OVERVIEW: &str = "/api/v0/smarthome/overview";
18
19/// A Smart Home device.
20#[derive(Debug, Clone, PartialEq, Serialize)]
21pub struct Device {
22    /// The actor identification number, like `11630 0015376`.
23    pub ain: String,
24    pub name: String,
25    /// Like `FRITZ!Smart Energy 200`.
26    pub product: Option<String>,
27    /// `blind`, `control`, `lamp`, `other`, `sensor`, `socket` or
28    /// `thermostat`.
29    pub category: Option<String>,
30    pub firmware: Option<String>,
31    /// Whether the device is reachable. If not, the values are the last
32    /// known ones.
33    pub connected: bool,
34    /// The charge of the battery in percent, for devices with one.
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub battery: Option<u8>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub battery_low: Option<bool>,
39    pub units: Vec<Unit>,
40}
41
42/// A function of a device, like a switch, and its values.
43#[derive(Debug, Clone, Default, PartialEq, Serialize)]
44pub struct Unit {
45    pub ain: String,
46    pub name: String,
47    /// Like `avmPlugSocket`, `avmThermostat` or `dimmableColorBulb`.
48    pub kind: Option<String>,
49    /// Whether a switch is on.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub on: Option<bool>,
52    /// The measured temperature in °C.
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub temperature: Option<f64>,
55    /// The target of a thermostat.
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub target: Option<Target>,
58    /// The power in W.
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub power: Option<f64>,
61    /// The energy in Wh since the measurement started.
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub energy: Option<u64>,
64    /// The voltage in V.
65    #[serde(skip_serializing_if = "Option::is_none")]
66    pub voltage: Option<f64>,
67    /// The level of a dimmer or a blind in percent.
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub level: Option<u8>,
70    /// The relative humidity in percent.
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub humidity: Option<u8>,
73    /// Active alerts, like `open` or `smoke`.
74    #[serde(skip_serializing_if = "Vec::is_empty")]
75    pub alerts: Vec<String>,
76}
77
78/// The target of a thermostat: a temperature in °C, or `on` or `off`.
79#[derive(Debug, Clone, PartialEq, Serialize)]
80#[serde(untagged)]
81pub enum Target {
82    Celsius(f64),
83    Mode(String),
84}
85
86/// Reads the devices, ordered by name.
87///
88/// # Errors
89///
90/// The errors of the request, and [`Error::Invalid`] if the answer is not
91/// an overview.
92pub async fn devices(session: &Session) -> Result<Vec<Device>, Error> {
93    parse(&session.get(OVERVIEW).await?)
94}
95
96/// The devices of an overview, ordered by name.
97///
98/// # Errors
99///
100/// [`Error::Invalid`] if `json` is not an overview.
101pub fn parse(json: &str) -> Result<Vec<Device>, Error> {
102    let overview: Overview = serde_json::from_str(json).map_err(|e| Error::Invalid {
103        what: "the Smart Home API",
104        reason: e.to_string(),
105    })?;
106    let mut devices: Vec<Device> = overview
107        .devices
108        .into_iter()
109        .map(|device| Device {
110            units: device
111                .unit_uids
112                .iter()
113                .filter_map(|uid| overview.units.iter().find(|u| &u.uid == uid))
114                .map(RawUnit::summary)
115                .collect(),
116            ain: device.ain,
117            name: device.name,
118            product: device.product_name,
119            category: device.product_category,
120            firmware: device.firmware_version,
121            connected: device.is_connected,
122            battery: device.battery_value,
123            battery_low: device.is_battery_low,
124        })
125        .collect();
126    devices.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.ain.cmp(&b.ain)));
127    Ok(devices)
128}
129
130#[derive(Debug, Deserialize)]
131struct Overview {
132    #[serde(default)]
133    devices: Vec<RawDevice>,
134    #[serde(default)]
135    units: Vec<RawUnit>,
136}
137
138#[derive(Debug, Deserialize)]
139#[serde(rename_all = "camelCase")]
140struct RawDevice {
141    #[serde(default)]
142    ain: String,
143    #[serde(default)]
144    name: String,
145    product_name: Option<String>,
146    product_category: Option<String>,
147    firmware_version: Option<String>,
148    #[serde(default)]
149    is_connected: bool,
150    battery_value: Option<u8>,
151    is_battery_low: Option<bool>,
152    #[serde(default)]
153    unit_uids: Vec<String>,
154}
155
156#[derive(Debug, Deserialize)]
157#[serde(rename_all = "camelCase")]
158struct RawUnit {
159    #[serde(rename = "UID")]
160    uid: String,
161    #[serde(default)]
162    ain: String,
163    #[serde(default)]
164    name: String,
165    unit_type: Option<String>,
166    #[serde(default)]
167    interfaces: Interfaces,
168}
169
170impl RawUnit {
171    fn summary(&self) -> Unit {
172        let i = &self.interfaces;
173        Unit {
174            ain: self.ain.clone(),
175            name: self.name.clone(),
176            kind: self.unit_type.clone(),
177            on: valid(i.on_off.as_ref()).and_then(|v| v.active),
178            temperature: valid(i.temperature.as_ref()).and_then(|v| v.celsius),
179            target: valid(i.thermostat.as_ref())
180                .and_then(|v| v.set_point_temperature.as_ref())
181                .and_then(SetPoint::target),
182            power: valid(i.multimeter.as_ref())
183                .and_then(|v| v.power)
184                .map(|milliwatts| f64::from(milliwatts) / 1000.0),
185            energy: valid(i.multimeter.as_ref()).and_then(|v| v.energy),
186            voltage: valid(i.multimeter.as_ref())
187                .and_then(|v| v.voltage)
188                .map(|millivolts| f64::from(millivolts) / 1000.0),
189            level: valid(i.level_control.as_ref()).and_then(|v| v.level),
190            humidity: valid(i.humidity.as_ref()).and_then(|v| v.relative_humidity),
191            alerts: valid(i.alert.as_ref())
192                .map_or_default(|v| v.alerts.iter().filter(|a| *a != "none").cloned().collect()),
193        }
194    }
195}
196
197#[derive(Debug, Default, Deserialize)]
198struct Interfaces {
199    #[serde(rename = "onOffInterface")]
200    on_off: Option<Interface<OnOff>>,
201    #[serde(rename = "temperatureInterface")]
202    temperature: Option<Interface<Temperature>>,
203    #[serde(rename = "thermostatInterface")]
204    thermostat: Option<Interface<Thermostat>>,
205    #[serde(rename = "multimeterInterface")]
206    multimeter: Option<Interface<Multimeter>>,
207    #[serde(rename = "levelControlInterface")]
208    level_control: Option<Interface<Level>>,
209    #[serde(rename = "humidityInterface")]
210    humidity: Option<Interface<Humidity>>,
211    #[serde(rename = "alertInterface")]
212    alert: Option<Interface<Alert>>,
213}
214
215/// An interface with its state: `valid`, `unknown` or `notConnected`.
216#[derive(Debug, Deserialize)]
217struct Interface<T> {
218    state: Option<String>,
219    #[serde(flatten)]
220    values: T,
221}
222
223/// The values of an interface, if they are valid.
224fn valid<T>(interface: Option<&Interface<T>>) -> Option<&T> {
225    interface
226        .filter(|i| i.state.as_deref() == Some("valid"))
227        .map(|i| &i.values)
228}
229
230#[derive(Debug, Deserialize)]
231struct OnOff {
232    active: Option<bool>,
233}
234
235#[derive(Debug, Deserialize)]
236struct Temperature {
237    celsius: Option<f64>,
238}
239
240#[derive(Debug, Deserialize)]
241#[serde(rename_all = "camelCase")]
242struct Thermostat {
243    set_point_temperature: Option<SetPoint>,
244}
245
246#[derive(Debug, Deserialize)]
247struct SetPoint {
248    mode: String,
249    celsius: Option<f64>,
250}
251
252impl SetPoint {
253    fn target(&self) -> Option<Target> {
254        match (self.mode.as_str(), self.celsius) {
255            ("temperature", Some(celsius)) => Some(Target::Celsius(celsius)),
256            (mode @ ("on" | "off"), _) => Some(Target::Mode(mode.to_owned())),
257            _ => None,
258        }
259    }
260}
261
262#[derive(Debug, Deserialize)]
263struct Multimeter {
264    /// In mW.
265    power: Option<i32>,
266    /// In Wh.
267    energy: Option<u64>,
268    /// In mV.
269    voltage: Option<i32>,
270}
271
272#[derive(Debug, Deserialize)]
273struct Level {
274    level: Option<u8>,
275}
276
277#[derive(Debug, Deserialize)]
278#[serde(rename_all = "camelCase")]
279struct Humidity {
280    relative_humidity: Option<u8>,
281}
282
283#[derive(Debug, Deserialize)]
284struct Alert {
285    #[serde(default)]
286    alerts: Vec<String>,
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    const FIXTURE: &str = include_str!(concat!(
294        env!("CARGO_MANIFEST_DIR"),
295        "/../fritz-sim/fixtures/fritzbox-7690/8.25/api/v0/smarthome/overview.json"
296    ));
297
298    #[test]
299    fn reads_devices_and_their_units() {
300        let devices = parse(FIXTURE).unwrap();
301        let names: Vec<_> = devices.iter().map(|d| d.name.as_str()).collect();
302        assert_eq!(names, ["device-1", "device-2", "device-3", "device-4"]);
303
304        let plug = &devices[0];
305        assert_eq!(plug.product.as_deref(), Some("FRITZ!Smart Energy 200"));
306        assert_eq!(plug.category.as_deref(), Some("socket"));
307        assert!(plug.connected);
308        assert_eq!(plug.battery, None);
309        assert_eq!(
310            plug.units,
311            [Unit {
312                ain: "11630 0000001".to_owned(),
313                name: "device-1".to_owned(),
314                kind: Some("avmPlugSocket".to_owned()),
315                on: Some(true),
316                temperature: Some(21.5),
317                power: Some(23.45),
318                energy: Some(1053),
319                voltage: Some(228.055),
320                ..Unit::default()
321            }]
322        );
323
324        let thermostat = &devices[1];
325        assert_eq!(thermostat.battery, Some(80));
326        assert_eq!(thermostat.battery_low, Some(false));
327        assert_eq!(thermostat.units[0].target, Some(Target::Celsius(21.0)));
328        assert_eq!(thermostat.units[0].temperature, Some(20.5));
329
330        let lamp = &devices[2];
331        assert_eq!(lamp.units[0].on, Some(false));
332        assert_eq!(lamp.units[0].level, Some(25));
333
334        // Not connected: the values of interfaces that are not valid are
335        // left out.
336        let sensor = &devices[3];
337        assert!(!sensor.connected);
338        assert_eq!(sensor.units[0].temperature, None);
339        assert_eq!(sensor.units[0].humidity, Some(55));
340        assert_eq!(sensor.units[0].alerts, ["open"]);
341    }
342
343    #[test]
344    fn prints_compact_json() {
345        let devices = parse(FIXTURE).unwrap();
346        let json = serde_json::to_value(&devices[1].units[0]).unwrap();
347        assert_eq!(
348            json,
349            serde_json::json!({
350                "ain": "09995 0000002",
351                "name": "device-2",
352                "kind": "avmThermostat",
353                "temperature": 20.5,
354                "target": 21.0,
355            })
356        );
357    }
358
359    #[test]
360    fn reads_thermostat_modes() {
361        let target = |mode: &str, celsius| {
362            SetPoint {
363                mode: mode.to_owned(),
364                celsius,
365            }
366            .target()
367        };
368        assert_eq!(target("on", None), Some(Target::Mode("on".to_owned())));
369        assert_eq!(
370            target("off", Some(8.0)),
371            Some(Target::Mode("off".to_owned()))
372        );
373        assert_eq!(target("temperature", None), None);
374        assert_eq!(target("unknown", Some(8.0)), None);
375    }
376
377    #[test]
378    fn tolerates_missing_parts() {
379        let devices =
380            parse(r#"{"devices": [{"name": "x", "unitUids": ["missing"]}], "units": []}"#).unwrap();
381        assert_eq!(devices.len(), 1);
382        assert_eq!(devices[0].units, []);
383        assert_eq!(parse("{}").unwrap(), []);
384    }
385
386    #[test]
387    fn rejects_other_answers() {
388        let error = parse("[1]").unwrap_err().to_string();
389        assert!(
390            error.starts_with("invalid answer from the Smart Home API: "),
391            "{error}"
392        );
393    }
394}