Add notifier to break relay loop
This commit is contained in:
parent
83c1f033d5
commit
8785186dfa
12 changed files with 124 additions and 45 deletions
emgauwa-controller/src/ws
|
@ -1,4 +1,5 @@
|
|||
use actix::Addr;
|
||||
use emgauwa_lib::constants::WEBSOCKET_RETRY_TIMEOUT;
|
||||
use emgauwa_lib::db::DbController;
|
||||
use emgauwa_lib::errors::{DatabaseError, EmgauwaError};
|
||||
use emgauwa_lib::models::Controller;
|
||||
|
@ -6,25 +7,44 @@ use emgauwa_lib::types::ControllerWsAction;
|
|||
use futures::{SinkExt, StreamExt};
|
||||
use sqlx::pool::PoolConnection;
|
||||
use sqlx::{Pool, Sqlite};
|
||||
use tokio::time;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
use tokio_tungstenite::{connect_async, tungstenite};
|
||||
|
||||
use crate::app_state;
|
||||
use crate::app_state::AppState;
|
||||
use crate::utils::get_this;
|
||||
use crate::utils::app_state_get_this;
|
||||
|
||||
pub async fn run_websocket(
|
||||
pub async fn run_ws_loop(pool: Pool<Sqlite>, app_state: Addr<AppState>, url: String) {
|
||||
log::debug!("Spawned ws loop");
|
||||
loop {
|
||||
let run_result = run_websocket(pool.clone(), &app_state, &url).await;
|
||||
if let Err(err) = run_result {
|
||||
log::error!("Error running websocket: {}", err);
|
||||
}
|
||||
|
||||
log::info!(
|
||||
"Retrying to connect in {} seconds...",
|
||||
WEBSOCKET_RETRY_TIMEOUT.as_secs()
|
||||
);
|
||||
time::sleep(WEBSOCKET_RETRY_TIMEOUT).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_websocket(
|
||||
pool: Pool<Sqlite>,
|
||||
app_state: &Addr<AppState>,
|
||||
url: &str,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
log::debug!("Trying to connect to {}", url);
|
||||
match connect_async(url).await {
|
||||
Ok(connection) => {
|
||||
log::debug!("Websocket connected");
|
||||
let (ws_stream, _) = connection;
|
||||
|
||||
let (mut write, read) = ws_stream.split();
|
||||
|
||||
let ws_action = ControllerWsAction::Register(get_this(app_state).await?);
|
||||
let ws_action = ControllerWsAction::Register(app_state_get_this(app_state).await?);
|
||||
|
||||
let ws_action_json = serde_json::to_string(&ws_action)?;
|
||||
if let Err(err) = write.send(Message::text(ws_action_json)).await {
|
||||
|
@ -98,7 +118,7 @@ pub async fn handle_controller(
|
|||
app_state: &Addr<AppState>,
|
||||
controller: Controller,
|
||||
) -> Result<(), EmgauwaError> {
|
||||
let this = get_this(app_state).await?;
|
||||
let this = app_state_get_this(app_state).await?;
|
||||
if controller.c.uid != this.c.uid {
|
||||
return Err(EmgauwaError::Other(String::from(
|
||||
"Controller UID mismatch during update",
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue