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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//-----------------------------------------------------------------------------
// Crate xcp_registry
// Registry for calibration segments, instances of parameters and measurement signals, type definitions and events
// Standalone pure-Rust crate — no C/xcplib dependency

#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![doc = include_str!("../README.md")]

// EPK calibration segment constants
// Used by the A2L reader/writer to identify the XCPlite EPK segment
pub(crate) const EPK_SEG_NAME: &str = "epk";

use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::{Mutex, MutexGuard, PoisonError};
use thiserror::Error;

// Registry
mod mc_registry;
pub use mc_registry::McApplication;
pub use mc_registry::Registry;

// A2L reader and writer
mod a2l;
pub use a2l::McA2mlMode;

/// ASAM XCP 1.4 A2ML description (content of the file XCP_104.aml)
/// Embedded into A2L files with `McA2mlMode::Embed`, or to be written next to an A2L file which includes "XCP_104.aml"
pub const XCP_104_AML: &str = include_str!("../XCP_104.aml");

// McEvent
mod mc_event;
pub use mc_event::McEvent;
pub use mc_event::McEventList;

// McCalibrationSegment
mod mc_calseg;
pub use mc_calseg::McCalibrationSegment;
pub use mc_calseg::McCalibrationSegmentList;

// McInstance
mod mc_instance;
pub use mc_instance::McInstance;
pub use mc_instance::McInstanceList;

// McTypeDef
mod mc_typedef;
pub use mc_typedef::McTypeDef;
pub use mc_typedef::McTypeDefField;
pub use mc_typedef::McTypeDefList;

// McObjectType, McSupportData
mod mc_support;
pub use mc_support::McObjectQualifier;
pub use mc_support::McObjectType;
pub use mc_support::McSupportData;

// McValueType, McDimType
mod mc_type;
pub use mc_type::McDimType;
pub use mc_type::McValueType;
pub use mc_type::McValueTypeTrait;

// McAddress
mod mc_address;
pub use mc_address::McAddrMode;
pub use mc_address::McAddress;

// McText
mod mc_text;
pub use mc_text::McIdentifier;
pub use mc_text::McText;

// McRegisterType (runtime support for the #[derive(McRegisterType)] proc-macro)
mod mc_register_type;
pub use mc_register_type::McEnumType;
pub use mc_register_type::McRegisterContext;
pub use mc_register_type::McRegisterTarget;
pub use mc_register_type::McRegisterType;

// Re-export the derive macros (serde-style: one import brings the trait and the derive)
pub use xcp_registry_derive::McRegisterEnum;
pub use xcp_registry_derive::McRegisterType;

//-----------------------------------------------------------------------------
// Removed: the old RegisterFieldsTrait blanket impl that walked StructDescriptor /
// FieldDescriptor trees. Registration is now generated directly by #[derive(McRegisterType)]
// (see mc_register_type.rs and the xcp_registry_derive crate).

//----------------------------------------------------------------------------------------------
// Error

/// Error type returned by functions of the registry API
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum RegistryError {
    /// I/O error while reading or writing a file
    #[error("io error")]
    Io(#[from] std::io::Error),

    /// An object with this name already exists
    #[error("registry error: duplicate symbol `{0}` ")]
    Duplicate(String),

    /// No object with this name was found
    #[error("registry error: `{0}` not found")]
    NotFound(String),

    /// No event with this id is defined
    #[error("registry error: event id not defined `{0}` ")]
    UnknownEventChannel(u16),

    /// The field already has metadata, it can not be set again
    #[error("registry error: metadata already set for field `{0}`")]
    MetadataAlreadySet(String),

    /// An index exceeds its value range
    #[error("registry error: index overflow")]
    IndexOverflow,

    /// The object type of the named object is `McObjectType::Unspecified`
    #[error("registry error: object type of `{0}` is unspecified")]
    ObjectTypeUnspecified(String),

    /// An A2L file could not be read or used, with a description of the problem
    #[error("A2L error: {0}")]
    A2l(String),

    /// Unspecified error
    #[error("unknown error")]
    Unknown,
}

//-------------------------------------------------------------------------------------------------
// McXcpTransportLayer
// XCP Transport layer parameters
// For A2l XCP IF_DATA

/// XCP transport layer parameters, written to the `IF_DATA XCP` block of the A2L file
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct McXcpTransportLayer {
    /// Protocol name: `"UDP"`, `"TCP"`, `"CAN"` or `"SxI"`
    pub protocol_name: &'static str,
    /// IPv4 address of the XCP server, for UDP and TCP
    pub addr: Option<Ipv4Addr>,
    /// Port of the XCP server, for UDP and TCP
    pub port: Option<u16>,
    /// Baud rate, for SxI
    pub baud_rate: Option<u32>,
}

impl Default for McXcpTransportLayer {
    fn default() -> Self {
        McXcpTransportLayer {
            protocol_name: "UDP",
            addr: Some(Ipv4Addr::new(127, 0, 0, 1)),
            port: Some(5555),
            baud_rate: None,
        }
    }
}

//-------------------------------------------------------------------------------------------------
// McXcpProtocolLayer
// XCP Protocol layer parameters
// For A2l XCP IF_DATA

/// XCP protocol layer parameters, written to the `IF_DATA XCP` block of the A2L file
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub struct McXcpProtocolLayer {
    /// Maximum size of a command packet (CTO) in bytes
    pub max_cto: u8,
    /// Maximum size of a data packet (DTO) in bytes
    pub max_dto: u16,
}

impl Default for McXcpProtocolLayer {
    fn default() -> Self {
        McXcpProtocolLayer { max_cto: 8, max_dto: 8 }
    }
}

//-------------------------------------------------------------------------------------------------
// Registry singleton

/// Open registry singleton
/// Open for modification, mutable access through Mutex
/// Registry is closed when None
static REGISTRY: Mutex<Option<Registry>> = Mutex::new(None);

/// Closed registry singleton
/// (Finalized and read only after call to `Registry::close()`)
// A Mutex, not a OnceLock, because `registry_test::test_reinit()` must be able to reset it
static CLOSED_REGISTRY: Mutex<Option<&'static Registry>> = Mutex::new(None);

// Lock a singleton mutex, ignoring poisoning (a panic in another thread while it held the lock)
fn lock<T>(m: &'static Mutex<T>) -> MutexGuard<'static, T> {
    m.lock().unwrap_or_else(PoisonError::into_inner)
}

//---------------------------------------------------------------------------------------------------------
// Associated function for the registry singleton

/// Initialize the mutable registry singleton
pub fn init() {
    let mut l = lock(&REGISTRY);
    if l.is_none() {
        *l = Some(Registry::new());
        log::info!("Registry initialized");
    } else {
        log::info!("Registry already initialized");
    }
}

/// Lock guard for the mutable registry singleton, returned by [`get_lock`]
/// Dereferences to `Option<Registry>`, which is `None` when the registry is closed
#[derive(Debug)]
pub struct RegistryGuard(MutexGuard<'static, Option<Registry>>);

impl std::ops::Deref for RegistryGuard {
    type Target = Option<Registry>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for RegistryGuard {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Get a lock on the mutable registry singleton
/// # Panics
/// If the registry is not initialized with registry::init
/// # Returns
/// None if the registry is closed
pub fn get_lock() -> RegistryGuard {
    // Check if registry is closed, it should be None then
    #[cfg(not(test))]
    if lock(&CLOSED_REGISTRY).is_some() {
        let l = lock(&REGISTRY);
        assert!(l.is_none());
        return RegistryGuard(l);
    }

    let l = lock(&REGISTRY);
    assert!(l.is_some(), "Registry not initialized!");
    RegistryGuard(l)
}

/// Get a reference to the closed registry singleton
/// Close and flatten if not already closed
/// # Panics
/// If the registry is not initialized with [`init`]
pub fn get() -> &'static Registry {
    if lock(&CLOSED_REGISTRY).is_none() {
        // Close the mutable registry singleton
        // Flatten typedefs
        log::warn!("Automatically close registry - call to Registry::get() without explictic close!");
        close();
    }
    lock(&CLOSED_REGISTRY).unwrap()
}

/// Get closed status   
pub fn is_closed() -> bool {
    lock(&CLOSED_REGISTRY).is_some()
}

/// Close registry
/// No more changes allowed
/// Move registry to read only singleton
/// # Panics
/// If the registry is not initialized with [`init`]
pub fn close() {
    // Check if registry is already closed
    if is_closed() {
        log::warn!("Mutable registry singleton already closed !");
        return;
    }

    // Move mutable registry singleton out
    log::info!("Mutable registry singleton closed !");
    let mut reg = get_lock().take().unwrap();

    // Flatten the registry if requested
    if reg.get_flatten_typedefs_mode() {
        flatten_registry(&mut reg);
    }

    // Move mutable registry singleton to closed singleton
    *lock(&CLOSED_REGISTRY) = Some(Box::leak(Box::new(reg)));
    // CLOSED_REGISTRY.get().unwrap()

    // log::info!("Registry instance list:");
    // for i in &get().instance_list {
    //     log::info!("  {}: {:?} {}", i.name, i.dim_type.value_type, i.address.get_addr_offset());
    // }
}

// Expand a typedef-typed slot (a single struct, or an array/matrix of structs) into flattened
// leaf instances. A scalar struct is expanded in place; an array of structs is unrolled element
// by element, each element getting a dotted index suffix (`name._i`, or `name._iy_ix` for a 2D
// matrix) and an address offset of `element_index * typedef.size`. The dotted `._i` form is used
// because the A2L writer sanitizes `[` / `]` to `_`.
#[allow(clippy::too_many_arguments)]
fn expand_typedef_slot(
    reg: &Registry,
    new_instances: &mut McInstanceList,
    typedef_index: &HashMap<&'static str, usize>,
    base_name: &str,
    root_instance_address: &McAddress,
    base_offset: i32,
    dim_type: &McDimType,
    typedef: &McTypeDef,
) {
    let [x_dim, y_dim] = dim_type.get_dim();

    // Scalar struct (no array dimensions): expand in place.
    if x_dim <= 1 && y_dim <= 1 {
        collect_flattened_instances(reg, new_instances, typedef_index, base_name.to_string(), root_instance_address, base_offset, typedef);
        return;
    }

    // Array or matrix of structs: unroll element by element.
    let columns = x_dim.max(1);
    let rows = y_dim.max(1);
    let stride = i32::try_from(typedef.size).expect("Typedef size exceeds i32::MAX");
    for iy in 0..rows {
        for ix in 0..columns {
            let element_index = iy as i32 * columns as i32 + ix as i32;
            let element_offset = base_offset + element_index * stride;
            let element_name = if y_dim > 1 {
                format!("{}._{}_{}", base_name, iy, ix)
            } else {
                format!("{}._{}", base_name, ix)
            };
            collect_flattened_instances(reg, new_instances, typedef_index, element_name, root_instance_address, element_offset, typedef);
        }
    }
}

// Recursive helper function to build additional flattened instances from typedefs
// Collect all typedef tree leafs and mangle the instance name
fn collect_flattened_instances(
    reg: &Registry,
    new_instances: &mut McInstanceList,
    typedef_index: &HashMap<&'static str, usize>,
    name: String,
    root_instance_address: &McAddress,
    root_address_offset: i32,
    typedef: &McTypeDef,
) {
    for field in &typedef.fields {
        let mangled_name = format!("{}.{}", name, field.name);
        if let Some(typedef_name) = field.get_typedef_name() {
            let i = *typedef_index.get(typedef_name).unwrap();
            let field_typedef = reg.typedef_list.get(i).unwrap();
            // A field may be a single struct or an array/matrix of structs; unroll arrays.
            expand_typedef_slot(
                reg,
                new_instances,
                typedef_index,
                &mangled_name,
                root_instance_address,
                root_address_offset + field.offset as i32,
                &field.dim_type,
                field_typedef,
            );
        } else {
            let mut address = *root_instance_address;
            address.add_addr_offset(root_address_offset + field.offset as i32);
            let _ = new_instances.add_instance(mangled_name, field.dim_type.clone(), field.mc_support_data.clone(), address);
        }
    }
}

// Collect all instance leafs and create new instances with mangled names
fn create_flattened_instance_list(reg: &mut Registry, typedef_index: &HashMap<&'static str, usize>) -> McInstanceList {
    let mut flat_instance_list = McInstanceList::new();
    for instance in &reg.instance_list {
        let name: String = instance.get_name().to_string();
        if let Some(typedef_name) = instance.get_typedef_name() {
            if let Some(i) = typedef_index.get(typedef_name) {
                // A top-level instance may be a single struct or an array/matrix of structs.
                expand_typedef_slot(
                    reg,
                    &mut flat_instance_list,
                    typedef_index,
                    &name,
                    instance.get_address(),
                    0,
                    instance.get_dim_type(),
                    reg.typedef_list.get(*i).unwrap(),
                );
            } else {
                log::error!("Typedef {} not found in typedef list", typedef_name);
            }
        } else {
            // No typedef, just add the instance
            let _ = flat_instance_list.add_instance(name, instance.dim_type.clone(), instance.get_mc_support_data().clone(), *instance.get_address());
        }
    }
    flat_instance_list
}

/// Replace all instances of a typedef in `reg` by instances of basic type, one for each leaf field, with mangled names (`instance.field`, `instance._i.field` for array elements)
/// # Panics
/// If a typedef refers to a typedef which is not in the registry
pub fn flatten_registry(reg: &mut Registry) {
    log::info!("Flattening typedef structure in registry into mangled instance names !");

    // Build typedef (name,index) hashmap
    let typedef_index: &HashMap<&str, usize> = &reg
        .typedef_list
        .into_iter()
        .enumerate()
        .map(|(index, typedef)| (typedef.get_name(), index))
        .collect::<std::collections::HashMap<_, _>>();
    // log::info!("Registry typedef index:");
    // log::Info!("{:#?}", typedef_index);

    reg.instance_list = create_flattened_instance_list(reg, typedef_index);
    reg.typedef_list.clear();
    // for i in &reg.instance_list {
    //     log::info!("  + {}: {:?} {}", i.name, i.dim_type.value_type, i.address.get_addr_offset());
    // }
}

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

#[doc(hidden)]
pub mod registry_test {
    use super::*;

    pub fn test_reinit() {
        *lock(&REGISTRY) = Some(Registry::new());
        *lock(&CLOSED_REGISTRY) = None;
    }
}

#[cfg(test)]
mod flatten_tests {
    use super::*;

    fn offset_of(reg: &Registry, name: &str) -> i32 {
        reg.instance_list
            .get_instance(name, McObjectType::Characteristic, None)
            .unwrap_or_else(|| panic!("flattened instance '{}' not found", name))
            .get_address()
            .get_addr_offset()
    }

    // Flattening must unroll arrays of structs element by element, both as a nested
    // typedef field and as a top-level instance, accumulating per-element offsets.
    #[test]
    fn flatten_array_of_structs() {
        let mut reg = Registry::new();
        let cal = McSupportData::new(McObjectType::Characteristic);

        // typedef Inner { a: u8 @0, b: u16 @2 }  size 4
        reg.add_typedef("Inner", 4).unwrap();
        reg.add_typedef_field("Inner", "a", McDimType::new(McValueType::Ubyte, 1, 1), cal.clone(), 0).unwrap();
        reg.add_typedef_field("Inner", "b", McDimType::new(McValueType::Uword, 1, 1), cal.clone(), 2).unwrap();

        // typedef Outer { items: [Inner; 3] @0, count: u32 @12 }  size 16
        reg.add_typedef("Outer", 16).unwrap();
        reg.add_typedef_field("Outer", "items", McDimType::new(McValueType::new_typedef("Inner"), 3, 1), cal.clone(), 0)
            .unwrap();
        reg.add_typedef_field("Outer", "count", McDimType::new(McValueType::Ulong, 1, 1), cal.clone(), 12).unwrap();

        // instance outer: Outer @ calseg offset 0x10
        reg.instance_list
            .add_instance(
                "outer",
                McDimType::new(McValueType::new_typedef("Outer"), 1, 1),
                cal.clone(),
                McAddress::new_calseg_rel("seg", 0x10),
            )
            .unwrap();

        // instance arr: [Inner; 2] @ calseg offset 0x40
        reg.instance_list
            .add_instance(
                "arr",
                McDimType::new(McValueType::new_typedef("Inner"), 2, 1),
                cal.clone(),
                McAddress::new_calseg_rel("seg", 0x40),
            )
            .unwrap();

        flatten_registry(&mut reg);

        // Typedefs are dropped after flattening
        assert!(reg.typedef_list.is_empty(), "typedef list should be empty after flattening");

        // Nested array-of-structs field is unrolled with dotted indices and accumulated offsets
        assert_eq!(offset_of(&reg, "outer.items._0.a"), 0x10);
        assert_eq!(offset_of(&reg, "outer.items._0.b"), 0x12);
        assert_eq!(offset_of(&reg, "outer.items._1.a"), 0x14);
        assert_eq!(offset_of(&reg, "outer.items._1.b"), 0x16);
        assert_eq!(offset_of(&reg, "outer.items._2.a"), 0x18);
        assert_eq!(offset_of(&reg, "outer.items._2.b"), 0x1A);
        assert_eq!(offset_of(&reg, "outer.count"), 0x1C);

        // Top-level array-of-structs instance is unrolled too
        assert_eq!(offset_of(&reg, "arr._0.a"), 0x40);
        assert_eq!(offset_of(&reg, "arr._0.b"), 0x42);
        assert_eq!(offset_of(&reg, "arr._1.a"), 0x44);
        assert_eq!(offset_of(&reg, "arr._1.b"), 0x46);

        // 7 leaves from outer (3 * 2 + 1) plus 4 from arr (2 * 2)
        assert_eq!(reg.instance_list.len(), 11);
    }
}