2024-06-29 09:45:39 +00:00
|
|
|
use crate::constants;
|
2024-07-01 19:10:45 +00:00
|
|
|
use crate::devices::device::DeviceId;
|
|
|
|
use crate::devices::devices_list::DevicesList;
|
2024-06-29 09:45:39 +00:00
|
|
|
use crate::energy::consumption;
|
|
|
|
use crate::energy::consumption::EnergyConsumption;
|
|
|
|
use actix::prelude::*;
|
|
|
|
|
|
|
|
pub struct EnergyActor {
|
|
|
|
curr_consumption: EnergyConsumption,
|
2024-07-01 19:10:45 +00:00
|
|
|
devices: DevicesList,
|
2024-06-29 09:45:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl EnergyActor {
|
|
|
|
pub async fn new() -> anyhow::Result<Self> {
|
|
|
|
Ok(Self {
|
|
|
|
curr_consumption: consumption::get_curr_consumption().await?,
|
2024-07-01 19:10:45 +00:00
|
|
|
devices: DevicesList::load()?,
|
2024-06-29 09:45:39 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn refresh(&mut self) -> anyhow::Result<()> {
|
|
|
|
// Refresh energy
|
|
|
|
self.curr_consumption = consumption::get_curr_consumption()
|
|
|
|
.await
|
|
|
|
.unwrap_or_else(|e| {
|
|
|
|
log::error!(
|
|
|
|
"Failed to fetch latest consumption value, will use fallback value! {e}"
|
|
|
|
);
|
|
|
|
constants::FALLBACK_PRODUCTION_VALUE
|
|
|
|
});
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Actor for EnergyActor {
|
|
|
|
type Context = Context<Self>;
|
|
|
|
|
|
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
|
|
|
log::info!("Energy actor successfully started!");
|
|
|
|
|
|
|
|
ctx.run_interval(constants::ENERGY_REFRESH_INTERVAL, |act, _ctx| {
|
|
|
|
log::info!("Performing energy refresh operation");
|
|
|
|
if let Err(e) = futures::executor::block_on(act.refresh()) {
|
|
|
|
log::error!("Energy refresh failed! {e}")
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
fn stopped(&mut self, _ctx: &mut Self::Context) {
|
|
|
|
log::info!("Energy actor successfully stopped!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub type EnergyActorAddr = Addr<EnergyActor>;
|
|
|
|
|
|
|
|
/// Get current consumption
|
|
|
|
#[derive(Message)]
|
|
|
|
#[rtype(result = "EnergyConsumption")]
|
|
|
|
pub struct GetCurrConsumption;
|
|
|
|
|
|
|
|
impl Handler<GetCurrConsumption> for EnergyActor {
|
|
|
|
type Result = EnergyConsumption;
|
|
|
|
|
|
|
|
fn handle(&mut self, _msg: GetCurrConsumption, _ctx: &mut Context<Self>) -> Self::Result {
|
|
|
|
self.curr_consumption
|
|
|
|
}
|
|
|
|
}
|
2024-07-01 19:10:45 +00:00
|
|
|
|
|
|
|
/// Get current consumption
|
|
|
|
#[derive(Message)]
|
|
|
|
#[rtype(result = "bool")]
|
|
|
|
pub struct CheckDeviceExists(DeviceId);
|
|
|
|
|
|
|
|
impl Handler<CheckDeviceExists> for EnergyActor {
|
|
|
|
type Result = bool;
|
|
|
|
|
|
|
|
fn handle(&mut self, msg: CheckDeviceExists, _ctx: &mut Context<Self>) -> Self::Result {
|
|
|
|
self.devices.exists(&msg.0)
|
|
|
|
}
|
|
|
|
}
|