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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
//! Types related to the connection interval.

use byteorder::{ByteOrder, LittleEndian};
use core::cmp;
use core::time::Duration;

/// Define a connection interval range with its latency and supervision timeout. This value is
/// passed to the controller, which determines the [actual connection
/// interval](crate::types::FixedConnectionInterval).
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ConnectionInterval {
    interval_: (Duration, Duration),
    conn_latency_: u16,
    supervision_timeout_: Duration,
}

impl ConnectionInterval {
    /// Returns the connection interval.
    pub fn interval(&self) -> (Duration, Duration) {
        self.interval_
    }

    /// Returns the connection latency, in number of events.
    pub fn conn_latency(&self) -> u16 {
        self.conn_latency_
    }

    /// Returns the supervision timeout.
    pub fn supervision_timeout(&self) -> Duration {
        self.supervision_timeout_
    }

    /// Serializes the connection interval into the given byte buffer.
    ///
    /// The interval is serialized as:
    /// - The minimum interval value, appropriately converted (2 bytes)
    /// - The maximum interval value, appropriately converted (2 bytes)
    /// - The connection latency (2 bytes)
    /// - The supervision timeout, appropriately converted (2 bytes)
    ///
    /// # Panics
    ///
    /// The provided buffer must be at least 8 bytes long.
    pub fn copy_into_slice(&self, bytes: &mut [u8]) {
        assert!(bytes.len() >= 8);

        LittleEndian::write_u16(&mut bytes[0..2], Self::interval_as_u16(self.interval_.0));
        LittleEndian::write_u16(&mut bytes[2..4], Self::interval_as_u16(self.interval_.1));
        LittleEndian::write_u16(&mut bytes[4..6], self.conn_latency_);
        LittleEndian::write_u16(
            &mut bytes[6..8],
            Self::timeout_as_u16(self.supervision_timeout_),
        );
    }

    /// Deserializes the connection interval from the given byte buffer.
    ///
    /// - The minimum interval value, appropriately converted (2 bytes)
    /// - The maximum interval value, appropriately converted (2 bytes)
    /// - The connection latency (2 bytes)
    /// - The supervision timeout, appropriately converted (2 bytes)
    ///
    /// # Panics
    ///
    /// The provided buffer must be at least 8 bytes long.
    ///
    /// # Errors
    ///
    /// Any of the errors from the [builder](ConnectionIntervalBuilder::build) except for
    /// Incomplete.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ConnectionIntervalError> {
        assert!(bytes.len() >= 8);

        // Do the error checking with the standard connection interval builder. The min and max of
        // the interval range are allowed to be equal.
        let interval_min =
            Duration::from_micros(1_250) * u32::from(LittleEndian::read_u16(&bytes[0..2]));
        let interval_max =
            Duration::from_micros(1_250) * u32::from(LittleEndian::read_u16(&bytes[2..4]));
        let latency = LittleEndian::read_u16(&bytes[4..6]);
        let timeout = Duration::from_millis(10) * u32::from(LittleEndian::read_u16(&bytes[6..8]));
        ConnectionIntervalBuilder::new()
            .with_range(interval_min, interval_max)
            .with_latency(latency)
            .with_supervision_timeout(timeout)
            .build()
    }

    fn interval_as_u16(d: Duration) -> u16 {
        // T ms = N * 1.25 ms
        // N = T / 1.25 ms
        //   = T / (5/4) ms
        //   = 4 * T ms / 5 ms
        //
        // Note: 1000 * 4 / 5 = 800
        ((800 * d.as_secs()) as u32 + 4 * d.subsec_millis() / 5) as u16
    }

    fn timeout_as_u16(d: Duration) -> u16 {
        // T ms = N * 10 ms
        // N = T ms / 10 ms
        ((100 * d.as_secs()) as u32 + d.subsec_millis() / 10) as u16
    }
}

/// Intermediate builder for the [`ConnectionInterval`].
#[derive(Default)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ConnectionIntervalBuilder {
    interval: Option<(Duration, Duration)>,
    conn_latency: Option<u16>,
    supervision_timeout: Option<Duration>,
}

impl ConnectionIntervalBuilder {
    /// Initializes a new builder.
    pub fn new() -> ConnectionIntervalBuilder {
        ConnectionIntervalBuilder {
            interval: None,
            conn_latency: None,
            supervision_timeout: None,
        }
    }

    /// Sets the connection interval range.
    ///
    /// # Errors
    ///
    /// There are no errors from this function, but it may cause errors in
    /// [build](ConnectionIntervalBuilder::build) if:
    /// - `min` is greater than `max`
    /// - Either `min` or `max` is less than 7.5 ms or more than 4 seconds.
    /// - `max` leads to an invalid relative supervision timeout.
    pub fn with_range(&mut self, min: Duration, max: Duration) -> &mut ConnectionIntervalBuilder {
        self.interval = Some((min, max));
        self
    }

    /// Sets the connection latency.
    ///
    /// # Errors
    ///
    /// There are no errors from this function, but it may cause errors in
    /// [build](ConnectionIntervalBuilder::build) if:
    /// - `latency` is 500 or greater.
    /// - `latency` leads to an invalid relative supervision timeout.
    pub fn with_latency(&mut self, latency: u16) -> &mut ConnectionIntervalBuilder {
        self.conn_latency = Some(latency);
        self
    }

    /// Sets the supervision timeout.
    ///
    /// # Errors
    ///
    /// There are no errors from this function, but it may cause errors in
    /// [build](ConnectionIntervalBuilder::build) if:
    /// - `timeout` less than 100 ms or greater than 32 seconds
    /// - `timeout` results in an invalid relative supervision timeout.
    pub fn with_supervision_timeout(
        &mut self,
        timeout: Duration,
    ) -> &mut ConnectionIntervalBuilder {
        self.supervision_timeout = Some(timeout);
        self
    }

    /// Builds the connection interval if all parameters are valid.
    ///
    /// # Errors
    ///
    /// - [Incomplete](ConnectionIntervalError::Incomplete) if any of
    ///   [`with_range`](ConnectionIntervalBuilder::with_range),
    ///   [`with_latency`](ConnectionIntervalBuilder::with_latency), or
    ///   [`with_supervision_timeout`](ConnectionIntervalBuilder::with_supervision_timeout) have not
    ///   been called.
    /// - [IntervalTooShort](ConnectionIntervalError::IntervalTooShort) if the minimum range value
    ///   is less than 7.5 ms.
    /// - [IntervalTooLong](ConnectionIntervalError::IntervalTooLong) if the maximum range value
    ///   is greater than 4 seconds.
    /// - [IntervalInverted](ConnectionIntervalError::IntervalInverted) if the minimum range value
    ///   is greater than the maximum.
    /// - [BadConnectionLatency](ConnectionIntervalError::BadConnectionLatency) if the connection
    ///   latency is 500 or more.
    /// - [SupervisionTimeoutTooShort](ConnectionIntervalError::SupervisionTimeoutTooShort) if the
    ///   supervision timeout is less than 100 ms, or if it is less than the computed minimum: (1 +
    ///   latency) * interval max * 2.
    /// - [SupervisionTimeoutTooLong](ConnectionIntervalError::SupervisionTimeoutTooLong) if the
    ///   supervision timeout is more than 32 seconds.
    /// - [ImpossibleSupervisionTimeout](ConnectionIntervalError::ImpossibleSupervisionTimeout) if
    ///   the computed minimum supervision timeout ((1 + latency) * interval max * 2) is 32 seconds
    ///   or more.
    pub fn build(&self) -> Result<ConnectionInterval, ConnectionIntervalError> {
        if self.interval.is_none()
            || self.conn_latency.is_none()
            || self.supervision_timeout.is_none()
        {
            return Err(ConnectionIntervalError::Incomplete);
        }

        let interval = self.interval.unwrap();
        const INTERVAL_MIN: Duration = Duration::from_micros(7500);
        if interval.0 < INTERVAL_MIN {
            return Err(ConnectionIntervalError::IntervalTooShort(interval.0));
        }

        const INTERVAL_MAX: Duration = Duration::from_secs(4);
        if interval.1 > INTERVAL_MAX {
            return Err(ConnectionIntervalError::IntervalTooLong(interval.1));
        }

        if interval.0 > interval.1 {
            return Err(ConnectionIntervalError::IntervalInverted(
                interval.0, interval.1,
            ));
        }

        let conn_latency = self.conn_latency.unwrap();
        const LATENCY_MAX: u16 = 0x1F3;
        if conn_latency > LATENCY_MAX {
            return Err(ConnectionIntervalError::BadConnectionLatency(conn_latency));
        }

        let supervision_timeout = self.supervision_timeout.unwrap();
        let computed_timeout_min = interval.1 * (1 + u32::from(conn_latency)) * 2;
        const TIMEOUT_MAX: Duration = Duration::from_secs(32);
        if computed_timeout_min >= TIMEOUT_MAX {
            return Err(ConnectionIntervalError::ImpossibleSupervisionTimeout(
                computed_timeout_min,
            ));
        }

        const TIMEOUT_ABS_MIN: Duration = Duration::from_millis(100);
        let timeout_min = cmp::max(computed_timeout_min, TIMEOUT_ABS_MIN);
        if supervision_timeout <= timeout_min {
            return Err(ConnectionIntervalError::SupervisionTimeoutTooShort(
                supervision_timeout,
                timeout_min,
            ));
        }

        if supervision_timeout > TIMEOUT_MAX {
            return Err(ConnectionIntervalError::SupervisionTimeoutTooLong(
                supervision_timeout,
            ));
        }

        Ok(ConnectionInterval {
            interval_: interval,
            conn_latency_: conn_latency,
            supervision_timeout_: supervision_timeout,
        })
    }
}

/// Types of errors that can occure when creating a [`ConnectionInterval`].
#[derive(Copy, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ConnectionIntervalError {
    /// At least one of any of [`with_range`](ConnectionIntervalBuilder::with_range),
    /// [`with_latency`](ConnectionIntervalBuilder::with_latency), or
    /// [`with_supervision_timeout`](ConnectionIntervalBuilder::with_supervision_timeout) has not
    /// been called.
    Incomplete,
    /// The minimum range value is less than 7.5 ms. Includes the invalid value.
    IntervalTooShort(Duration),
    /// The maximum range value is greater than 4 seconds. Includes the invalid value.
    IntervalTooLong(Duration),
    /// The minimum range value is greater than the maximum. Includes the provided minimum and
    /// maximum, respectively.
    IntervalInverted(Duration, Duration),
    /// The connection latency is 500 or more. Includes the provided value.
    BadConnectionLatency(u16),
    /// The supervision timeout is less than 100 ms, or it is less than the computed minimum: (1 +
    /// latency) * interval max * 2. The first value is the provided timeout; the second is the
    /// required minimum.
    SupervisionTimeoutTooShort(Duration, Duration),
    /// The supervision timeout is more than 32 seconds. Includes the provided timeout.
    SupervisionTimeoutTooLong(Duration),
    /// The computed minimum supervision timeout ((1 + latency) * interval max * 2) is 32 seconds
    /// or more. Includes the computed minimum.
    ImpossibleSupervisionTimeout(Duration),
}

/// Define a connection interval with its latency and supervision timeout. This value is
/// returned from the controller.
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct FixedConnectionInterval {
    interval_: Duration,
    conn_latency_: u16,
    supervision_timeout_: Duration,
}

impl FixedConnectionInterval {
    /// Deserializes the connection interval from the given byte buffer.
    ///
    /// - The interval value, appropriately converted (2 bytes)
    /// - The connection latency (2 bytes)
    /// - The supervision timeout, appropriately converted (2 bytes)
    ///
    /// # Panics
    ///
    /// The provided buffer must be at least 6 bytes long.
    ///
    /// # Errors
    ///
    /// Any of the errors from the [builder](ConnectionIntervalBuilder::build) except for
    /// Incomplete.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ConnectionIntervalError> {
        assert!(bytes.len() >= 6);

        // Do the error checking with the standard connection interval builder. The min and max of
        // the interval range are allowed to be equal.
        let interval =
            Duration::from_micros(1_250) * u32::from(LittleEndian::read_u16(&bytes[0..2]));
        let latency = LittleEndian::read_u16(&bytes[2..4]);
        let timeout = Duration::from_millis(10) * u32::from(LittleEndian::read_u16(&bytes[4..6]));
        ConnectionIntervalBuilder::new()
            .with_range(interval, interval)
            .with_latency(latency)
            .with_supervision_timeout(timeout)
            .build()?;

        Ok(FixedConnectionInterval {
            interval_: interval,
            conn_latency_: latency,
            supervision_timeout_: timeout,
        })
    }

    /// Returns the connection interval.
    pub fn interval(&self) -> Duration {
        self.interval_
    }

    /// Returns the connection latency, in number of events.
    pub fn conn_latency(&self) -> u16 {
        self.conn_latency_
    }

    /// Returns the supervision timeout.
    pub fn supervision_timeout(&self) -> Duration {
        self.supervision_timeout_
    }
}