DEVELOPMENT ENVIRONMENT

~liljamo/emerwen

ref: 36a2db664cb9b35a9b296226f3f8bb3809f5f92d emerwen/emerwen-master/src/main.rs -rw-r--r-- 2.2 KiB
36a2db66Jonni Liljamo feat: protocol testing 15 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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)
    }
}