Add self-creation for controller

This commit is contained in:
Tobias Reisinger 2023-11-25 00:39:44 +01:00
parent d193000aec
commit 4e3df272c3
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
10 changed files with 105 additions and 14 deletions
emgauwa-controller/src

View file

@ -1,19 +1,50 @@
use std::str;
use futures::{future, pin_mut, StreamExt};
use futures::{future, pin_mut, SinkExt, StreamExt};
use futures::channel::mpsc;
use sqlx::pool::PoolConnection;
use sqlx::Sqlite;
use tokio::io::AsyncReadExt;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
use tokio_tungstenite::tungstenite::Error;
use emgauwa_lib::db;
use emgauwa_lib::db::Controller;
use emgauwa_lib::db::types::ControllerUid;
use crate::settings::Settings;
mod settings;
mod driver;
fn create_this_controller(conn: &mut PoolConnection<Sqlite>, settings: &Settings) -> Controller {
futures::executor::block_on(async {
Controller::create(
conn,
&ControllerUid::new(),
&settings.name,
i64::try_from(settings.relays.len()).expect("Too many relays"),
true
).await.expect("Failed to create controller")
})
}
#[tokio::main]
async fn main() {
let settings = settings::init();
let _pool = db::init(&settings.database).await;
let pool = db::init(&settings.database).await;
let mut conn = pool.acquire().await.unwrap();
let this = Controller::get_all(&mut conn)
.await
.expect("Failed to get controller from database")
.pop()
.unwrap_or_else(|| create_this_controller(&mut conn, &settings));
let this_json = serde_json::to_string(&this).unwrap();
println!("{:?}", this);
println!("{:?}", this_json);
let url = format!(
"ws://{}:{}/api/v1/ws/controllers",
@ -26,13 +57,14 @@ async fn main() {
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
let (write, read) = ws_stream.split();
let (mut write, read) = ws_stream.split();
let stdin_to_ws = stdin_rx.map(Ok).forward(write);
write.send(Message::text(this_json)).await.unwrap();
let ws_to_stdout = read.for_each(handle_message);
pin_mut!(stdin_to_ws, ws_to_stdout);
future::select(stdin_to_ws, ws_to_stdout).await;
ws_to_stdout.await;
//pin_mut!(stdin_to_ws, ws_to_stdout);
//future::select(stdin_to_ws, ws_to_stdout).await;
}
// Our helper method which will read data from stdin and send it along the