Fix bugs and add controller action for controller ws

This commit is contained in:
Tobias Reisinger 2023-12-05 16:11:40 +01:00
parent 8b1affd8c7
commit 6f8d63e7be
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
11 changed files with 177 additions and 56 deletions
emgauwa-controller/src

View file

@ -2,23 +2,21 @@ use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT;
use emgauwa_lib::db::{DbController, DbJunctionRelaySchedule, DbRelay, DbSchedule};
use emgauwa_lib::errors::EmgauwaError;
use emgauwa_lib::models::{Controller, FromDbModel};
use emgauwa_lib::types::{ControllerUid, ControllerWsAction};
use emgauwa_lib::types::ControllerUid;
use emgauwa_lib::{db, utils};
use futures::{SinkExt, StreamExt};
use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use tokio::time;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::protocol::Message;
use tokio_tungstenite::tungstenite::Error;
use utils::init_logging;
use crate::relay_loop::run_relay_loop;
use crate::settings::Settings;
use crate::ws::run_websocket;
mod driver;
mod relay_loop;
mod settings;
mod ws;
async fn create_this_controller(
conn: &mut PoolConnection<Sqlite>,
@ -57,34 +55,6 @@ async fn create_this_relay(
Ok(relay)
}
async fn run_websocket(this: Controller, url: &str) -> Result<(), EmgauwaError> {
match connect_async(url).await {
Ok(connection) => {
let (ws_stream, _) = connection;
let (mut write, read) = ws_stream.split();
let ws_action = ControllerWsAction::Register(this.clone());
let ws_action_json = serde_json::to_string(&ws_action)?;
if let Err(err) = write.send(Message::text(ws_action_json)).await {
log::error!("Failed to register at websocket: {}", err);
return Ok(());
}
let read_handler = read.for_each(handle_message);
read_handler.await;
log::warn!("Lost connection to websocket");
}
Err(err) => {
log::warn!("Failed to connect to websocket: {}", err,);
}
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let settings = settings::init()?;
@ -128,8 +98,6 @@ async fn main() -> Result<(), std::io::Error> {
.await
.map_err(EmgauwaError::from)?;
let this = Controller::from_db_model(&mut conn, db_controller).map_err(EmgauwaError::from)?;
let url = format!(
"ws://{}:{}/api/v1/ws/controllers",
settings.core.host, settings.core.port
@ -138,7 +106,14 @@ async fn main() -> Result<(), std::io::Error> {
tokio::spawn(run_relay_loop(settings));
loop {
let run_result = run_websocket(this.clone(), &url).await;
let db_controller = db_controller
.reload(&mut conn)
.await
.map_err(EmgauwaError::from)?;
let this =
Controller::from_db_model(&mut conn, db_controller).map_err(EmgauwaError::from)?;
let run_result = run_websocket(pool.clone(), this.clone(), &url).await;
if let Err(err) = run_result {
log::error!("Error running websocket: {}", err);
}
@ -150,14 +125,3 @@ async fn main() -> Result<(), std::io::Error> {
time::sleep(WEBSOCKET_RETRY_TIMEOUT).await;
}
}
async fn handle_message(message_result: Result<Message, Error>) {
match message_result {
Ok(message) => {
if let Message::Text(msg_text) = message {
log::debug!("{}", msg_text)
}
}
Err(err) => log::debug!("Error: {}", err),
}
}

View file

@ -8,7 +8,7 @@ use crate::settings::Settings;
#[allow(unused_variables)]
pub async fn run_relay_loop(settings: Settings) {
let default_duration = Duration::from_millis(1000);
let default_duration = Duration::from_millis(10000);
loop {
let next_timestamp = Instant::now() + default_duration;
time::sleep_until(next_timestamp).await;

View file

@ -0,0 +1,109 @@
use emgauwa_lib::db::DbController;
use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
use emgauwa_lib::models::Controller;
use emgauwa_lib::types::ControllerWsAction;
use futures::{SinkExt, StreamExt};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{connect_async, tungstenite};
pub async fn run_websocket(
pool: Pool<Sqlite>,
this: Controller,
url: &str,
) -> Result<(), EmgauwaError> {
match connect_async(url).await {
Ok(connection) => {
let (ws_stream, _) = connection;
let (mut write, read) = ws_stream.split();
let ws_action = ControllerWsAction::Register(this.clone());
let ws_action_json = serde_json::to_string(&ws_action)?;
if let Err(err) = write.send(Message::text(ws_action_json)).await {
log::error!("Failed to register at websocket: {}", err);
return Ok(());
}
let read_handler = read.for_each(|msg| handle_message(pool.clone(), this.clone(), msg));
read_handler.await;
log::warn!("Lost connection to websocket");
}
Err(err) => {
log::warn!("Failed to connect to websocket: {}", err,);
}
}
Ok(())
}
async fn handle_message(
pool: Pool<Sqlite>,
this: Controller,
message_result: Result<Message, tungstenite::Error>,
) {
let msg = match message_result {
Ok(msg) => msg,
Err(err) => {
log::error!("Error reading message: {}", err);
return;
}
};
match msg {
Message::Text(text) => match serde_json::from_str(&text) {
Ok(action) => {
log::debug!("Received action: {:?}", action);
let mut pool_conn = match pool.acquire().await {
Ok(conn) => conn,
Err(err) => {
log::error!("Failed to acquire database connection: {:?}", err);
return;
}
};
let action_res = handle_action(&mut pool_conn, this, action).await;
if let Err(e) = action_res {
log::error!("Error handling action: {:?}", e);
}
}
Err(e) => {
log::error!("Error deserializing action: {:?}", e);
}
},
_ => (),
}
}
pub async fn handle_action(
conn: &mut PoolConnection<Sqlite>,
this: Controller,
action: ControllerWsAction,
) -> Result<(), EmgauwaError> {
match action {
ControllerWsAction::Controller(controller) => {
handle_controller(conn, this, controller).await
}
_ => Ok(()),
}
}
pub async fn handle_controller(
conn: &mut PoolConnection<Sqlite>,
this: Controller,
controller: Controller,
) -> Result<(), EmgauwaError> {
if controller.c.uid != this.c.uid {
return Err(EmgauwaError::Other(String::from(
"Controller UID mismatch during update",
)));
}
DbController::get_by_uid(conn, &controller.c.uid)
.await?
.ok_or(DatabaseError::NotFound)?
.update(conn, controller.c.name.as_str(), this.c.relay_count)
.await?;
Ok(())
}