Create energy actor

This commit is contained in:
2024-06-29 11:45:39 +02:00
parent 49a3e3a669
commit d4a81f5fdf
10 changed files with 163 additions and 7 deletions

View File

@@ -85,6 +85,12 @@ impl From<actix_web::Error> for HttpErr {
}
}
impl From<actix::MailboxError> for HttpErr {
fn from(value: actix::MailboxError) -> Self {
HttpErr::Err(std::io::Error::new(ErrorKind::Other, value.to_string()).into())
}
}
impl From<HttpResponse> for HttpErr {
fn from(value: HttpResponse) -> Self {
HttpErr::HTTPResponse(value)

View File

@@ -1,9 +1,10 @@
use crate::energy::consumption;
use crate::energy::{consumption, energy_actor};
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor;
use actix_web::HttpResponse;
#[derive(serde::Serialize)]
struct CurrConsumption {
struct Consumption {
consumption: i32,
}
@@ -11,5 +12,12 @@ struct CurrConsumption {
pub async fn curr_consumption() -> HttpResult {
let consumption = consumption::get_curr_consumption().await?;
Ok(HttpResponse::Ok().json(CurrConsumption { consumption }))
Ok(HttpResponse::Ok().json(Consumption { consumption }))
}
/// Get cached energy consumption
pub async fn cached_consumption(energy_actor: WebEnergyActor) -> HttpResult {
let consumption = energy_actor.send(energy_actor::GetCurrConsumption).await?;
Ok(HttpResponse::Ok().json(Consumption { consumption }))
}

View File

@@ -4,12 +4,15 @@ use openssl::ssl::{SslAcceptor, SslMethod};
use crate::app_config::AppConfig;
use crate::crypto::pki;
use crate::energy::energy_actor::EnergyActorAddr;
pub mod custom_error;
pub mod energy_controller;
pub mod pki_controller;
pub mod server_controller;
pub type WebEnergyActor = web::Data<EnergyActorAddr>;
/// Start unsecure (HTTP) server
pub async fn unsecure_server() -> anyhow::Result<()> {
log::info!(
@@ -31,7 +34,7 @@ pub async fn unsecure_server() -> anyhow::Result<()> {
}
/// Start secure (HTTPS) server
pub async fn secure_server() -> anyhow::Result<()> {
pub async fn secure_server(energy_actor: EnergyActorAddr) -> anyhow::Result<()> {
let web_ca = pki::CertData::load_web_ca()?;
let server_cert = pki::CertData::load_server()?;
@@ -45,14 +48,19 @@ pub async fn secure_server() -> anyhow::Result<()> {
AppConfig::get().listen_address,
AppConfig::get().secure_origin()
);
HttpServer::new(|| {
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(energy_actor.clone()))
.wrap(Logger::default())
.route("/", web::get().to(server_controller::secure_home))
.route(
"/api/energy/curr_consumption",
web::get().to(energy_controller::curr_consumption),
)
.route(
"/api/energy/cached_consumption",
web::get().to(energy_controller::cached_consumption),
)
})
.bind_openssl(&AppConfig::get().listen_address, builder)?
.run()