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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
//! This module contains everything related to the transfer protocol that will be used to transmit the uavcan frame
//!
//! The only transfer protocol that is currently supported by the uavcan protocol is CAN2.0B.

use lib::core::convert::From;
use lib::core::cmp::Ordering;

use embedded_types;

pub use embedded_types::io::Error as IOError;

/// `TransferInterface` is an interface to a hardware unit which can communicate over a CAN like transfer protocol
///
/// It's associated with a `TransferFrame` and must be able to receive and transmit this type of frames.
/// The interface must also do ordering of incoming frames after priority defined by the transfer frame ID to avoid priority inversion,
/// while making sure that transfer frames with the same ID is transmitted in the same order as they was added in the transmit buffer.
///
/// Receiving frames must be returned in the same order they were received by the interface.
pub trait TransferInterface {
    /// The TransferFrame associated with this interface.
    type Frame: TransferFrame;

    /// Put a `TransferFrame` in the transfer buffer (or transmit it on the bus) or return `Err(IOError::BufferExhausted)` if buffer is full.
    ///
    /// To avoid priority inversion the new frame needs to be prioritized inside the interface as it would on the bus.
    /// When reprioritizing the `TransferInterface` must for equal ID frames respect the order they were attempted transmitted in.
    fn transmit(&self, frame: &Self::Frame) -> Result<(), IOError>;
    
    /// Receive a frame, removing to from the receive buffer.
    /// if there are no frames in the receive buffer this function will return `None`
    fn receive(&self) -> Option<Self::Frame>;
}

/// `TransferFrame` is a CAN like frame that can be sent over a network
///
/// For a frame to work it need to have a 28 bit ID, and a payload of
/// at least 4 bytes. Guarantee that frames are delivered in order
/// and correctness check is needed as well.
///
/// The uavcan protocol defines how this works with a CAN2.0B frame
pub trait TransferFrame {
    /// Maximum data length the transfer protocol supports.
    const MAX_DATA_LENGTH: usize;

    /// Create a new TransferFrame with id: id, and length 0.
    /// Data length can be changed with `set_data_length(&self)`.
    /// Data can be changed with `data_as_mut(&mut self)`.
    fn new(id: TransferFrameID) -> Self;

    /// Returns the 28 bit ID of this TransferFrame.
    ///
    /// When deciding which frame that will be transmitted,
    /// the ID is used to prioritze (lower ID means higher priority)
    fn id(&self) -> TransferFrameID;

    /// Returns a slice with the data in this TransferFrame
    ///
    /// Length can be found by checking the length
    /// of this slice `self.data().len()`
    fn data(&self) -> &[u8];

    /// Returns a mutable slice with the data in this TransferFrame
    /// use this method to set/change the data inside this TransferFrame
    fn data_as_mut(&mut self) -> &mut [u8];

    /// Set the data length of this TransferFrame
    ///
    /// ## Panics
    /// `set_data_lengt(&mut self, length: usize)` should panic if `length > T::MAX_DATA_LENGTH`
    fn set_data_length(&mut self, length: usize);
    
    /// Returns the tail byte of the TransferFrame assuming the current length
    ///
    /// ## Panics
    /// panics if `self.data().len() == 0` as no tail_byte exists
    fn tail_byte(&self) -> TailByte {
        TailByte::from(
            *self.data()
                .last()
                .expect("Can't return tail byte of frame with 0 data bytes"),
        )
    }

    /// Checks the tail byte if this frame is a start frame and return the result
    fn is_start_frame(&self) -> bool {
        self.tail_byte().start_of_transfer()
    }
    
    /// Checks the tail byte if this frame is an end frame and return the result
    fn is_end_frame(&self) -> bool {
        self.tail_byte().end_of_transfer()
    }
    
    /// Checks the tail byte if this is both a start frame and an end frame and return the result
    fn is_single_frame(&self) -> bool {
        self.is_end_frame() && self.is_start_frame()
    }

    /// Returns the full ID of the frame (both Frame ID and transfer ID)
    ///
    /// ## Panics
    /// panics if `self.data().len() == 0` as no tail_byte exists
    fn full_id(&self) -> FullTransferID {
        FullTransferID {
            frame_id: self.id(),
            transfer_id: self.tail_byte().transfer_id(),
        }
    }
}


/// Cotains both the `TransferFrameID` and `TransferID` to uniquely distinguish a transfer.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct FullTransferID {
    pub frame_id: TransferFrameID,
    pub transfer_id: TransferID,
}

impl FullTransferID {
    /// Deasserts bits based on the asserted bits of `mask`
    pub fn mask(self, mask: Self) -> Self {
        FullTransferID {
            frame_id: self.frame_id.mask(mask.frame_id),
            transfer_id: self.transfer_id.mask(mask.transfer_id),
        }
    }
}

/// The 29-bit ID of a `TransferFrame`
///
/// Frames that will win arbitration can be found by the help of ordering.
/// If `frame1 < frame2`, then `frame1` will win arbitration over `frame2`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct TransferFrameID(u32);

impl TransferFrameID {
    /// Constructs a new `TransferFrameID`
    /// ## Panic
    /// Panics if `value` is something not representable with 29-bits
    pub fn new(value: u32) -> TransferFrameID {
        assert_eq!(value & !0x1fff_ffff, 0);
        TransferFrameID(value)
    }
    
    /// Deasserts bits based on the asserted bits of `mask`
    pub fn mask(self, mask: Self) -> Self {
        let TransferFrameID(mut value) = self;
        value &= u32::from(mask);
        TransferFrameID(value)        
    }
}

impl From<TransferFrameID> for u32 {
    fn from(id: TransferFrameID) -> u32 {
        let TransferFrameID(value) = id;
        value
    }
}

/// A filter for `TransferFrameID`
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub struct TransferFrameIDFilter{
    value: u32,
    mask: u32,
}

impl TransferFrameIDFilter {
    pub fn new(value: u32, mask: u32) -> Self {
        TransferFrameIDFilter{
            mask: mask,
            value: value,
        }
    }

    pub fn is_match(&self, value: TransferFrameID) -> bool {
        self.mask & u32::from(value) == self.mask & self.value
    }
}

/// The 5-bit ID used to distinguish consecutive transfers
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct TransferID(u8);

impl TransferID {
    /// Constructs a new `TransferID`
    /// ## Panic
    /// Panics if `value` is something not representable with 5-bits
    pub fn new(value: u8) -> TransferID {
        assert_eq!(value & !0x1f, 0);
        TransferID(value)
    }
    
    /// Deasserts bits based on the asserted bits of `mask`
    pub fn mask(self, mask: Self) -> Self {
        let TransferID(mut value) = self;
        value &= u8::from(mask);
        TransferID(value)        
    }
}

impl From<TransferID> for u8 {
    fn from(tid: TransferID) -> u8 {
        let TransferID(value) = tid;
        value
    }
}

/// A Wrapper that can be used for sorting after priority
///
/// PartialEq, Eq, PartialOrd and Ord is implemented but only cares about priority.
///
/// # Examples
/// ## Usable with `TransferFrameID`
/// ```
/// use uavcan::transfer::TransferFrameID;
/// use uavcan::transfer::Priority;
///
/// assert!(Priority(TransferFrameID::new(0)) > Priority(TransferFrameID::new(1)))
///
/// ```
///
/// ## Usable with anything that implements `TransferFrame`
/// ```
/// use uavcan::transfer::Priority;
/// use uavcan::transfer::TransferFrameID;
/// use uavcan::transfer::TransferFrame;
///
/// #[derive(Debug, PartialEq)]
/// pub struct CanFrame {
///     pub id: TransferFrameID,
///     pub dlc: usize,
///     pub data: [u8; 8],
/// }
///
/// impl TransferFrame for CanFrame {
///     const MAX_DATA_LENGTH: usize = 8;
///
///     fn new(id: TransferFrameID) -> CanFrame {
///         CanFrame{id: id, dlc: 0, data: [0; 8]}
///     }
///
///     fn set_data_length(&mut self, length: usize) {
///         assert!(length <= 8);
///         self.dlc = length;
///     }
///
///     fn data(&self) -> &[u8] {
///         &self.data[0..self.dlc]
///     }
///
///     fn data_as_mut(&mut self) -> &mut[u8] {
///         &mut self.data[0..self.dlc]
///     }
///
///     fn id(&self) -> TransferFrameID {
///         self.id
///     }
/// }
///
/// assert!(Priority(CanFrame::new(TransferFrameID::new(0))) > Priority(CanFrame::new(TransferFrameID::new(1))));
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Priority<T>(pub T);



impl Eq for Priority<TransferFrameID> {}

impl PartialEq for Priority<TransferFrameID> {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq(&other.0)
    }
}

impl Ord for Priority<TransferFrameID> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0).reverse()
    }
}

impl PartialOrd for Priority<TransferFrameID> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}



impl<F: TransferFrame> Eq for Priority<F> {}


impl<F: TransferFrame> PartialEq for Priority<F> {
    fn eq(&self, other: &Self) -> bool {
        self.0.id().eq(&other.0.id())
    }
}

impl<F: TransferFrame> Ord for Priority<F> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.id().cmp(&other.0.id()).reverse()
    }
}

impl<F: TransferFrame> PartialOrd for Priority<F> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}


/// The last byte of the transfer frame data field, which contains auxiliary transport layer fields.
///
/// | SOT | EOT | Toggle | TID | TID | TID | TID | TID |
/// |-----|-----|--------|-----|-----|-----|-----|-----|
/// | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
///
/// ### Start of transfer (SOT)
/// For single-frame transfers, the value of this field is always 1.
///
/// For multi-frame transfers, the value of this field is 1 if the current frame is the first frame of the transfer, and 0 otherwise.
///
/// ### End of transfer (EOT)
/// For single-frame transfers, the value of this field is always 1.
///
/// For multi-frame transfers, the value of this field is 1 if the current frame is the last frame of the transfer, and 0 otherwise.
///
/// ### Toggle
/// For single-frame transfers, the value of this field is always 0.
///
/// For multi-frame transfers, this field contains the value of the toggle bit. As specified above this will alternate value between frames, starting at 0 for the first frame.
///
/// ### Transfer ID (TID)
/// This field contains the transfer ID value of the current transfer (for all types of transfers).
///
/// The value is 5 bits wide, therefore the allowed values range from 0 to 31, inclusively.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TailByte(u8);

impl TailByte {
    pub fn new(
        start_of_transfer: bool,
        end_of_transfer: bool,
        toggle: bool,
        transfer_id: TransferID,
    ) -> Self {
        TailByte(
            ((start_of_transfer as u8) << 7) |
            ((end_of_transfer as u8) << 6) |
            ((toggle as u8) << 5) |
            (u8::from(transfer_id))
        )
    }

    /// Checks if the SOT bit is asserted
    pub fn start_of_transfer(&self) -> bool {
        let TailByte(value) = *self;
        value & (1 << 7) != 0
    }

    /// Checks if the EOT bit is asserted
    pub fn end_of_transfer(&self) -> bool {
        let TailByte(value) = *self;
        value & (1 << 6) != 0
    }
    
    /// Checks if the toggle bit is asserted
    pub fn toggle(&self) -> bool {
        let TailByte(value) = *self;
        value & (1 << 5) != 0
    }
    
    /// Returns the `TransferID`
    pub fn transfer_id(&self) -> TransferID {
        let TailByte(value) = *self;
        TransferID::new(value & 0x1f)
    }
}


impl From<TailByte> for u8 {
    fn from(tb: TailByte) -> u8 {
        let TailByte(value) = tb;
        value
    }
}

impl From<u8> for TailByte {
    fn from(value: u8) -> TailByte {
        TailByte(value)
    }
}






impl From<TransferFrameID> for embedded_types::can::ExtendedID {
    fn from(id: TransferFrameID) -> Self {
        embedded_types::can::ExtendedID::new(u32::from(id))
    }
}

impl From<TransferFrameID> for embedded_types::can::ID {
    fn from(id: TransferFrameID) -> Self {
        embedded_types::can::ID::ExtendedID(embedded_types::can::ExtendedID::from(id))
    }
}

impl From<embedded_types::can::ExtendedID> for TransferFrameID {
    fn from(id: embedded_types::can::ExtendedID) -> Self {
        TransferFrameID::new(u32::from(id))
    }
}

impl TransferFrame for embedded_types::can::ExtendedDataFrame {
    const MAX_DATA_LENGTH: usize = 8;

    fn new(id: TransferFrameID) -> Self {
        embedded_types::can::ExtendedDataFrame::new(id.into())
    }
    fn set_data_length(&mut self, length: usize) {
        assert!(
            length <= Self::MAX_DATA_LENGTH,
            "ExtendedDataFrame::set_data_length() needs the length to be less than 8"
        );
        self.set_data_length(length);
    }
    fn data(&self) -> &[u8] {
        &self.data()
    }
    fn data_as_mut(&mut self) -> &mut [u8] {
        self.data_as_mut()
    }
    fn id(&self) -> TransferFrameID {
        self.id().into()
    }
}