use clap::Parser;
use emerwen_protocol::{Message, MessagePayload};
use tokio::{io::AsyncWriteExt, net::TcpStream};
use tracing::{debug, info, level_filters::LevelFilter};
use tracing_subscriber::{prelude::*, EnvFilter};
#[derive(Parser)]
#[command(version)]
struct Args {
/// Enable debug logging
#[arg(long)]
debug: bool,
}
#[tokio::main]
async fn main() {
let args = Args::parse();
tracing_subscriber::registry()
.with(
tracing_subscriber::fmt::layer()
.with_file(args.debug)
.with_line_number(args.debug)
.with_level(true),
)
.with(
EnvFilter::builder()
.with_default_directive(if args.debug {
LevelFilter::DEBUG.into()
} else {
LevelFilter::INFO.into()
})
.from_env_lossy(),
)
.init();
info!("Starting emerwen master...");
debug!("Hello, debug!");
let mut worker_client = WorkerClient::new("127.0.0.1:8000");
let _ = worker_client.connect().await;
let _ = worker_client
.send_message(MessagePayload::Authentication {
key: "avain".to_owned(),
})
.await
.unwrap();
let _ = worker_client
.send_message(MessagePayload::TargetStateChange {
target_id: 42,
state: true,
})
.await
.unwrap();
}
struct WorkerClient {
addr: String,
stream: Option<TcpStream>,
}
impl WorkerClient {
pub fn new(addr: impl Into<String>) -> WorkerClient {
WorkerClient {
addr: addr.into(),
stream: None,
}
}
pub async fn connect(&mut self) -> Result<(), Box<dyn std::error::Error>> {
self.stream = Some(TcpStream::connect(&self.addr).await?);
Ok(())
}
pub async fn send_message(
&mut self,
payload: MessagePayload,
) -> Result<Option<MessagePayload>, Box<dyn std::error::Error>> {
if let Some(stream) = &mut self.stream {
let message = Message::new(payload).encode();
stream.write_all(&message).await?;
stream.flush().await.unwrap();
}
Ok(None)
}
}