1786286362

This commit is contained in:
2026-08-09 16:39:22 +02:00
parent 3a313a89dc
commit 56a6dacd28

View File

@@ -9,6 +9,59 @@ use crate::{
messages::{CommandMessage, EventMessage}, messages::{CommandMessage, EventMessage},
}; };
async fn handle_command(
message: CommandMessage,
state: &HashMap<String, HassEntity>,
client: &mut HassClient,
) -> Result<(), AppError> {
match message {
CommandMessage::ToggleLight { entity_id } => {
if let Some(entity) = state.get(&entity_id) {
let payload = json!({
"entity_id": entity_id
});
let service = toggle_action(&entity.state, "on");
client
.call_service("light".into(), service.into(), Some(payload))
.await
.map_err(Box::new)
.map_err(Into::into)
} else {
Err(AppError::NoEntity(entity_id))
}
}
CommandMessage::ToggleThermostat { entity_id } => {
if let Some(entity) = state.get(&entity_id) {
let payload = json!({
"entity_id": entity_id
});
let service = toggle_action(&entity.state, "heat");
client
.call_service("climate".into(), service.into(), Some(payload))
.await
.map_err(Box::new)
.map_err(Into::into)
} else {
Err(AppError::NoEntity(entity_id))
}
}
CommandMessage::SetTemperature {
entity_id,
temperature,
} => {
let payload = json!({
"entity_id": entity_id,
"temperature": temperature
});
client
.call_service("climate".into(), "set_temperature".into(), Some(payload))
.await
.map_err(Box::new)
.map_err(Into::into)
}
}
}
pub async fn hass( pub async fn hass(
s2c_tx: UnboundedSender<EventMessage>, s2c_tx: UnboundedSender<EventMessage>,
mut c2s_rx: UnboundedReceiver<CommandMessage>, mut c2s_rx: UnboundedReceiver<CommandMessage>,
@@ -79,52 +132,7 @@ pub async fn hass(
} }
Some(message) = c2s_rx.recv() => { Some(message) = c2s_rx.recv() => {
if let Err(err) = match message { if let Err(err) = handle_command(message, &state, &mut client).await {
CommandMessage::ToggleLight { entity_id } => {
if let Some(entity) = state.get(&entity_id) {
let payload = json!({
"entity_id": entity_id
});
let service = toggle_action(&entity.state, "on");
client
.call_service("light".into(), service.into(), Some(payload))
.await
.map_err(Box::new)
.map_err(Into::into)
} else {
Err(AppError::NoEntity(entity_id))
}
}
CommandMessage::ToggleThermostat { entity_id } => {
if let Some(entity) = state.get(&entity_id) {
let payload = json!({
"entity_id": entity_id
});
let service = toggle_action(&entity.state, "heat");
client
.call_service("climate".into(), service.into(), Some(payload))
.await
.map_err(Box::new)
.map_err(Into::into)
} else {
Err(AppError::NoEntity(entity_id))
}
}
CommandMessage::SetTemperature {
entity_id,
temperature,
} => {
let payload = json!({
"entity_id": entity_id,
"temperature": temperature
});
client
.call_service("climate".into(), "set_temperature".into(), Some(payload))
.await
.map_err(Box::new)
.map_err(Into::into)
}
} {
eprintln!("Failed to execute Service Call.\n\t{:?}", err); eprintln!("Failed to execute Service Call.\n\t{:?}", err);
} }
} }