aboutsummaryrefslogtreecommitdiff
path: root/src/session.rs
blob: 8a326f5de5f01dfda8ff86624742068ad2dfbd43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! ## Specifications
//! - [MAC] FiRa Consortium UWB MAC Technical Requirements
//! - [UCI] FiRa Consortium UWB Command Interface Generic Technical specification

use crate::packets::uci::{self, *};
use crate::{AppConfig, MacAddress, PicaCommand};
use bytes::BytesMut;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
use tokio::time;

use super::UciPacket;

pub struct Session {
    /// cf. [UCI] 7.1
    pub state: SessionState,
    /// cf. [UCI] 7.2 Table 13: 4 octets unique random number generated by application
    id: u32,
    device_handle: usize,
    data: BytesMut,

    pub session_type: SessionType,
    pub sequence_number: u32,
    pub app_config: AppConfig,
    ranging_task: Option<JoinHandle<()>>,
    tx: mpsc::UnboundedSender<UciPacket>,
    pica_tx: mpsc::Sender<PicaCommand>,
}

impl Session {
    pub fn new(
        id: u32,
        session_type: SessionType,
        device_handle: usize,
        tx: mpsc::UnboundedSender<UciPacket>,
        pica_tx: mpsc::Sender<PicaCommand>,
    ) -> Self {
        Self {
            state: SessionState::SessionStateDeinit,
            id,
            device_handle,
            data: BytesMut::new(),
            session_type,
            sequence_number: 0,
            app_config: AppConfig::default(),
            ranging_task: None,
            tx,
            pica_tx,
        }
    }

    pub fn set_state(&mut self, session_state: SessionState, reason_code: ReasonCode) {
        // No transition: ignore
        if session_state == self.state {
            return;
        }

        // Send status notification
        self.state = session_state;
        let tx = self.tx.clone();
        let session_id = self.id;
        tokio::spawn(async move {
            time::sleep(Duration::from_millis(1)).await;
            tx.send(
                SessionStatusNtfBuilder {
                    session_token: session_id,
                    session_state,
                    reason_code: reason_code.into(),
                }
                .build()
                .into(),
            )
            .unwrap()
        });
    }

    pub fn get_dst_mac_address(&self) -> &[MacAddress] {
        &self.app_config.dst_mac_address
    }

    pub fn is_session_info_ntf_enabled(&self) -> bool {
        self.app_config.session_info_ntf_config != uci::SessionInfoNtfConfig::Disable
    }

    #[allow(unused)]
    pub fn is_session_data_transfer_status_ntf_enabled(&self) -> bool {
        self.app_config.session_data_transfer_status_ntf_config
            != uci::SessionDataTransferStatusNtfConfig::Disable
    }

    pub fn data(&self) -> &BytesMut {
        &self.data
    }

    pub fn clear_data(&mut self) {
        self.data.clear()
    }

    pub fn session_type(&self) -> SessionType {
        self.session_type
    }

    pub fn session_state(&self) -> SessionState {
        self.state
    }

    pub fn init(&mut self) {
        self.set_state(
            SessionState::SessionStateInit,
            ReasonCode::StateChangeWithSessionManagementCommands,
        );
    }

    fn command_range_start(&mut self, cmd: SessionStartCmd) -> SessionStartRsp {
        log::debug!("[{}:0x{:x}] Range Start", self.device_handle, self.id);
        assert_eq!(self.id, cmd.get_session_id());

        let status = if self.state != SessionState::SessionStateIdle {
            StatusCode::UciStatusSessionNotConfigured
        } else {
            assert!(self.ranging_task.is_none());
            assert_eq!(self.state, SessionState::SessionStateIdle);

            let session_id = self.id;
            let ranging_interval =
                time::Duration::from_millis(self.app_config.ranging_duration as u64);
            let device_handle = self.device_handle;
            let tx = self.pica_tx.clone();
            self.ranging_task = Some(tokio::spawn(async move {
                loop {
                    time::sleep(ranging_interval).await;
                    tx.send(PicaCommand::Ranging(device_handle, session_id))
                        .await
                        .unwrap();
                }
            }));
            self.set_state(
                SessionState::SessionStateActive,
                ReasonCode::StateChangeWithSessionManagementCommands,
            );
            StatusCode::UciStatusOk
        };
        SessionStartRspBuilder { status }.build()
    }

    pub fn stop_ranging_task(&mut self) {
        if let Some(handle) = &self.ranging_task {
            handle.abort();
            self.ranging_task = None;
        }
    }
    fn command_range_stop(&mut self, cmd: SessionStopCmd) -> SessionStopRsp {
        log::debug!("[{}:0x{:x}] Range Stop", self.device_handle, self.id);
        assert_eq!(self.id, cmd.get_session_id());

        let status = if self.state != SessionState::SessionStateActive {
            StatusCode::UciStatusSessionActive
        } else {
            self.stop_ranging_task();
            self.set_state(
                SessionState::SessionStateIdle,
                ReasonCode::StateChangeWithSessionManagementCommands,
            );
            StatusCode::UciStatusOk
        };
        SessionStopRspBuilder { status }.build()
    }

    fn command_get_ranging_count(
        &self,
        cmd: SessionGetRangingCountCmd,
    ) -> SessionGetRangingCountRsp {
        log::debug!(
            "[{}:0x{:x}] Range Get Ranging Count",
            self.device_handle,
            self.id
        );
        assert_eq!(self.id, cmd.get_session_id());

        SessionGetRangingCountRspBuilder {
            status: StatusCode::UciStatusOk,
            count: self.sequence_number,
        }
        .build()
    }

    pub fn ranging_command(&mut self, cmd: SessionControlCommand) -> SessionControlResponse {
        match cmd.specialize() {
            SessionControlCommandChild::SessionStartCmd(cmd) => {
                self.command_range_start(cmd).into()
            }
            SessionControlCommandChild::SessionStopCmd(cmd) => self.command_range_stop(cmd).into(),
            SessionControlCommandChild::SessionGetRangingCountCmd(cmd) => {
                self.command_get_ranging_count(cmd).into()
            }
            _ => panic!("Unsupported ranging command"),
        }
    }

    pub fn data_message_snd(&mut self, data: DataMessageSnd) -> SessionControlNotification {
        log::debug!("[{}] data_message_snd", self.device_handle);
        let session_token = data.get_session_handle();
        let uci_sequence_number = data.get_data_sequence_number() as u8;

        if self.session_type != SessionType::FiraRangingAndInBandDataSession {
            return DataTransferStatusNtfBuilder {
                session_token,
                status: DataTransferNtfStatusCode::UciDataTransferStatusSessionTypeNotSupported,
                tx_count: 1, // TODO: support for retries?
                uci_sequence_number,
            }
            .build()
            .into();
        }

        assert_eq!(self.id, session_token);

        self.data.extend_from_slice(data.get_application_data());

        DataCreditNtfBuilder {
            credit_availability: CreditAvailability::CreditAvailable,
            session_token,
        }
        .build()
        .into()
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        // Make sure to abort the ranging task when dropping the session,
        // the default behaviour when dropping a task handle is to detach
        // the task, which is undesirable.
        self.stop_ranging_task();
        self.set_state(
            SessionState::SessionStateDeinit,
            ReasonCode::StateChangeWithSessionManagementCommands,
        );
    }
}