Skip to main content

antenna_protocol/handshake/
host.rs

1use crate::handshake::{HandshakeInput, HandshakeOutput, HandshakeState};
2use anyhow::{Result, anyhow};
3
4/// Host-side handshake FSM
5pub struct Host {
6    state: HandshakeState,
7}
8
9impl Default for Host {
10    fn default() -> Self {
11        Self::new()
12    }
13}
14
15impl Host {
16    pub fn new() -> Self {
17        Self {
18            state: HandshakeState::Idle,
19        }
20    }
21
22    pub fn state(&self) -> &HandshakeState {
23        &self.state
24    }
25
26    pub fn process(&mut self, input: HandshakeInput) -> Result<Option<HandshakeOutput>> {
27        match (&self.state, input) {
28            (HandshakeState::Idle, HandshakeInput::Init) => {
29                self.state = HandshakeState::CreatingOffer;
30                Ok(Some(HandshakeOutput::InitSDPOffer))
31            }
32            (HandshakeState::CreatingOffer, HandshakeInput::OfferCreated(_)) => {
33                self.state = HandshakeState::WaitingForAnswer;
34                Ok(None)
35            }
36            (HandshakeState::WaitingForAnswer, HandshakeInput::Answer(answer)) => {
37                self.state = HandshakeState::WaitingForDataChannel;
38                Ok(Some(HandshakeOutput::AcceptSDPAnswer(answer)))
39            }
40            (HandshakeState::WaitingForDataChannel, HandshakeInput::DataChannelOpen) => {
41                self.state = HandshakeState::Connected;
42                Ok(Some(HandshakeOutput::Connected))
43            }
44            (_, HandshakeInput::ConnectionDropped) => {
45                self.state = HandshakeState::Closed;
46                Ok(Some(HandshakeOutput::Close))
47            }
48            _ => Err(anyhow!("Unhandled input by host fsm")),
49        }
50    }
51}