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
mod address;
mod message;
mod payload;
mod pgn;

pub use address::*;
pub use message::*;
pub use payload::*;
pub use pgn::*;

use std::fmt::format;
use bitfield_struct::bitfield;
use crate::constant::EFF_MASK;
use crate::Conversion;

pub trait J1939 {
    /// Constructs a 29-bit J1939 identifier from its raw parts.
    fn from_raw_parts(
        priority: u8,
        data_page: bool,
        pdu_format: u8,
        pdu_specific: u8,
        source_addr: u8,
    ) -> Option<Self> where Self: Sized;

    /// Returns the priority bits indicating the priority level.
    ///
    /// 0 = highest priority
    fn priority(&self) -> u8;

    /// Returns the data page flag - 0 or 1
    fn data_page(&self) -> bool;

    /// Returns the PDU format bits specifying the Protocol Data Unit format.
    fn pdu_format(&self) -> u8;

    /// Returns the PDU specific bits providing additional details about the PDU.
    fn pdu_specific(&self) -> u8;

    /// Returns the source address bits identifying the source of the data.
    fn source_address(&self) -> SourceAddress;
}

/// Bitfield representation of a 29-bit J1939 CAN identifier.
///
/// ### Repr: `u32`
///
/// | Field                  | Size (bits) |
/// |------------------------|-------------|
/// | Padding bits (private) | 3           |
/// | Priority bits          | 3           |
/// | Reserved bits          | 1           |
/// | Data page bits         | 1           |
/// | PDU format bits        | 8           |
/// | PDU specific bits      | 8           |
/// | Source address bits    | 8           |
#[bitfield(u32, order = Msb)]
#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct J1939Id {
    #[bits(3)]
    _padding_bits: u8,
    #[bits(3)]
    priority_bits: u8,
    #[bits(1)]
    reserved_bits: bool,
    #[bits(1)]
    data_page_bits: bool,
    #[bits(8)]
    pdu_format_bits: u8,
    #[bits(8)]
    pdu_specific_bits: u8,
    #[bits(8)]
    source_address_bits: u8,
}

impl Conversion for J1939Id {
    type Type = u32;

    /// Creates a new 29-bit J1939 identifier from a 32-bit integer.
    ///
    /// # Examples
    /// ```rust
    /// use can_type_rs::Conversion;
    /// use can_type_rs::identifier::Id;
    /// use can_type_rs::j1939::J1939Id;
    /// let id_a = J1939Id::from_bits(0);
    /// let id_b = J1939Id::from_bits(4294967295);
    ///
    /// assert_eq!(0b000_000_0_0_00000000_00000000_00000000, id_a.into_bits());
    /// assert_eq!(0b111_111_1_1_11111111_11111111_11111111, id_b.into_bits());
    /// ```
    #[inline]
    fn from_bits(bits: u32) -> Self {
        J1939Id(bits)
    }

    /// Creates a new 29-bit J1939 identifier from a base-16 (hex) string slice.
    /// # Examples
    /// ```rust
    /// use can_type_rs::Conversion;
    /// use can_type_rs::identifier::Id;
    /// use can_type_rs::j1939::J1939Id;
    /// let hex_str = "0CF00400";
    ///
    /// let id_a = J1939Id::from_hex(hex_str);
    ///
    /// assert_eq!(0b000_011_0_0_11110000_00000100_00000000, id_a.into_bits());
    /// assert_eq!(217056256, id_a.into_bits());
    /// ```
    #[inline]
    fn from_hex(hex_str: &str) -> Self {
        let bits = u32::from_str_radix(hex_str, 16).unwrap_or_default();
        J1939Id(bits)
    }

    /// Creates a new 29-bit J1939 identifier from a 32-bit integer.
    ///
    /// # Examples
    /// ```rust
    /// use can_type_rs::Conversion;
    /// use can_type_rs::identifier::Id;
    /// use can_type_rs::j1939::J1939Id;
    /// let id_a = J1939Id::try_from_bits(0);
    /// let id_b = J1939Id::try_from_bits(4294967295);
    ///
    /// assert_eq!(0b000_000_0_0_00000000_00000000_00000000, id_a.unwrap().into_bits());
    /// assert!(id_b.is_none());
    /// ```
    #[inline]
    fn try_from_bits(bits: u32) -> Option<Self> {
        match bits {
            0..=EFF_MASK => Some(J1939Id(bits)),
            _ => None,
        }
    }

    /// Creates a new 29-bit J1939 identifier from a base-16 (hex) string slice.
    ///
    /// # Examples
    /// ```rust
    /// use can_type_rs::Conversion;
    /// use can_type_rs::identifier::Id;
    /// use can_type_rs::j1939::J1939Id;
    /// let id_a = J1939Id::try_from_hex("00FF00FF").unwrap();
    /// let id_b = J1939Id::try_from_hex("20000000");
    ///
    /// assert_eq!(0b000_0_0_11111111_00000000_11111111, id_a.into_bits());
    /// assert!(id_b.is_none())
    /// ```
    #[inline]
    fn try_from_hex(hex_str: &str) -> Option<Self> {
        match u32::from_str_radix(hex_str, 16) {
            Ok(v) => Self::try_from_bits(v),
            Err(_) => None,
        }
    }

    /// Creates a new 32-bit integer from the 29-bit J1939 identifier.
    ///
    /// # Examples
    /// ```rust
    /// use can_type_rs::Conversion;
    /// use can_type_rs::identifier::Id;
    /// use can_type_rs::j1939::J1939Id;
    /// let id_a = J1939Id::from_bits(0);
    ///
    /// assert_eq!(0, id_a.into_bits());
    /// ```
    #[inline]
    fn into_bits(self) -> u32 {
        self.into_bits()
    }

    /// Creates a new base-16 (hex) `String` from the 29-bit J1939 identifier.
    ///
    /// # Examples
    /// ```rust
    /// use can_type_rs::Conversion;
    /// use can_type_rs::identifier::Id;
    /// use can_type_rs::j1939::J1939Id;
    /// let id_a = J1939Id::from_bits(15);
    ///
    /// assert_eq!("0000000F", id_a.into_hex());
    /// ```
    #[inline]
    fn into_hex(self) -> String {
        format(format_args!("{:08X}", self.into_bits()))
    }
}

impl J1939 for J1939Id {
    /// Constructs a 29-bit J1939 identifier from its raw parts.
    ///
    /// # Arguments
    /// - `priority`: `u8`.
    /// - `reserved`: `bool`.
    /// - `data_page`: `bool`.
    /// - `pdu_format`: `u8`.
    /// - `pdu_specific`: `u8`.
    /// - `source_addr`: `u8`.
    #[inline]
    fn from_raw_parts(
        priority: u8,
        data_page: bool,
        pdu_format: u8,
        pdu_specific: u8,
        source_addr: u8,
    ) -> Option<Self> {
        match priority {
            0..=0x70 => {
                let bitfield = J1939Id::new()
                    .with_priority_bits(priority)
                    .with_data_page_bits(data_page)
                    .with_pdu_format_bits(pdu_format)
                    .with_pdu_specific_bits(pdu_specific)
                    .with_source_address_bits(source_addr);
                Some(bitfield)
            },
            _ => None,
        }
    }

    /// Returns the priority bits indicating the priority level.
    ///
    /// 0 = highest priority
    #[inline]
    #[must_use]
    fn priority(&self) -> u8 {
        self.priority_bits()
    }

    /// Returns the data page flag - 0 or 1
    #[inline]
    #[must_use]
    fn data_page(&self) -> bool {
        self.data_page_bits()
    }

    /// Returns the PDU format bits specifying the Protocol Data Unit format.
    #[inline]
    #[must_use]
    fn pdu_format(&self) -> u8 {
        self.pdu_format_bits()
    }

    /// Returns the PDU specific bits providing additional details about the PDU.
    #[inline]
    #[must_use]
    fn pdu_specific(&self) -> u8 {
        self.pdu_specific_bits()
    }

    /// Returns the source address bits identifying the source of the data.
    #[inline]
    #[must_use]
    fn source_address(&self) -> SourceAddress {
        SourceAddress::Some(self.source_address_bits())
    }
}