xcp_registry 0.1.0

Measurement and Calibration registry for XCP - pure Rust, no C dependency
Documentation
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
439
440
441
442
443
444
445
446
447
448
449
450
// Module address
// McAddress

use serde::{Deserialize, Serialize};

use super::{McIdentifier, Registry};

//-------------------------------------------------------------------------------------------------
// Address Mode Enum

/// Address modes for accessing measurement and calibration data
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[non_exhaustive]
pub enum McAddrMode {
    /// Calibration segment relative addressing
    Cal = 0,
    /// Absolute addressing (not implemented for Rust)
    Abs = 1,
    /// Dynamic addressing (event relative addressing, async access)
    Dyn = 2,
    /// Generic A2L address
    A2l = 0xA0,
    /// A2L address with event association
    A2lEvent = 0xA1,
    /// Undefined addressing mode
    Undef = 0xFF,
}

impl Default for McAddrMode {
    fn default() -> Self {
        McAddrMode::Cal
    }
}

impl McAddrMode {
    /// Check if this addressing mode is segment relative
    pub fn is_segment_relative(&self) -> bool {
        matches!(self, McAddrMode::Cal)
    }

    /// Check if this addressing mode is event relative
    pub fn is_event_relative(&self) -> bool {
        matches!(self, McAddrMode::Dyn)
    }

    /// Check if this is an A2L addressing mode
    pub fn is_a2l(&self) -> bool {
        matches!(self, McAddrMode::A2l | McAddrMode::A2lEvent)
    }

    /// Convert to u8 representation
    pub fn as_u8(&self) -> u8 {
        *self as u8
    }
}

//-------------------------------------------------------------------------------------------------
// McAddress
// Information needed to access data instances

/// Addressing information of a measurement or calibration object
/// Calibration segment relative, event relative, absolute or a raw A2L address, see [`McAddrMode`]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct McAddress {
    #[serde(skip_serializing_if = "Option::is_none")]
    calseg_name: Option<McIdentifier>, // Name of the calibration segment of a calibration object

    #[serde(skip_serializing_if = "Option::is_none")]
    event_id: Option<u16>, // Event id of a measurement signal

    #[serde(default = "default_addr_offset")]
    #[serde(skip_serializing_if = "skip_addr_offset")]
    addr_offset: i32, // Offset relative to calibration segment (XCP_ADDR_EXT_SEG,calseg_name.is_some) or relative to event base address (XCP_ADDR_EXT_DYN..,event_id.is_some)

    addr_mode: McAddrMode, // Addressing mode

    #[serde(default = "default_a2l_addr")]
    #[serde(skip_serializing_if = "skip_a2l_addr")]
    a2l_addr: u32, // XCP address, used if data description is generated from a third party A2L file

    #[serde(default = "default_a2l_addr_ext")]
    #[serde(skip_serializing_if = "skip_a2l_addr_ext")]
    a2l_addr_ext: u8, // XCP address extensionAddress,, used if data description is generated from a third party A2L file, otherwise XCP_ADDR_EXT_UNDEF
}

impl Default for McAddress {
    fn default() -> Self {
        McAddress {
            calseg_name: None,
            event_id: None,
            addr_offset: McAddress::XCP_ADDR_OFFSET_UNDEF,
            addr_mode: McAddrMode::Cal,
            a2l_addr: 0,
            a2l_addr_ext: 0,
        }
    }
}

// Defaults for deserializer
fn default_a2l_addr_ext() -> u8 {
    0
}
fn default_a2l_addr() -> u32 {
    0
}
fn default_addr_offset() -> i32 {
    McAddress::XCP_ADDR_OFFSET_UNDEF
}

// Skip on defaults
fn skip_a2l_addr_ext(value: &u8) -> bool {
    *value == 0
}
fn skip_a2l_addr(value: &u32) -> bool {
    *value == 0
}
fn skip_addr_offset(value: &i32) -> bool {
    *value == McAddress::XCP_ADDR_OFFSET_UNDEF
}

impl McAddress {
    // XCPlite addressing modes (for default addressing scheme XCPLITE__CASDD in XCPlite):

    /// Segment relative addressing (for CAL objects) ((index|0x8000)<<16+offset)  (CANape does not support addr_ext != 0 in memory segments))
    pub const XCP_ADDR_EXT_SEG: u8 = 0;

    /// Absolute addressing (not used for rust, but registry can handle it)
    pub const XCP_ADDR_EXT_ABS: u8 = 1;

    /// Base pointer relative addressing (for DAQ objects and asychronous read/write access)
    /// xcp-lite for Rust uses only one base pointer for event relative addressing (in xcplib, the base pointer index is encoded in the address extension (XCP_ADDR_EXT_DYN+index)
    /// We call XcpEventExt(baseptr-XCP_ADDR_EXT_DYN_OFFSET_OFFSET) to allow offsets in the range [-XCP_ADDR_EXT_DYN_OFFSET_OFFSET, XCP_ADDR_EXT_DYN_OFFSET_MASK-XCP_ADDR_EXT_DYN_OFFSET_OFFSET]
    pub const XCP_ADDR_EXT_DYN: u8 = 2;
    /// Offset added to an event relative address offset, negative offsets down to `-XCP_ADDR_EXT_DYN_OFFSET_OFFSET` can be encoded
    pub const XCP_ADDR_EXT_DYN_OFFSET_OFFSET: i32 = 0x10000;
    /// Number of address bits used for the offset of an event relative address
    pub const XCP_ADDR_EXT_DYN_OFFSET_BITS: u8 = 22;
    /// Mask for the offset bits of an event relative address
    pub const XCP_ADDR_EXT_DYN_OFFSET_MASK: u32 = 0x003FFFFF;

    /// Undefined
    pub const XCP_ADDR_EXT_UNDEF: u8 = 0xFF;
    /// Undefined address offset
    pub const XCP_ADDR_OFFSET_UNDEF: i32 = 0x80000000u32.cast_signed();

    /// Create a calibration segment relative address, `addr_offset` bytes from the start of the calibration segment `calseg_name`
    pub fn new_calseg_rel<T: Into<McIdentifier>>(calseg_name: T, addr_offset: i32) -> Self {
        McAddress {
            calseg_name: Some(calseg_name.into()),
            event_id: None,
            addr_offset,
            addr_mode: McAddrMode::Cal,
            a2l_addr: 0,
            a2l_addr_ext: McAddress::XCP_ADDR_EXT_SEG,
        }
    }

    /// Create an absolute address `addr_offset` for an object associated with the event `event_id`
    pub fn new_event_abs(event_id: u16, addr_offset: i32) -> Self {
        McAddress {
            calseg_name: None,
            event_id: Some(event_id),
            addr_offset,
            addr_mode: McAddrMode::Abs,
            a2l_addr: 0,
            a2l_addr_ext: McAddress::XCP_ADDR_EXT_ABS,
        }
    }

    /// Dynamic event relative addressing
    /// # Arguments
    /// * `index` - Index of the dynamic address space (XCP_ADDR_EXT_DYN+index)
    /// * `event_id` - Event id of the measurement signal
    /// * `addr_offset` - Address offset relative to the event base address
    /// # Returns
    /// McAddress instance
    pub fn new_event_dyn(index: u8, event_id: u16, addr_offset: i32) -> Self {
        McAddress {
            calseg_name: None,
            event_id: Some(event_id),
            addr_offset,
            addr_mode: McAddrMode::Dyn,
            a2l_addr: 0,
            a2l_addr_ext: McAddress::XCP_ADDR_EXT_DYN + index,
        }
    }

    /// Create an address from a raw A2L address and address extension, as read from an A2L file
    pub fn new_a2l(a2l_addr: u32, a2l_addr_ext: u8) -> Self {
        McAddress {
            calseg_name: None,
            event_id: None,
            addr_offset: McAddress::XCP_ADDR_OFFSET_UNDEF,
            addr_mode: McAddrMode::A2l,
            a2l_addr,
            a2l_addr_ext,
        }
    }

    /// Create an address from a raw A2L address and address extension with an associated event, as read from an A2L file with `IF_DATA XCP`
    pub fn new_a2l_with_event(event_id: u16, a2l_addr: u32, a2l_addr_ext: u8) -> Self {
        McAddress {
            calseg_name: None,
            event_id: Some(event_id),
            addr_offset: 0,
            addr_mode: McAddrMode::A2lEvent,
            a2l_addr,
            a2l_addr_ext,
        }
    }

    /// Get address mode
    pub fn get_addr_mode(&self) -> McAddrMode {
        self.addr_mode
    }

    /// Get A2L address extension
    pub fn get_a2l_addr_ext(&self) -> u8 {
        self.a2l_addr_ext
    }

    /// Check address mode is absolute
    pub fn is_absolute(&self) -> bool {
        self.addr_mode == McAddrMode::Abs || self.addr_mode == McAddrMode::A2l || self.addr_mode == McAddrMode::A2lEvent
    }

    /// Check address mode is segment relative
    /// # Panics
    /// If the address is segment relative, but has no calibration segment name
    pub fn is_segment_relative(&self) -> bool {
        if self.addr_mode.is_segment_relative() {
            assert!(self.calseg_name.is_some());
            true
        } else {
            false
        }
    }

    /// Check address mode is event relative
    /// # Panics
    /// If the address is event relative, but has no event id
    pub fn is_event_relative(&self) -> bool {
        if self.addr_mode.is_event_relative() {
            assert!(self.event_id.is_some());
            true
        } else {
            false
        }
    }

    /// Get name of the calibration segment of a calibration object
    pub fn get_calseg_name(&self) -> Option<McIdentifier> {
        self.calseg_name
    }

    /// Get event id of the event associated with a measurement signal
    pub fn get_event_id(&self) -> Option<u16> {
        self.event_id
    }
    /// Get the event id, `0xFFFF` if there is none
    pub fn get_event_id_unchecked(&self) -> u16 {
        self.get_event_id().unwrap_or(
            0xFFFF, // Invalid event id, used in sorting by event id
        )
    }

    /// Get relative address offset to event or calibration segment
    /// # Panics
    /// If the address is not segment or event relative
    pub fn get_addr_offset(&self) -> i32 {
        match self.addr_mode {
            McAddrMode::Cal | McAddrMode::Dyn => self.addr_offset,
            McAddrMode::A2l | McAddrMode::A2lEvent => panic!("A2L address does not have an offset"),
            McAddrMode::Abs | McAddrMode::Undef => panic!("Address mode not supported"),
        }
    }

    /// Add an offset to an address
    /// # Panics
    /// If the address mode is `Undef`
    // Infallible: value is always < u32::MAX (bounded by protocol)
    #[allow(clippy::cast_possible_truncation)]
    #[allow(clippy::cast_sign_loss)]
    pub fn add_addr_offset(&mut self, offset: i32) {
        match self.addr_mode {
            McAddrMode::Cal | McAddrMode::Dyn => {
                self.addr_offset += offset;
            }
            McAddrMode::A2l | McAddrMode::A2lEvent => {
                self.a2l_addr = (self.a2l_addr as i64 + offset as i64) as u32;
            }
            McAddrMode::Abs => {
                self.addr_offset += offset;
            }
            McAddrMode::Undef => panic!("Address mode Undef"),
        }
    }

    fn get_abs_ext_addr(offset: u32) -> (u8, u32) {
        let a2l_ext = McAddress::XCP_ADDR_EXT_ABS;
        #[allow(clippy::cast_sign_loss)]
        let a2l_addr: u32 = offset;
        (a2l_ext, a2l_addr)
    }

    fn get_dyn_ext_addr(addr_ext: u8, event_id: u16, offset: i32) -> (u8, u32) {
        assert!(
            addr_ext >= McAddress::XCP_ADDR_EXT_DYN && addr_ext < McAddress::XCP_ADDR_EXT_DYN + 16,
            "Invalid address extension for DYN addressing"
        );
        assert!(
            offset >= -McAddress::XCP_ADDR_EXT_DYN_OFFSET_OFFSET && offset <= McAddress::XCP_ADDR_EXT_DYN_OFFSET_MASK.cast_signed() - McAddress::XCP_ADDR_EXT_DYN_OFFSET_OFFSET,
            "Offset out of range for DYN addressing"
        );
        let a2l_addr: u32 = ((event_id as u32) << McAddress::XCP_ADDR_EXT_DYN_OFFSET_BITS)
            | ((offset + McAddress::XCP_ADDR_EXT_DYN_OFFSET_OFFSET).cast_unsigned() & McAddress::XCP_ADDR_EXT_DYN_OFFSET_MASK);
        (addr_ext, a2l_addr)
    }

    /// Get A2L addr (ext,addr) of a CalSeg
    pub fn get_calseg_ext_addr_base(calseg_index: u16) -> (u8, u32) {
        // McAddress format for calibration segment field is index | 0x8000 in high word, addr_ext is 0 (CANape does not support addr_ext in memory segments)
        let addr_ext = McAddress::XCP_ADDR_EXT_SEG;
        let addr = ((calseg_index as u32) | 0x8000) << 16;
        (addr_ext, addr)
    }

    /// Get A2L addr (ext,addr) for a calibration value field at offset in a CalSeg
    /// The address is relative to the base addr of the calibration segment
    pub fn get_calseg_ext_addr(calseg_index: u16, offset: u16) -> (u8, u32) {
        {
            let (addr_ext, mut addr) = McAddress::get_calseg_ext_addr_base(calseg_index);
            addr += offset as u32;
            (addr_ext, addr)
        }
    }

    /// Get address extension and address for A2L generation and the XCP protocol
    /// # Panics
    /// If the calibration segment of a segment relative address is not in `registry`,
    /// if the offset is out of range for the address mode, or if the address mode is `Undef`
    pub fn get_a2l_addr(&self, registry: &Registry) -> (u8, u32) {
        match self.addr_mode {
            // Event relative addressing with async access
            McAddrMode::Dyn => McAddress::get_dyn_ext_addr(self.a2l_addr_ext, self.event_id.unwrap(), self.addr_offset),
            // Absolute addressing with default event
            McAddrMode::Abs => McAddress::get_abs_ext_addr(self.addr_offset.try_into().expect("get_a2l_addr: addr too large")),
            // Explicit segment relative addressing
            McAddrMode::Cal => {
                let name = self.calseg_name.as_ref().expect("get_a2l_addr: Calibration segment name not set");
                let index = registry
                    .cal_seg_list
                    .get_cal_seg_index(name)
                    .unwrap_or_else(|| panic!("get_a2l_addr: Calibration segment {} not found", name));
                McAddress::get_calseg_ext_addr(index, self.addr_offset.try_into().expect("get_a2l_addroffset too large"))
            }
            // Explicit A2L address
            McAddrMode::A2l | McAddrMode::A2lEvent => (self.a2l_addr_ext, self.a2l_addr),
            // Undefined address mode
            McAddrMode::Undef => panic!("get_a2l_addr: Undefined address mode"),
        }
    }

    /// Get raw A2L addr (ext,addr) stored in the McAddress
    /// This is used when the address is imported from a third party A2L file
    /// No conversion is done
    /// # Panics
    /// If the address mode is not A2L
    pub fn get_raw_a2l_addr(&self) -> (u8, u32) {
        assert!(self.addr_mode.is_a2l(), "Raw A2L address is only available for A2L addressing modes");
        (self.a2l_addr_ext, self.a2l_addr)
    }
}

impl std::fmt::Display for McAddress {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)?;
        Ok(())
    }
}

// Implement cmp and ord for sorting by event_id, addr_ext, addr, name
impl PartialOrd for McAddress {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for McAddress {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let mode1 = self.addr_mode;
        let mode2 = other.addr_mode;
        if mode1 != mode2 {
            mode1.cmp(&mode2)
        } else if self.addr_mode.is_a2l() {
            if self.a2l_addr_ext != other.a2l_addr_ext {
                self.a2l_addr_ext.cmp(&other.a2l_addr_ext)
            } else if self.a2l_addr != other.a2l_addr {
                self.a2l_addr.cmp(&other.a2l_addr)
            } else {
                std::cmp::Ordering::Equal
            }
        } else {
            self.addr_offset.cmp(&other.addr_offset)
        }
    }
}

//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
// Test module

#[cfg(test)]
mod mc_address_tests {

    use super::*;

    #[test]
    fn test_mc_address() {
        let mut reg = Registry::new();
        reg.cal_seg_list.add_a2l_cal_seg("calseg", 0, None, 0, 0x80000000, 0x1000).unwrap();

        let addr = McAddress::new_calseg_rel("calseg", 11);
        assert_eq!(addr.get_calseg_name(), Some(McIdentifier::new("calseg")));
        assert_eq!(addr.get_event_id(), None);
        assert_eq!(addr.get_addr_offset(), 11);
        let a = addr.get_a2l_addr(&reg);
        assert!(a.0 == McAddress::XCP_ADDR_EXT_SEG);
        assert_eq!(a.1, 0x80000000 + 11);

        {
            let addr = McAddress::new_event_dyn(0, 2, -1);
            assert_eq!(addr.get_calseg_name(), None);
            assert_eq!(addr.get_event_id(), Some(2));
            assert_eq!(addr.get_addr_offset(), -1);
            let a = addr.get_a2l_addr(&reg);
            assert!(a.0 == McAddress::XCP_ADDR_EXT_DYN);
            // The offset is stored with XCP_ADDR_EXT_DYN_OFFSET_OFFSET added, so -1 becomes 0xFFFF
            assert_eq!(a.1, 2 << McAddress::XCP_ADDR_EXT_DYN_OFFSET_BITS | 0xFFFF);

            let addr = McAddress::new_event_dyn(0, 2, 0x7FFF);
            assert_eq!(addr.get_calseg_name(), None);
            assert_eq!(addr.get_event_id(), Some(2));
            assert_eq!(addr.get_addr_offset(), 0x7FFF);
            let a = addr.get_a2l_addr(&reg);
            assert!(a.0 == McAddress::XCP_ADDR_EXT_DYN);
            assert_eq!(a.1, 2 << McAddress::XCP_ADDR_EXT_DYN_OFFSET_BITS | 0x17FFF);
        }
    }
}