houseflow_device/devices/
light.rs

1use super::Device;
2use async_trait::async_trait;
3use houseflow_types::{DeviceCommand, DeviceError, DeviceStatus};
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7#[serde(untagged)]
8pub enum ExecuteParams {
9    NoOperation(()),
10    OnOff { on: bool },
11}
12
13impl super::ExecuteParams for ExecuteParams {}
14
15#[derive(Debug, Clone, Default, Serialize, Deserialize)]
16pub struct Light {
17    on: bool,
18}
19
20#[async_trait]
21impl Device<ExecuteParams> for Light {
22    async fn on_execute(
23        &mut self,
24        command: DeviceCommand,
25        params: ExecuteParams,
26    ) -> anyhow::Result<(DeviceStatus, DeviceError)> {
27        let result = match command {
28            DeviceCommand::NoOperation => (DeviceStatus::Success, DeviceError::None),
29            DeviceCommand::OnOff => match params {
30                ExecuteParams::OnOff { on } => {
31                    log::info!("setting light state to {}", on);
32                    self.on = on;
33                    (DeviceStatus::Success, DeviceError::None)
34                }
35                _ => (DeviceStatus::Error, DeviceError::InvalidParameters),
36            },
37            _ => (DeviceStatus::Error, DeviceError::FunctionNotSupported),
38        };
39        Ok(result)
40    }
41
42    fn state(&self) -> serde_json::Value {
43        serde_json::to_value(self).unwrap()
44    }
45}