Add ControllerWsAction

This commit is contained in:
Tobias Reisinger 2023-11-27 17:21:40 +01:00
parent cb47dcda5c
commit 3b596de06f
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
10 changed files with 134 additions and 34 deletions
emgauwa-lib/src/handlers/v1/ws

View file

@ -1,12 +1,22 @@
use crate::db::DbSchedule;
use crate::db::errors::DatabaseError;
use crate::db::{DbController, DbRelay};
use crate::handlers::errors::ApiError;
use crate::models::Controller;
use actix::{Actor, StreamHandler};
use actix_web::{get, web, HttpRequest, HttpResponse};
use actix_web_actors::ws;
use actix_web_actors::ws::ProtocolError;
use futures::FutureExt;
use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};
use ws::Message;
#[derive(Debug, Serialize, Deserialize)]
pub enum ControllerWsAction {
Register(Controller),
}
struct ControllerWs {
pub pool: Pool<Sqlite>,
}
@ -15,24 +25,57 @@ impl Actor for ControllerWs {
type Context = ws::WebsocketContext<Self>;
}
async fn get_schedules(pool: &mut Pool<Sqlite>) -> Result<Vec<DbSchedule>, ApiError> {
let mut pool_conn = pool.acquire().await?;
Ok(DbSchedule::get_all(&mut pool_conn).await?)
}
impl StreamHandler<Result<Message, ProtocolError>> for ControllerWs {
fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
let schedules = futures::executor::block_on(get_schedules(&mut self.pool)).unwrap();
let schedules_json = serde_json::to_string(&schedules).unwrap();
let mut pool_conn = futures::executor::block_on(self.pool.acquire()).unwrap();
match msg {
Ok(Message::Ping(msg)) => ctx.pong(&msg),
Ok(Message::Text(text)) => {
println!("Got text: {}", text);
ctx.text(schedules_json)
let action: ControllerWsAction = serde_json::from_str(&text).unwrap();
let action_res = futures::executor::block_on(handle_action(&mut pool_conn, action));
if let Err(e) = action_res {
log::error!("Error handling action: {:?}", e);
ctx.text(serde_json::to_string(&e).unwrap());
}
}
_ => {}
}
//let schedules = futures::executor::block_on(DbSchedule::get_all(&mut pool_conn)).unwrap();
//let schedules_json = serde_json::to_string(&schedules).unwrap();
//ctx.text(schedules_json);
}
}
pub async fn handle_action(
conn: &mut PoolConnection<Sqlite>,
action: ControllerWsAction,
) -> Result<(), DatabaseError> {
match action {
ControllerWsAction::Register(controller) => {
log::info!("Registering controller: {:?}", controller);
let c = &controller.controller;
let controller_db =
DbController::get_by_uid_or_create(conn, &c.uid, &c.name, c.relay_count, c.active)
.await?;
println!("Controller: {:?}", controller_db);
for relay in &controller.relays {
let r = &relay.relay;
let relay_db = DbRelay::get_by_controller_and_num_or_create(
conn,
&controller_db,
r.number,
&r.name,
)
.await?;
println!("Controller relay: {:?}", relay_db);
}
Ok(())
}
}
}