88 lines
2.7 KiB
Rust
88 lines
2.7 KiB
Rust
use super::service::{turn_off::TurnOff, turn_on::TurnOn};
|
|
use super::{GetStateObjectError, HomeAssistantLight};
|
|
use crate::home_assistant::GetServicesError;
|
|
use crate::service_registry::CallServiceError;
|
|
use crate::{
|
|
event::context::Context,
|
|
state::{ErrorState, HomeAssistantState, UnexpectedState},
|
|
};
|
|
use protocol::light::{GetState, SetState};
|
|
use pyo3::Python;
|
|
use python_utils::IsNone;
|
|
use snafu::{ResultExt, Snafu};
|
|
|
|
#[derive(Debug, Snafu)]
|
|
pub enum GetStateError {
|
|
GetStateObjectError { source: GetStateObjectError },
|
|
Error { state: ErrorState },
|
|
UnexpectedError { state: UnexpectedState },
|
|
}
|
|
|
|
impl GetState for HomeAssistantLight {
|
|
type Error = GetStateError;
|
|
|
|
async fn get_state(&self) -> Result<protocol::light::State, Self::Error> {
|
|
let state_object = self.get_state_object().context(GetStateObjectSnafu)?;
|
|
let state = state_object.state;
|
|
|
|
match state {
|
|
HomeAssistantState::Ok(light_state) => Ok(light_state.into()),
|
|
HomeAssistantState::Err(error_state) => {
|
|
Err(GetStateError::Error { state: error_state })
|
|
}
|
|
HomeAssistantState::Unexpected(state) => Err(GetStateError::UnexpectedError { state }),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Snafu)]
|
|
pub enum SetStateError {
|
|
/// couldn't get the service registry
|
|
GetServicesError { source: GetServicesError },
|
|
|
|
/// couldn't call the service
|
|
CallServiceError { source: CallServiceError },
|
|
}
|
|
|
|
impl SetState for HomeAssistantLight {
|
|
type Error = SetStateError;
|
|
|
|
async fn set_state(&mut self, state: protocol::light::State) -> Result<(), Self::Error> {
|
|
let context: Option<Context<()>> = None;
|
|
let target: Option<()> = None;
|
|
|
|
let services =
|
|
Python::attach(|py| self.home_assistant.services(py)).context(GetServicesSnafu)?;
|
|
|
|
let _: IsNone = match state {
|
|
protocol::light::State::Off => {
|
|
services
|
|
.call_service(
|
|
TurnOff {
|
|
object_id: self.object_id.clone(),
|
|
},
|
|
context,
|
|
target,
|
|
false,
|
|
)
|
|
.await
|
|
}
|
|
protocol::light::State::On => {
|
|
services
|
|
.call_service(
|
|
TurnOn {
|
|
object_id: self.object_id.clone(),
|
|
},
|
|
context,
|
|
target,
|
|
false,
|
|
)
|
|
.await
|
|
}
|
|
}
|
|
.context(CallServiceSnafu)?;
|
|
|
|
Ok(())
|
|
}
|
|
}
|