canlink_hal/monitor/
connection.rs1use std::time::Duration;
6
7use super::{ConnectionState, ReconnectConfig};
8
9pub struct ConnectionMonitor {
23 heartbeat_interval: Duration,
25 reconnect_config: Option<ReconnectConfig>,
27 state: ConnectionState,
29}
30
31impl ConnectionMonitor {
32 #[must_use]
38 pub fn new(heartbeat_interval: Duration) -> Self {
39 Self {
40 heartbeat_interval,
41 reconnect_config: None,
42 state: ConnectionState::Connected,
43 }
44 }
45
46 #[must_use]
53 pub fn with_reconnect(heartbeat_interval: Duration, reconnect_config: ReconnectConfig) -> Self {
54 Self {
55 heartbeat_interval,
56 reconnect_config: Some(reconnect_config),
57 state: ConnectionState::Connected,
58 }
59 }
60
61 #[must_use]
63 pub fn state(&self) -> ConnectionState {
64 self.state
65 }
66
67 #[must_use]
69 pub fn heartbeat_interval(&self) -> Duration {
70 self.heartbeat_interval
71 }
72
73 #[must_use]
75 pub fn auto_reconnect_enabled(&self) -> bool {
76 self.reconnect_config.is_some()
77 }
78
79 #[must_use]
81 pub fn reconnect_config(&self) -> Option<&ReconnectConfig> {
82 self.reconnect_config.as_ref()
83 }
84
85 pub fn set_state(&mut self, state: ConnectionState) {
87 self.state = state;
88 }
89}
90
91impl Default for ConnectionMonitor {
92 fn default() -> Self {
93 Self::new(Duration::from_secs(1))
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn test_new_monitor() {
103 let monitor = ConnectionMonitor::new(Duration::from_secs(1));
104 assert_eq!(monitor.state(), ConnectionState::Connected);
105 assert!(!monitor.auto_reconnect_enabled());
106 }
107
108 #[test]
109 fn test_with_reconnect() {
110 let monitor =
111 ConnectionMonitor::with_reconnect(Duration::from_secs(1), ReconnectConfig::default());
112 assert!(monitor.auto_reconnect_enabled());
113 }
114
115 #[test]
116 fn test_set_state() {
117 let mut monitor = ConnectionMonitor::new(Duration::from_secs(1));
118 monitor.set_state(ConnectionState::Disconnected);
119 assert_eq!(monitor.state(), ConnectionState::Disconnected);
120 }
121}