device-daemon-core 0.0.1

Reusable async daemon and MQTT infrastructure for device clients
Documentation
use crate::daemon::{HardwareStatus, Output};
use anyhow::{Context, Result};
use async_trait::async_trait;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;

/// Supported console and MQTT telemetry encodings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
pub enum OutputFormat {
    #[default]
    Json,
    Individual,
}

/// Supported daemon output destinations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)]
#[cfg_attr(feature = "cli", derive(clap::ValueEnum))]
#[serde(rename_all = "snake_case")]
pub enum OutputMode {
    #[default]
    Console,
    Mqtt,
}

/// Dispatch output to either of two sinks implementing the shared output contract.
pub enum EitherOutput<A, B> {
    First(A),
    Second(B),
}

#[async_trait]
impl<S, A, B> Output<S> for EitherOutput<A, B>
where
    S: Send + Sync,
    A: Output<S>,
    B: Output<S>,
{
    async fn publish(&mut self, snapshot: &S) -> Result<()> {
        match self {
            Self::First(output) => output.publish(snapshot).await,
            Self::Second(output) => output.publish(snapshot).await,
        }
    }

    async fn hardware_status(&mut self, status: HardwareStatus) -> Result<()> {
        match self {
            Self::First(output) => output.hardware_status(status).await,
            Self::Second(output) => output.hardware_status(status).await,
        }
    }

    async fn shutdown(&mut self) -> Result<()> {
        match self {
            Self::First(output) => output.shutdown().await,
            Self::Second(output) => output.shutdown().await,
        }
    }
}

/// Print snapshots as formatted JSON or as flattened individual values.
#[derive(Debug, Clone, Copy)]
pub struct ConsoleOutput {
    format: OutputFormat,
}

impl ConsoleOutput {
    pub const fn new(format: OutputFormat) -> Self {
        Self { format }
    }
}

#[async_trait]
impl<S> Output<S> for ConsoleOutput
where
    S: Serialize + Send + Sync,
{
    async fn publish(&mut self, snapshot: &S) -> Result<()> {
        match self.format {
            OutputFormat::Json => {
                println!("{}", serde_json::to_string_pretty(snapshot)?);
            }
            OutputFormat::Individual => {
                for (path, value) in flatten_values(snapshot)? {
                    println!("{path}: {value}");
                }
            }
        }
        Ok(())
    }

    async fn hardware_status(&mut self, _status: HardwareStatus) -> Result<()> {
        Ok(())
    }
}

/// Flatten a serializable value into path/value leaves for individual output.
///
/// Object fields are separated with `/`; arrays use their numeric index.
/// Null values and empty containers do not produce output rows.
pub fn flatten_values<T: Serialize>(value: &T) -> Result<Vec<(String, String)>> {
    let value = serde_json::to_value(value).context("Cannot serialize output values")?;
    let mut leaves = Vec::new();
    flatten_value("", &value, &mut leaves);
    Ok(leaves)
}

fn flatten_value(path: &str, value: &Value, leaves: &mut Vec<(String, String)>) {
    match value {
        Value::Object(fields) => {
            for (name, value) in fields {
                let path = if path.is_empty() {
                    name.clone()
                } else {
                    format!("{path}/{name}")
                };
                flatten_value(&path, value, leaves);
            }
        }
        Value::Array(values) => {
            for (index, value) in values.iter().enumerate() {
                flatten_value(&format!("{path}/{index}"), value, leaves);
            }
        }
        Value::Null => {}
        Value::String(value) => leaves.push((path.to_owned(), value.clone())),
        value => leaves.push((path.to_owned(), value.to_string())),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::Serialize;

    #[derive(Serialize)]
    struct Example {
        label: &'static str,
        channels: [i32; 2],
        absent: Option<String>,
    }

    #[test]
    fn flattens_nested_objects_and_arrays() {
        let values = Example {
            label: "ready",
            channels: [21, 22],
            absent: None,
        };
        assert_eq!(
            flatten_values(&values).unwrap(),
            vec![
                ("channels/0".to_owned(), "21".to_owned()),
                ("channels/1".to_owned(), "22".to_owned()),
                ("label".to_owned(), "ready".to_owned()),
            ]
        );
    }
}