Skip to main content

rodecaster_protocol/
session.rs

1//! High-level session management and connection lifecycle.
2//!
3//! [`ProtocolSession`] is the central state machine for communicating with a
4//! RØDECaster. It manages device discovery, keeps track of the active layout,
5//! decodes incoming payloads into [`DeviceEvent`]s, and encodes [`Command`]s
6//! into wire payloads.
7//!
8//! # The Session Lifecycle
9//!
10//! 1. **Initialization**: Create a new session with [`ProtocolSession::new`].
11//!    At this stage, the session is waiting for the device to introduce itself.
12//! 2. **Full Sync**: When first connected (or after a handshake), the device sends
13//!    a full state snapshot (`fullSync`). Ingesting this yields [`SessionUpdate::Ready`],
14//!    which populates [`DeviceCapabilities`] and yields `initial_events` describing
15//!    the current state of all faders, mutes, and routing.
16//! 3. **Steady State**: While connected, incoming messages yield [`SessionUpdate::Event`]
17//!    for real-time updates (fader movements, knob adjustments, button presses).
18//!    You can also call [`ProtocolSession::encode`] to send commands to the device.
19//! 4. **Resync**: If the device tree topology changes (e.g. major mode switch),
20//!    the session yields [`SessionUpdate::NeedsFullSync`] and resets its layout.
21//!    Your transport should request a fresh full sync before resuming commands.
22
23use crate::change_frame::{decode, ChangeFrame};
24use crate::commands::EncodeError;
25use crate::events::{decode_event_from_frame, extract_initial_state};
26use crate::layout::BuildError;
27use crate::{Command, DeviceCapabilities, DeviceEvent, Layout};
28
29/// Result of ingesting one complete JUCE change-frame payload.
30#[derive(Debug, Clone, PartialEq)]
31pub enum SessionUpdate {
32    /// A full sync established or replaced the device layout.
33    Ready {
34        /// Semantic state extracted from the complete full sync.
35        initial_events: Vec<DeviceEvent>,
36    },
37    /// One incremental device event.
38    Event(DeviceEvent),
39    /// Tree topology changed. Request a fresh full sync before sending commands
40    /// or interpreting further property paths.
41    NeedsFullSync,
42}
43
44/// Failure to decode a payload, establish a layout, or encode a command.
45#[derive(Debug)]
46pub enum SessionError {
47    /// The payload is not exactly one valid JUCE change frame.
48    Decode,
49    /// A full sync did not contain the required device topology.
50    Layout(BuildError),
51    /// A command or incremental event was attempted before a valid full sync.
52    NotReady,
53    /// The command is not valid for the discovered layout.
54    Encode(EncodeError),
55}
56
57impl std::fmt::Display for SessionError {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        match self {
60            SessionError::Decode => f.write_str("invalid or incomplete protocol payload"),
61            SessionError::Layout(error) => write!(f, "could not build device layout: {error}"),
62            SessionError::NotReady => f.write_str("protocol session needs a full sync"),
63            SessionError::Encode(error) => write!(f, "could not encode command: {error}"),
64        }
65    }
66}
67
68impl std::error::Error for SessionError {
69    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
70        match self {
71            SessionError::Layout(error) => Some(error),
72            SessionError::Encode(error) => Some(error),
73            SessionError::Decode | SessionError::NotReady => None,
74        }
75    }
76}
77
78/// Stateful, transport-independent RODECaster protocol session.
79#[derive(Debug, Default)]
80pub struct ProtocolSession {
81    layout: Option<Layout>,
82    capabilities: Option<DeviceCapabilities>,
83}
84
85impl ProtocolSession {
86    /// Create a session waiting for its first full sync.
87    pub fn new() -> Self {
88        Self::default()
89    }
90
91    /// Whether a valid full sync has established the current address layout.
92    pub fn is_ready(&self) -> bool {
93        self.layout.is_some()
94    }
95
96    /// Capabilities discovered from the most recent full sync.
97    pub fn capabilities(&self) -> Option<&DeviceCapabilities> {
98        self.capabilities.as_ref()
99    }
100
101    /// Current low-level address layout for advanced consumers.
102    pub fn layout(&self) -> Option<&Layout> {
103        self.layout.as_ref()
104    }
105
106    /// Forget the current layout and return to the pre-full-sync state.
107    pub fn reset(&mut self) {
108        self.layout = None;
109        self.capabilities = None;
110    }
111
112    /// Ingest exactly one change-frame payload, without a TCP or USB wrapper.
113    pub fn ingest(&mut self, payload: &[u8]) -> Result<SessionUpdate, SessionError> {
114        let frame = decode(payload).ok_or(SessionError::Decode)?;
115        match frame {
116            ChangeFrame::FullSync { root } => {
117                // A replacement sync supersedes the old address space even if
118                // the new topology is unsupported. Never keep encoding through
119                // a stale layout after observing a failed resync.
120                self.reset();
121                let layout = Layout::from_full_sync(&root).map_err(SessionError::Layout)?;
122                let capabilities = DeviceCapabilities::discover(&root, &layout);
123                let initial_events = extract_initial_state(&root, &layout);
124                self.layout = Some(layout);
125                self.capabilities = Some(capabilities);
126                Ok(SessionUpdate::Ready { initial_events })
127            }
128            ChangeFrame::ChildAdded { .. }
129            | ChangeFrame::ChildRemoved { .. }
130            | ChangeFrame::ChildMoved { .. } => {
131                self.reset();
132                Ok(SessionUpdate::NeedsFullSync)
133            }
134            ChangeFrame::PropertyChanged { .. } | ChangeFrame::PropertyRemoved { .. } => {
135                let layout = self.layout.as_ref().ok_or(SessionError::NotReady)?;
136                let event = decode_event_from_frame(frame, layout);
137                Ok(SessionUpdate::Event(event))
138            }
139        }
140    }
141
142    /// Encode a typed command using the layout from the most recent full sync.
143    pub fn encode(&self, command: &Command) -> Result<Vec<Vec<u8>>, SessionError> {
144        let layout = self.layout.as_ref().ok_or(SessionError::NotReady)?;
145        command.encode(layout).map_err(SessionError::Encode)
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152    use crate::change_frame::encode_property_changed;
153    use crate::Value;
154
155    #[test]
156    fn rejects_incremental_event_before_full_sync() {
157        let mut session = ProtocolSession::new();
158        let payload = encode_property_changed(&[], "property", &Value::Bool(true));
159        assert!(matches!(
160            session.ingest(&payload),
161            Err(SessionError::NotReady)
162        ));
163    }
164
165    #[test]
166    fn structural_change_invalidates_session() {
167        let mut session = ProtocolSession::new();
168        // The lifecycle rule does not require an existing layout: either way a
169        // structural change means the next useful message must be a full sync.
170        let child_moved = [0x05, 0x00, 0x01, 0x00, 0x01, 0x01];
171        assert_eq!(
172            session.ingest(&child_moved).unwrap(),
173            SessionUpdate::NeedsFullSync
174        );
175        assert!(!session.is_ready());
176    }
177}