core/emgauwa-controller/src/main.rs

58 lines
1.5 KiB
Rust
Raw Normal View History

use std::str;
use futures::{future, pin_mut, StreamExt};
use futures::channel::mpsc;
2023-11-24 21:45:44 +00:00
use tokio::io::AsyncReadExt;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message};
2023-11-24 21:45:44 +00:00
use tokio_tungstenite::tungstenite::Error;
use emgauwa_lib::db;
mod settings;
#[tokio::main]
async fn main() {
let settings = settings::init();
2023-11-24 21:45:44 +00:00
let _pool = db::init(&settings.database).await;
let url = format!(
"ws://{}:{}/api/v1/ws/controllers",
settings.core.host,
settings.core.port
);
let (stdin_tx, stdin_rx) = mpsc::unbounded();
tokio::spawn(read_stdin(stdin_tx));
let (ws_stream, _) = connect_async(url).await.expect("Failed to connect");
let (write, read) = ws_stream.split();
let stdin_to_ws = stdin_rx.map(Ok).forward(write);
2023-11-24 21:45:44 +00:00
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;
}
// Our helper method which will read data from stdin and send it along the
// sender provided.
async fn read_stdin(tx: mpsc::UnboundedSender<Message>) {
let mut stdin = tokio::io::stdin();
loop {
let mut buf = vec![0; 1024];
let n = match stdin.read(&mut buf).await {
Err(_) | Ok(0) => break,
Ok(n) => n,
};
buf.truncate(n);
tx.unbounded_send(Message::text(str::from_utf8(&buf).unwrap())).unwrap();
}
2023-11-24 21:45:44 +00:00
}
pub async fn handle_message(message_result: Result<Message, Error>) {
match message_result {
Ok(message) => println!("{}", message.into_text().unwrap()),
Err(err) => println!("Error: {}", err)
}
}