Skip to main content

device_daemon_core/
output.rs

1use crate::daemon::{HardwareStatus, Output};
2use anyhow::{Context, Result};
3use async_trait::async_trait;
4use serde::Deserialize;
5use serde::Serialize;
6use serde_json::Value;
7
8/// Supported console and MQTT telemetry encodings.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
10#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
11#[serde(rename_all = "snake_case")]
12pub enum OutputFormat {
13    #[default]
14    Json,
15    Individual,
16}
17
18/// Supported daemon output destinations.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
20#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
21#[serde(rename_all = "snake_case")]
22pub enum OutputMode {
23    #[default]
24    Console,
25    Mqtt,
26}
27
28/// Dispatch output to either of two sinks implementing the shared output contract.
29pub enum EitherOutput<A, B> {
30    First(A),
31    Second(B),
32}
33
34#[async_trait]
35impl<S, A, B> Output<S> for EitherOutput<A, B>
36where
37    S: Send + Sync,
38    A: Output<S>,
39    B: Output<S>,
40{
41    async fn publish(&mut self, snapshot: &S) -> Result<()> {
42        match self {
43            Self::First(output) => output.publish(snapshot).await,
44            Self::Second(output) => output.publish(snapshot).await,
45        }
46    }
47
48    async fn hardware_status(&mut self, status: HardwareStatus) -> Result<()> {
49        match self {
50            Self::First(output) => output.hardware_status(status).await,
51            Self::Second(output) => output.hardware_status(status).await,
52        }
53    }
54
55    async fn shutdown(&mut self) -> Result<()> {
56        match self {
57            Self::First(output) => output.shutdown().await,
58            Self::Second(output) => output.shutdown().await,
59        }
60    }
61}
62
63/// Print snapshots as formatted JSON or as flattened individual values.
64#[derive(Debug, Clone, Copy)]
65pub struct ConsoleOutput {
66    format: OutputFormat,
67}
68
69impl ConsoleOutput {
70    pub const fn new(format: OutputFormat) -> Self {
71        Self { format }
72    }
73}
74
75#[async_trait]
76impl<S> Output<S> for ConsoleOutput
77where
78    S: Serialize + Send + Sync,
79{
80    async fn publish(&mut self, snapshot: &S) -> Result<()> {
81        match self.format {
82            OutputFormat::Json => {
83                println!("{}", serde_json::to_string_pretty(snapshot)?);
84            }
85            OutputFormat::Individual => {
86                for (path, value) in flatten_values(snapshot)? {
87                    println!("{path}: {value}");
88                }
89            }
90        }
91        Ok(())
92    }
93
94    async fn hardware_status(&mut self, _status: HardwareStatus) -> Result<()> {
95        Ok(())
96    }
97}
98
99/// Flatten a serializable value into path/value leaves for individual output.
100///
101/// Object fields are separated with `/`; arrays use their numeric index.
102/// Null values and empty containers do not produce output rows.
103pub fn flatten_values<T: Serialize>(value: &T) -> Result<Vec<(String, String)>> {
104    let value = serde_json::to_value(value).context("Cannot serialize output values")?;
105    let mut leaves = Vec::new();
106    flatten_value("", &value, &mut leaves);
107    Ok(leaves)
108}
109
110fn flatten_value(path: &str, value: &Value, leaves: &mut Vec<(String, String)>) {
111    match value {
112        Value::Object(fields) => {
113            for (name, value) in fields {
114                let path = if path.is_empty() {
115                    name.clone()
116                } else {
117                    format!("{path}/{name}")
118                };
119                flatten_value(&path, value, leaves);
120            }
121        }
122        Value::Array(values) => {
123            for (index, value) in values.iter().enumerate() {
124                flatten_value(&format!("{path}/{index}"), value, leaves);
125            }
126        }
127        Value::Null => {}
128        Value::String(value) => leaves.push((path.to_owned(), value.clone())),
129        value => leaves.push((path.to_owned(), value.to_string())),
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use serde::Serialize;
137
138    #[derive(Serialize)]
139    struct Example {
140        label: &'static str,
141        channels: [i32; 2],
142        absent: Option<String>,
143    }
144
145    #[test]
146    fn flattens_nested_objects_and_arrays() {
147        let values = Example {
148            label: "ready",
149            channels: [21, 22],
150            absent: None,
151        };
152        assert_eq!(
153            flatten_values(&values).unwrap(),
154            vec![
155                ("channels/0".to_owned(), "21".to_owned()),
156                ("channels/1".to_owned(), "22".to_owned()),
157                ("label".to_owned(), "ready".to_owned()),
158            ]
159        );
160    }
161}