rs_connections/
base.rs

1use std::{any::Any, sync::Arc};
2
3use async_trait::async_trait;
4use rs_event_emitter::Handle;
5
6use crate::ConnectError;
7
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub enum Protocol {
11    TCP,
12    UDP,
13    WEBSOCKET,
14}
15
16impl Default for Protocol {
17    fn default() -> Self {
18        Protocol::WEBSOCKET
19    }
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum ConnectionStatus {
24    ConnectStateInit,
25    ConnectStateConnecting,
26    ConnectStateConnected,
27    ConnectStateClosed,
28    ConnectStateClosing,
29    ConnectStateReconnect,
30}
31
32impl From<u8> for ConnectionStatus {
33    fn from(value: u8) -> Self {
34        match value {
35            0 => ConnectionStatus::ConnectStateInit,
36            1 => ConnectionStatus::ConnectStateConnecting,
37            2 => ConnectionStatus::ConnectStateConnected,
38            3 => ConnectionStatus::ConnectStateClosed,
39            4 => ConnectionStatus::ConnectStateClosing,
40            5 => ConnectionStatus::ConnectStateReconnect,
41            _ => ConnectionStatus::ConnectStateInit,
42        }
43    }
44}
45
46impl Into<u8> for ConnectionStatus {
47    fn into(self) -> u8 {
48        match self {
49            ConnectionStatus::ConnectStateInit => 0,
50            ConnectionStatus::ConnectStateConnecting => 1,
51            ConnectionStatus::ConnectStateConnected => 2,
52            ConnectionStatus::ConnectStateClosed => 3,
53            ConnectionStatus::ConnectStateClosing => 4,
54            ConnectionStatus::ConnectStateReconnect => 5,
55        }
56    }
57}
58
59pub static CONNECTING_EVENT: &str = "connecting";
60pub static CONNECTED_EVENT: &str = "connected";
61pub static CLOSE_EVENT: &str = "close";
62pub static DISCONNECT_EVENT: &str = "disconnect";
63pub static ERROR_EVENT: &str = "error";
64pub static MESSAGE_EVENT: &str = "message";
65pub static RECONNECT_EVENT: &str = "reconnect";
66
67pub trait Emitter: Send + Sync {
68    fn emit(&mut self, event: &'static str, data: Box<dyn Any>) -> ();
69
70    fn on(&mut self, event: &'static str, callback: Arc<dyn Handle>) -> ();
71
72    fn off(&mut self, event: &'static str, callback: Arc<dyn Handle>) -> ();
73}
74
75#[async_trait]
76pub trait ConnectionInterface: Send + Sync {
77    async fn connect(&mut self) -> Result<bool, ConnectError>;
78    async fn disconnect(&mut self) -> Result<bool, ConnectError>;
79    async fn send(&mut self, data: &[u8]) -> Result<bool, ConnectError>;
80    async fn receive(&mut self) -> Result<Vec<u8>, ()>;
81}
82
83pub trait ConnectionBaseInterface {
84    fn get_address(&self) -> String;
85}