Skip to main content

canlink_hal/monitor/
state.rs

1//! Connection state enumeration (FR-010)
2
3/// Connection state
4///
5/// Represents the current state of the backend connection.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
7pub enum ConnectionState {
8    /// Connected and operational
9    ///
10    /// The backend is working normally and can send/receive messages.
11    Connected,
12
13    /// Disconnected
14    ///
15    /// The backend connection has been lost and needs to be re-initialized.
16    #[default]
17    Disconnected,
18
19    /// Reconnecting
20    ///
21    /// The system is attempting to reconnect (only when auto-reconnect is enabled).
22    Reconnecting,
23}
24
25impl ConnectionState {
26    /// Check if messages can be sent in this state
27    #[must_use]
28    pub fn can_send(&self) -> bool {
29        matches!(self, Self::Connected)
30    }
31
32    /// Check if messages can be received in this state
33    #[must_use]
34    pub fn can_receive(&self) -> bool {
35        matches!(self, Self::Connected)
36    }
37
38    /// Check if the connection is active
39    #[must_use]
40    pub fn is_active(&self) -> bool {
41        matches!(self, Self::Connected)
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_can_send() {
51        assert!(ConnectionState::Connected.can_send());
52        assert!(!ConnectionState::Disconnected.can_send());
53        assert!(!ConnectionState::Reconnecting.can_send());
54    }
55
56    #[test]
57    fn test_can_receive() {
58        assert!(ConnectionState::Connected.can_receive());
59        assert!(!ConnectionState::Disconnected.can_receive());
60        assert!(!ConnectionState::Reconnecting.can_receive());
61    }
62}