flic_rust_client/
client.rs

1use tokio::io::*;
2use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
3use tokio::net::TcpStream;
4use tokio::sync::Mutex;
5
6use super::commands::stream_mapper::CommandToByteMapper;
7use super::commands::Command;
8use super::events::stream_mapper::*;
9use super::events::Event;
10
11pub fn event_handler<F>(f: F) -> EventClosureMutex
12where
13    F: FnMut(&Event) + Sync + Send + 'static,
14{
15    Box::new(f)
16}
17
18type EventClosure = dyn FnMut(&Event) + Sync + Send + 'static;
19type EventClosureMutex = Box<EventClosure>;
20
21pub struct FlicClient {
22    reader: Mutex<OwnedReadHalf>,
23    writer: Mutex<OwnedWriteHalf>,
24    is_running: Mutex<bool>,
25    command_mapper: Mutex<CommandToByteMapper>,
26    event_mapper: Mutex<ByteToEventMapper>,
27    handlers: Mutex<Vec<EventClosureMutex>>,
28}
29
30impl FlicClient {
31    pub async fn new(conn: &str) -> Result<FlicClient> {
32        TcpStream::connect(conn)
33            .await
34            .map(|s| s.into_split())
35            .map(|(reader, writer)| FlicClient {
36                reader: Mutex::new(reader),
37                writer: Mutex::new(writer),
38                is_running: Mutex::new(true),
39                command_mapper: Mutex::new(CommandToByteMapper::new()),
40                event_mapper: Mutex::new(ByteToEventMapper::new()),
41                handlers: Mutex::new(vec![]),
42            })
43    }
44    pub async fn register_event_handler(self, event: EventClosureMutex) -> Self {
45        self.handlers.lock().await.push(event);
46        self
47    }
48
49    pub async fn listen(&self) {
50        while *self.is_running.lock().await {
51            let mut reader = self.reader.lock().await;
52            let mut buffer = vec![0; 2048];
53
54            let size = reader.read(&mut buffer).await;
55
56            match size {
57                Ok(size) if size > 0 => {
58                    buffer.truncate(size);
59                    for b in buffer.iter() {
60                        match self.event_mapper.lock().await.map(*b) {
61                            EventResult::Some(Event::NoOp) => { }
62                            EventResult::Some(event) => {
63                                self.handlers
64                                    .lock()
65                                    .await
66                                    .iter_mut()
67                                    .for_each(|handler| handler(&event))
68                            }
69                            _ => {}
70                        }
71                    }
72                }
73                Ok(_) => {
74                    tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
75                }
76                Err(e) => {
77                    eprintln!("Error reading from reader: {}", e);
78                    break;
79                }
80            }
81        }
82    }
83
84    pub async fn stop(&self) {
85        *self.is_running.lock().await = false;
86    }
87
88    pub async fn submit(&self, cmd: Command) {
89        let mut writer = self.writer.lock().await;
90        for b in self.command_mapper.lock().await.map(cmd) {
91            let _ = writer.write_u8(b).await;
92        }
93    }
94}