This commit is contained in:
Mateusz Gruszczyński
2026-09-14 23:10:17 +02:00
parent 4bb9c8621a
commit 0a2fb8c6c7
47 changed files with 1337 additions and 372 deletions
+16 -5
View File
@@ -71,10 +71,7 @@ fn queue_influx_energy(state: &AppState, reading: EnergyReading) {
});
}
async fn sample_home_assistant_energy_device(state: &AppState, device: &Device) -> Result<(), AppError> {
let Some(entity_id) = device.ha_energy_entity_id.as_deref().filter(|value| !value.trim().is_empty()) else {
return Ok(());
};
async fn sample_home_assistant_energy_target(state: &AppState, target_id: &str, entity_id: &str) -> Result<(), AppError> {
let settings = state.settings.read().await.home_assistant.clone();
let payload = home_assistant::read_entity(&state.http, &settings, Some(entity_id))
.await
@@ -92,10 +89,15 @@ async fn sample_home_assistant_energy_device(state: &AppState, device: &Device)
if !matches!(unit.to_ascii_lowercase().as_str(), "wh" | "kwh") {
return Err(AppError::BadRequest("Home Assistant energy sensor must use Wh or kWh".into()));
}
let _ = record_cumulative_energy_sample(state, &device.id, "home_assistant", raw_value, unit, None)?;
let _ = record_cumulative_energy_sample(state, target_id, "home_assistant", raw_value, unit, None)?;
Ok(())
}
async fn sample_home_assistant_energy_device(state: &AppState, device: &Device) -> Result<(), AppError> {
let Some(entity_id) = device.ha_energy_entity_id.as_deref().filter(|value| !value.trim().is_empty()) else { return Ok(()); };
sample_home_assistant_energy_target(state, &device.id, entity_id).await
}
pub(crate) async fn home_assistant_energy_loop(state: AppState) {
sleep(Duration::from_secs(10)).await;
loop {
@@ -108,6 +110,15 @@ pub(crate) async fn home_assistant_energy_loop(state: AppState) {
}
}
}
if let Ok(groups) = state.db.list_device_groups() {
for group in groups.into_iter().filter(|group| matches!(group.energy_source, EnergySourcePreference::HomeAssistant | EnergySourcePreference::Auto)) {
let Some(entity_id) = group.ha_energy_entity_id.as_deref().filter(|value| !value.trim().is_empty()) else { continue; };
let target_id = format!("group:{}", group.id);
if let Err(err) = sample_home_assistant_energy_target(&state, &target_id, entity_id).await {
tracing::warn!(group=%group.id, error=?err, "Home Assistant installation energy sample failed");
}
}
}
}
sleep(Duration::from_secs(60)).await;
}