Skip to main content

powerlink_rs/od/
mod.rs

1use crate::common::{NetTime, TimeDifference, TimeOfDay};
2use crate::hal::ObjectDictionaryStorage;
3use crate::types::{
4    BOOLEAN, INTEGER16, INTEGER32, INTEGER64, INTEGER8, REAL32, REAL64, UNSIGNED16, UNSIGNED32,
5    UNSIGNED64, UNSIGNED8, IpAddress, MacAddress,
6};
7use crate::PowerlinkError;
8use alloc::{borrow::Cow, collections::BTreeMap, string::String, vec, vec::Vec};
9use core::fmt;
10
11/// Represents any value that can be stored in an Object Dictionary entry.
12#[derive(Debug, Clone, PartialEq)]
13pub enum ObjectValue {
14    Boolean(BOOLEAN),
15    Integer8(INTEGER8),
16    Integer16(INTEGER16),
17    Integer32(INTEGER32),
18    Integer64(INTEGER64),
19    Unsigned8(UNSIGNED8),
20    Unsigned16(UNSIGNED16),
21    Unsigned32(UNSIGNED32),
22    Unsigned64(UNSIGNED64),
23    Real32(REAL32),
24    Real64(REAL64),
25    VisibleString(String),
26    OctetString(Vec<u8>),
27    UnicodeString(Vec<u16>),
28    Domain(Vec<u8>),
29    TimeOfDay(TimeOfDay),
30    TimeDifference(TimeDifference),
31    NetTime(NetTime),
32    MacAddress(MacAddress),
33    IpAddress(IpAddress),
34}
35
36impl ObjectValue {
37    /// Serializes the inner value into a little-endian byte vector.
38    pub fn serialize(&self) -> Vec<u8> {
39        match self {
40            ObjectValue::Boolean(v) => v.to_le_bytes().to_vec(),
41            ObjectValue::Integer8(v) => v.to_le_bytes().to_vec(),
42            ObjectValue::Integer16(v) => v.to_le_bytes().to_vec(),
43            ObjectValue::Integer32(v) => v.to_le_bytes().to_vec(),
44            ObjectValue::Integer64(v) => v.to_le_bytes().to_vec(),
45            ObjectValue::Unsigned8(v) => v.to_le_bytes().to_vec(),
46            ObjectValue::Unsigned16(v) => v.to_le_bytes().to_vec(),
47            ObjectValue::Unsigned32(v) => v.to_le_bytes().to_vec(),
48            ObjectValue::Unsigned64(v) => v.to_le_bytes().to_vec(),
49            ObjectValue::Real32(v) => v.to_le_bytes().to_vec(),
50            ObjectValue::Real64(v) => v.to_le_bytes().to_vec(),
51            ObjectValue::VisibleString(v) => v.as_bytes().to_vec(),
52            ObjectValue::OctetString(v) => v.clone(),
53            ObjectValue::Domain(v) => v.clone(),
54            // Other types would be serialized here.
55            _ => vec![],
56        }
57    }
58
59    /// Deserializes a byte slice into a new ObjectValue, using an existing
60    /// ObjectValue as a type template.
61    pub fn deserialize(
62        data: &[u8],
63        type_template: &ObjectValue,
64    ) -> Result<ObjectValue, PowerlinkError> {
65        match type_template {
66            ObjectValue::Boolean(_) => Ok(ObjectValue::Boolean(u8::from_le_bytes(
67                data.try_into()?,
68            ))),
69            ObjectValue::Integer8(_) => Ok(ObjectValue::Integer8(i8::from_le_bytes(
70                data.try_into()?,
71            ))),
72            ObjectValue::Integer16(_) => Ok(ObjectValue::Integer16(i16::from_le_bytes(
73                data.try_into()?,
74            ))),
75            ObjectValue::Integer32(_) => Ok(ObjectValue::Integer32(i32::from_le_bytes(
76                data.try_into()?,
77            ))),
78            ObjectValue::Integer64(_) => Ok(ObjectValue::Integer64(i64::from_le_bytes(
79                data.try_into()?,
80            ))),
81            ObjectValue::Unsigned8(_) => Ok(ObjectValue::Unsigned8(u8::from_le_bytes(
82                data.try_into()?,
83            ))),
84            ObjectValue::Unsigned16(_) => Ok(ObjectValue::Unsigned16(u16::from_le_bytes(
85                data.try_into()?,
86            ))),
87            ObjectValue::Unsigned32(_) => Ok(ObjectValue::Unsigned32(u32::from_le_bytes(
88                data.try_into()?,
89            ))),
90            ObjectValue::Unsigned64(_) => Ok(ObjectValue::Unsigned64(u64::from_le_bytes(
91                data.try_into()?,
92            ))),
93            ObjectValue::VisibleString(_) => Ok(ObjectValue::VisibleString(
94                String::from_utf8(data.to_vec()).map_err(|_| PowerlinkError::TypeMismatch)?,
95            )),
96            ObjectValue::OctetString(_) => Ok(ObjectValue::OctetString(data.to_vec())),
97            ObjectValue::Domain(_) => Ok(ObjectValue::Domain(data.to_vec())),
98            // Other types would be deserialized here.
99            _ => Err(PowerlinkError::TypeMismatch),
100        }
101    }
102}
103
104/// Represents a single entry in the Object Dictionary.
105#[derive(Debug, Clone, PartialEq)]
106pub enum Object {
107    Variable(ObjectValue),
108    Array(Vec<ObjectValue>),
109    Record(Vec<ObjectValue>),
110}
111
112/// Defines the access rights for an Object Dictionary entry.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum AccessType {
115    /// read only access
116    ReadOnly,
117    /// write only access
118    WriteOnly,
119    /// write only access, value shall be stored
120    WriteOnlyStore,
121    /// read and write access
122    ReadWrite,
123    /// read and write access, value shall be stored
124    ReadWriteStore,
125    /// read only access, value is constant
126    Constant,
127    /// variable access controlled by the device
128    Conditional,
129}
130
131/// Defines if an object is mandatory or optional.
132/// (Reference: EPSG DS 301, Section 6.2.1)
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Category {
135    Mandatory,
136    Optional,
137    Conditional,
138}
139
140/// Defines the PDO mapping options for an object.
141/// (Reference: EPSG DS 301, Table 39)
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum PdoMapping {
144    No,
145    Optional,
146    Default,
147}
148
149/// Represents a range of valid values for an object.
150#[derive(Debug, Clone, PartialEq)]
151pub struct ValueRange {
152    pub min: ObjectValue,
153    pub max: ObjectValue,
154}
155
156/// A complete entry in the Object Dictionary, containing both the data and its metadata.
157/// (Reference: EPSG DS 301, Section 6.2.1)
158#[derive(Debug, Clone, PartialEq)]
159pub struct ObjectEntry {
160    /// The actual data, stored in the existing Object enum.
161    pub object: Object,
162    /// A descriptive name for the object.
163    pub name: &'static str,
164    /// The category of the object (Mandatory, Optional, etc.).
165    pub category: Category,
166    /// The access rights for this object. `None` for complex types.
167    pub access: Option<AccessType>,
168    /// The default value for this object. `None` for complex types.
169    pub default_value: Option<ObjectValue>,
170    /// The valid value range for this object. `None` for complex types.
171    pub value_range: Option<ValueRange>,
172    /// The PDO mapping possibility for this object. `None` for complex types.
173    pub pdo_mapping: Option<PdoMapping>,
174}
175
176/// The main Object Dictionary structure.
177pub struct ObjectDictionary<'a> {
178    entries: BTreeMap<u16, ObjectEntry>,
179    storage: Option<&'a mut dyn ObjectDictionaryStorage>,
180}
181
182impl<'a> fmt::Debug for ObjectDictionary<'a> {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        f.debug_struct("ObjectDictionary")
185            .field("entries", &self.entries)
186            .field(
187                "storage",
188                &if self.storage.is_some() {
189                    "Some(<Storage Backend>)"
190                } else {
191                    "None"
192                },
193            )
194            .finish()
195    }
196}
197
198impl<'a> ObjectDictionary<'a> {
199    /// Creates a new, empty OD.
200    /// Call `init()` after populating with application and device defaults
201    /// to load persistent parameters and finish setup.
202    pub fn new(storage: Option<&'a mut dyn ObjectDictionaryStorage>) -> Self {
203        Self {
204            entries: BTreeMap::new(),
205            storage,
206        }
207    }
208
209    /// Initialises the Object Dictionary.
210    /// This method must be called after the application has inserted all its
211    /// default and device-specific objects. It performs the following actions:
212    /// 1. Populates mandatory communication profile objects.
213    /// 2. Checks if a "Restore Defaults" command was flagged in storage.
214    /// 3. If so, clears storage and proceeds with firmware defaults.
215    /// 4. If not, loads all stored parameters from the backend.
216    pub fn init(&mut self) -> Result<(), PowerlinkError> {
217        let mut restore_defaults = false;
218        if let Some(s) = &mut self.storage {
219            if s.restore_defaults_requested() {
220                restore_defaults = true;
221                s.clear_restore_defaults_flag()?;
222                s.clear()?;
223            }
224        }
225
226        self.populate_protocol_objects();
227
228        if !restore_defaults {
229            self.load()?;
230        }
231        Ok(())
232    }
233
234    /// Populates the OD with mandatory objects that define protocol mechanisms.
235    /// Device-specific identification objects are left to the user to insert.
236    fn populate_protocol_objects(&mut self) {
237        // Add Store Parameters (1010h) as a RECORD.
238        self.insert(
239            0x1010,
240            ObjectEntry {
241                object: Object::Record(vec![
242                    ObjectValue::Unsigned32(1), // Sub-index 1: Save All Parameters
243                    ObjectValue::Unsigned32(1), // Sub-index 2: Save Communication Parameters
244                    ObjectValue::Unsigned32(1), // Sub-index 3: Save Application Parameters
245                ]),
246                name: "NMT_StoreParam_REC",
247                category: Category::Mandatory,
248                access: None,
249                default_value: None,
250                value_range: None,
251                pdo_mapping: None,
252            },
253        );
254
255        // Add Restore Default Parameters (1011h) as a RECORD.
256        self.insert(
257            0x1011,
258            ObjectEntry {
259                object: Object::Record(vec![
260                    ObjectValue::Unsigned32(1), // Sub-index 1: Restore All Parameters
261                    ObjectValue::Unsigned32(1), // Sub-index 2: Restore Communication Parameters
262                    ObjectValue::Unsigned32(1), // Sub-index 3: Restore Application Parameters
263                ]),
264                name: "NMT_RestoreDefParam_REC",
265                category: Category::Mandatory,
266                access: None,
267                default_value: None,
268                value_range: None,
269                pdo_mapping: None,
270            },
271        );
272
273        // Add current NMT state object (1F8Ch).
274        self.insert(
275            0x1F8C,
276            ObjectEntry {
277                object: Object::Variable(ObjectValue::Unsigned8(0)),
278                name: "NMT_CurrNMTState_U8",
279                category: Category::Mandatory,
280                access: Some(AccessType::ReadOnly),
281                default_value: Some(ObjectValue::Unsigned8(0)),
282                value_range: None,
283                pdo_mapping: Some(PdoMapping::No),
284            },
285        );
286    }
287
288    /// Validates that the OD contains all mandatory objects required for a node to function.
289    /// Should be called from the node's constructor.
290    pub fn validate_mandatory_objects(&self) -> Result<(), PowerlinkError> {
291        const MANDATORY_OBJECTS: &[u16] = &[
292            0x1000, // NMT_DeviceType_U32
293            0x1018, // NMT_IdentityObject_REC
294            0x1F82, // NMT_FeatureFlags_U32
295            0x1F93, // NMT_EPLNodeID_REC
296            0x1F99, // NMT_CNBasicEthernetTimeout_U32
297        ];
298        for &index in MANDATORY_OBJECTS {
299            if !self.entries.contains_key(&index) {
300                return Err(PowerlinkError::ObjectNotFound);
301            }
302        }
303        Ok(())
304    }
305
306    /// Loads values from the persistent storage backend and overwrites any
307    /// matching existing entries in the OD. This is called by `init()`.
308    fn load(&mut self) -> Result<(), PowerlinkError> {
309        if let Some(s) = &mut self.storage {
310            let stored_params = s.load()?;
311            for ((index, sub_index), value) in stored_params {
312                // Attempt to write the loaded value. Ignore errors for objects
313                // that might exist in storage but not in the current firmware.
314                let _ = self.write_internal(index, sub_index, value, false);
315            }
316        }
317        Ok(())
318    }
319
320    /// Inserts a new object entry into the dictionary at a given index.
321    pub fn insert(&mut self, index: u16, entry: ObjectEntry) {
322        self.entries.insert(index, entry);
323    }
324
325    /// Reads a value from the Object Dictionary by index and sub-index.
326    pub fn read<'s>(&'s self, index: u16, sub_index: u8) -> Option<Cow<'s, ObjectValue>> {
327        self.entries
328            .get(&index)
329            .and_then(|entry| match &entry.object {
330                Object::Variable(value) => {
331                    if sub_index == 0 {
332                        Some(Cow::Borrowed(value))
333                    } else {
334                        None
335                    }
336                }
337                Object::Array(values) | Object::Record(values) => {
338                    if sub_index == 0 {
339                        Some(Cow::Owned(ObjectValue::Unsigned8(values.len() as u8)))
340                    } else {
341                        values.get(sub_index as usize - 1).map(Cow::Borrowed)
342                    }
343                }
344            })
345    }
346
347    // --- Start of Type-Safe Accessors ---
348    pub fn read_u8(&self, index: u16, sub_index: u8) -> Option<u8> {
349        self.read(index, sub_index).and_then(|cow| {
350            if let ObjectValue::Unsigned8(val) = *cow {
351                Some(val)
352            } else {
353                None
354            }
355        })
356    }
357
358    pub fn read_u16(&self, index: u16, sub_index: u8) -> Option<u16> {
359        self.read(index, sub_index).and_then(|cow| {
360            if let ObjectValue::Unsigned16(val) = *cow {
361                Some(val)
362            } else {
363                None
364            }
365        })
366    }
367
368    pub fn read_u32(&self, index: u16, sub_index: u8) -> Option<u32> {
369        self.read(index, sub_index).and_then(|cow| {
370            if let ObjectValue::Unsigned32(val) = *cow {
371                Some(val)
372            } else {
373                None
374            }
375        })
376    }
377    // --- End of Type-Safe Accessors ---
378
379    /// Public write function that respects access rights and handles special command objects.
380    pub fn write(
381        &mut self,
382        index: u16,
383        sub_index: u8,
384        value: ObjectValue,
385    ) -> Result<(), PowerlinkError> {
386        // Special case for Store Parameters command (1010h).
387        if index == 0x1010 {
388            if let ObjectValue::VisibleString(s) = &value {
389                if s == "save" {
390                    return self.store_parameters(sub_index);
391                }
392            }
393            return Err(PowerlinkError::StorageError(
394                "Invalid signature for Store Parameters",
395            ));
396        }
397
398        // Special case for Restore Default Parameters command (1011h).
399        if index == 0x1011 {
400            if let ObjectValue::VisibleString(s) = &value {
401                if s == "load" {
402                    return self.restore_defaults(sub_index);
403                }
404            }
405            return Err(PowerlinkError::StorageError(
406                "Invalid signature for Restore Defaults",
407            ));
408        }
409        self.write_internal(index, sub_index, value, true)
410    }
411
412    /// Internal write function with an option to bypass access checks.
413    pub(super) fn write_internal(
414        &mut self,
415        index: u16,
416        sub_index: u8,
417        value: ObjectValue,
418        check_access: bool,
419    ) -> Result<(), PowerlinkError> {
420        self.entries
421            .get_mut(&index)
422            .map_or(Err(PowerlinkError::ObjectNotFound), |entry| {
423                if check_access {
424                    if let Some(access) = entry.access {
425                        if matches!(access, AccessType::ReadOnly | AccessType::Constant) {
426                            return Err(PowerlinkError::StorageError("Object is read-only"));
427                        }
428                    }
429                }
430                match &mut entry.object {
431                    Object::Variable(v) => {
432                        if sub_index == 0 {
433                            *v = value;
434                            Ok(())
435                        } else {
436                            Err(PowerlinkError::SubObjectNotFound)
437                        }
438                    }
439                    Object::Array(values) | Object::Record(values) => {
440                        if sub_index == 0 {
441                            Err(PowerlinkError::StorageError("Cannot write to sub-index 0"))
442                        } else if let Some(v) = values.get_mut(sub_index as usize - 1) {
443                            *v = value;
444                            Ok(())
445                        } else {
446                            Err(PowerlinkError::SubObjectNotFound)
447                        }
448                    }
449                }
450            })
451    }
452
453    /// Collects all storable parameters and tells the storage backend to save them.
454    fn store_parameters(&mut self, list_to_save: u8) -> Result<(), PowerlinkError> {
455        if list_to_save == 0 {
456            return Err(PowerlinkError::StorageError("Cannot save to sub-index 0"));
457        }
458        if let Some(s) = &mut self.storage {
459            let mut storable_params = BTreeMap::new();
460            for (&index, entry) in &self.entries {
461                // Determine if this object's group (Comm, App, etc.) should be saved.
462                let should_save = match list_to_save {
463                    1 => true,                                     // Save All
464                    2 => (0x1000..=0x1FFF).contains(&index), // Save Communication
465                    3 => (0x6000..=0x9FFF).contains(&index), // Save Application
466                    _ => false, // Other sub-indices are manufacturer-specific
467                };
468
469                if should_save {
470                    if let Some(access) = entry.access {
471                        if matches!(access, AccessType::ReadWriteStore | AccessType::WriteOnlyStore)
472                        {
473                            match &entry.object {
474                                Object::Variable(val) => {
475                                    storable_params.insert((index, 0), val.clone());
476                                }
477                                Object::Record(vals) | Object::Array(vals) => {
478                                    for (i, val) in vals.iter().enumerate() {
479                                        storable_params
480                                            .insert((index, (i + 1) as u8), val.clone());
481                                    }
482                                }
483                            }
484                        }
485                    }
486                }
487            }
488            s.save(&storable_params)
489        } else {
490            Err(PowerlinkError::StorageError(
491                "No storage backend configured",
492            ))
493        }
494    }
495
496    /// Tells the storage backend to set a flag to restore defaults on the next boot.
497    /// The actual data clearing happens at startup.
498    fn restore_defaults(&mut self, list_to_restore: u8) -> Result<(), PowerlinkError> {
499        if list_to_restore == 0 {
500            return Err(PowerlinkError::StorageError(
501                "Cannot restore from sub-index 0",
502            ));
503        }
504        if let Some(s) = &mut self.storage {
505            // For now, any valid "load" command flags a full restore.
506            // A full implementation could pass `list_to_restore` to the storage backend.
507            s.request_restore_defaults()
508        } else {
509            Err(PowerlinkError::StorageError(
510                "No storage backend configured",
511            ))
512        }
513    }
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::hal::ObjectDictionaryStorage;
520    use alloc::string::ToString;
521    use alloc::vec;
522
523    struct MockStorage {
524        saved_data: BTreeMap<(u16, u8), ObjectValue>,
525        restore_requested: bool,
526        save_called: bool,
527        load_called: bool,
528        clear_called: bool,
529    }
530    impl MockStorage {
531        fn new() -> Self {
532            Self {
533                saved_data: BTreeMap::new(),
534                restore_requested: false,
535                save_called: false,
536                load_called: false,
537                clear_called: false,
538            }
539        }
540    }
541    impl ObjectDictionaryStorage for MockStorage {
542        fn load(&mut self) -> Result<BTreeMap<(u16, u8), ObjectValue>, PowerlinkError> {
543            self.load_called = true;
544            Ok(self.saved_data.clone())
545        }
546        fn save(
547            &mut self,
548            params: &BTreeMap<(u16, u8), ObjectValue>,
549        ) -> Result<(), PowerlinkError> {
550            self.save_called = true;
551            self.saved_data = params.clone();
552            Ok(())
553        }
554        fn clear(&mut self) -> Result<(), PowerlinkError> {
555            self.clear_called = true;
556            self.saved_data.clear();
557            Ok(())
558        }
559        fn restore_defaults_requested(&self) -> bool {
560            self.restore_requested
561        }
562        fn request_restore_defaults(&mut self) -> Result<(), PowerlinkError> {
563            self.restore_requested = true;
564            Ok(())
565        }
566        fn clear_restore_defaults_flag(&mut self) -> Result<(), PowerlinkError> {
567            self.restore_requested = false;
568            Ok(())
569        }
570    }
571
572    #[test]
573    fn test_read_variable() {
574        let mut od = ObjectDictionary::new(None);
575        od.insert(
576            0x1006,
577            ObjectEntry {
578                object: Object::Variable(ObjectValue::Unsigned32(12345)),
579                name: "TestVar",
580                category: Category::Mandatory,
581                access: Some(AccessType::ReadWrite),
582                default_value: None,
583                value_range: None,
584                pdo_mapping: None,
585            },
586        );
587
588        let value = od.read(0x1006, 0).unwrap();
589        assert_eq!(*value, ObjectValue::Unsigned32(12345));
590    }
591
592    #[test]
593    fn test_read_write_array_element() {
594        let mut od = ObjectDictionary::new(None);
595        od.insert(
596            0x2000,
597            ObjectEntry {
598                object: Object::Array(vec![ObjectValue::Unsigned16(100)]),
599                name: "TestArray",
600                category: Category::Mandatory,
601                access: None, // Access is per-element for arrays
602                default_value: None,
603                value_range: None,
604                pdo_mapping: None,
605            },
606        );
607
608        od.write(0x2000, 1, ObjectValue::Unsigned16(999)).unwrap();
609        let value = od.read(0x2000, 1).unwrap();
610        assert_eq!(*value, ObjectValue::Unsigned16(999));
611    }
612
613    #[test]
614    fn test_read_sub_index_zero_returns_owned_length() {
615        let mut od = ObjectDictionary::new(None);
616        od.insert(
617            0x2000,
618            ObjectEntry {
619                object: Object::Array(vec![
620                    ObjectValue::Unsigned16(100),
621                    ObjectValue::Unsigned16(200),
622                ]),
623                name: "TestArray",
624                category: Category::Mandatory,
625                access: None,
626                default_value: None,
627                value_range: None,
628                pdo_mapping: None,
629            },
630        );
631
632        let value = od.read(0x2000, 0).unwrap();
633        assert_eq!(*value, ObjectValue::Unsigned8(2));
634        assert!(matches!(value, Cow::Owned(_)));
635    }
636
637    #[test]
638    fn test_write_to_readonly_fails() {
639        let mut od = ObjectDictionary::new(None);
640        od.insert(
641            0x1008,
642            ObjectEntry {
643                object: Object::Variable(ObjectValue::Unsigned8(10)),
644                name: "ReadOnlyVar",
645                category: Category::Mandatory,
646                access: Some(AccessType::ReadOnly),
647                default_value: None,
648                value_range: None,
649                pdo_mapping: None,
650            },
651        );
652
653        let result = od.write(0x1008, 0, ObjectValue::Unsigned8(42));
654        assert!(result.is_err());
655        assert_eq!(*od.read(0x1008, 0).unwrap(), ObjectValue::Unsigned8(10));
656    }
657
658    #[test]
659    fn test_save_command() {
660        let mut storage = MockStorage::new();
661        {
662            let mut od = ObjectDictionary::new(Some(&mut storage));
663            od.insert(
664                0x6000,
665                ObjectEntry {
666                    object: Object::Variable(ObjectValue::Unsigned32(123)),
667                    name: "StorableVar",
668                    category: Category::Optional,
669                    access: Some(AccessType::ReadWriteStore),
670                    default_value: None,
671                    value_range: None,
672                    pdo_mapping: None,
673                },
674            );
675
676            od.write(0x1010, 1, ObjectValue::VisibleString("save".to_string()))
677                .unwrap();
678        }
679
680        assert!(storage.save_called);
681        assert_eq!(
682            storage.saved_data.get(&(0x6000, 0)),
683            Some(&ObjectValue::Unsigned32(123))
684        );
685    }
686
687    #[test]
688    fn test_restore_defaults_command_flags_for_reboot() {
689        let mut storage = MockStorage::new();
690        let mut od = ObjectDictionary::new(Some(&mut storage));
691        assert!(!od.storage.as_ref().unwrap().restore_defaults_requested());
692        od.write(0x1011, 1, ObjectValue::VisibleString("load".to_string()))
693            .unwrap();
694        // After the write, the storage inside od is now borrowed mutably.
695        // To check its state, we must borrow it again immutably.
696        assert!(od.storage.as_ref().unwrap().restore_defaults_requested());
697    }
698
699    #[test]
700    fn test_loading_from_storage_on_init() {
701        let mut storage = MockStorage::new();
702        storage
703            .saved_data
704            .insert((0x6000, 0), ObjectValue::Unsigned32(999));
705
706        let mut od = ObjectDictionary::new(Some(&mut storage));
707        od.insert(
708            0x6000,
709            ObjectEntry {
710                object: Object::Variable(ObjectValue::Unsigned32(0)),
711                name: "StorableVar",
712                category: Category::Optional,
713                access: Some(AccessType::ReadWriteStore),
714                default_value: None,
715                value_range: None,
716                pdo_mapping: None,
717            },
718        );
719
720        od.init().unwrap();
721
722        assert_eq!(od.read_u32(0x6000, 0).unwrap(), 999);
723    }
724
725    #[test]
726    fn test_init_restores_defaults_if_flagged() {
727        let mut storage = MockStorage::new();
728        storage
729            .saved_data
730            .insert((0x6000, 0), ObjectValue::Unsigned32(999));
731        storage.restore_requested = true;
732
733        {
734            let mut od = ObjectDictionary::new(Some(&mut storage));
735            od.insert(
736                0x6000,
737                ObjectEntry {
738                    object: Object::Variable(ObjectValue::Unsigned32(0)), // Firmware default
739                    name: "StorableVar",
740                    category: Category::Optional,
741                    access: Some(AccessType::ReadWriteStore),
742                    default_value: None,
743                    value_range: None,
744                    pdo_mapping: None,
745                },
746            );
747            od.init().unwrap();
748            assert_eq!(od.read_u32(0x6000, 0).unwrap(), 0); // Back to default
749        }
750
751        assert!(storage.clear_called);
752        assert!(!storage.save_called);
753        assert!(!storage.restore_requested);
754    }
755}