Create energy actor
This commit is contained in:
64
central_backend/src/energy/energy_actor.rs
Normal file
64
central_backend/src/energy/energy_actor.rs
Normal file
@ -0,0 +1,64 @@
|
||||
use crate::constants;
|
||||
use crate::energy::consumption;
|
||||
use crate::energy::consumption::EnergyConsumption;
|
||||
use actix::prelude::*;
|
||||
|
||||
pub struct EnergyActor {
|
||||
curr_consumption: EnergyConsumption,
|
||||
}
|
||||
|
||||
impl EnergyActor {
|
||||
pub async fn new() -> anyhow::Result<Self> {
|
||||
Ok(Self {
|
||||
curr_consumption: consumption::get_curr_consumption().await?,
|
||||
})
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user