powerlink-rs 0.1.0

Platform-agnostic core logic for Ethernet POWERLINK Rust implementation.
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use crate::common::{NetTime, TimeDifference, TimeOfDay};
use crate::hal::ObjectDictionaryStorage;
use crate::types::{
    BOOLEAN, INTEGER16, INTEGER32, INTEGER64, INTEGER8, REAL32, REAL64, UNSIGNED16, UNSIGNED32,
    UNSIGNED64, UNSIGNED8, IpAddress, MacAddress,
};
use crate::PowerlinkError;
use alloc::{borrow::Cow, collections::BTreeMap, string::String, vec, vec::Vec};
use core::fmt;

/// Represents any value that can be stored in an Object Dictionary entry.
#[derive(Debug, Clone, PartialEq)]
pub enum ObjectValue {
    Boolean(BOOLEAN),
    Integer8(INTEGER8),
    Integer16(INTEGER16),
    Integer32(INTEGER32),
    Integer64(INTEGER64),
    Unsigned8(UNSIGNED8),
    Unsigned16(UNSIGNED16),
    Unsigned32(UNSIGNED32),
    Unsigned64(UNSIGNED64),
    Real32(REAL32),
    Real64(REAL64),
    VisibleString(String),
    OctetString(Vec<u8>),
    UnicodeString(Vec<u16>),
    Domain(Vec<u8>),
    TimeOfDay(TimeOfDay),
    TimeDifference(TimeDifference),
    NetTime(NetTime),
    MacAddress(MacAddress),
    IpAddress(IpAddress),
}

impl ObjectValue {
    /// Serializes the inner value into a little-endian byte vector.
    pub fn serialize(&self) -> Vec<u8> {
        match self {
            ObjectValue::Boolean(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Integer8(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Integer16(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Integer32(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Integer64(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Unsigned8(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Unsigned16(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Unsigned32(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Unsigned64(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Real32(v) => v.to_le_bytes().to_vec(),
            ObjectValue::Real64(v) => v.to_le_bytes().to_vec(),
            ObjectValue::VisibleString(v) => v.as_bytes().to_vec(),
            ObjectValue::OctetString(v) => v.clone(),
            ObjectValue::Domain(v) => v.clone(),
            // Other types would be serialized here.
            _ => vec![],
        }
    }

    /// Deserializes a byte slice into a new ObjectValue, using an existing
    /// ObjectValue as a type template.
    pub fn deserialize(
        data: &[u8],
        type_template: &ObjectValue,
    ) -> Result<ObjectValue, PowerlinkError> {
        match type_template {
            ObjectValue::Boolean(_) => Ok(ObjectValue::Boolean(u8::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Integer8(_) => Ok(ObjectValue::Integer8(i8::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Integer16(_) => Ok(ObjectValue::Integer16(i16::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Integer32(_) => Ok(ObjectValue::Integer32(i32::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Integer64(_) => Ok(ObjectValue::Integer64(i64::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Unsigned8(_) => Ok(ObjectValue::Unsigned8(u8::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Unsigned16(_) => Ok(ObjectValue::Unsigned16(u16::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Unsigned32(_) => Ok(ObjectValue::Unsigned32(u32::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::Unsigned64(_) => Ok(ObjectValue::Unsigned64(u64::from_le_bytes(
                data.try_into()?,
            ))),
            ObjectValue::VisibleString(_) => Ok(ObjectValue::VisibleString(
                String::from_utf8(data.to_vec()).map_err(|_| PowerlinkError::TypeMismatch)?,
            )),
            ObjectValue::OctetString(_) => Ok(ObjectValue::OctetString(data.to_vec())),
            ObjectValue::Domain(_) => Ok(ObjectValue::Domain(data.to_vec())),
            // Other types would be deserialized here.
            _ => Err(PowerlinkError::TypeMismatch),
        }
    }
}

/// Represents a single entry in the Object Dictionary.
#[derive(Debug, Clone, PartialEq)]
pub enum Object {
    Variable(ObjectValue),
    Array(Vec<ObjectValue>),
    Record(Vec<ObjectValue>),
}

/// Defines the access rights for an Object Dictionary entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AccessType {
    /// read only access
    ReadOnly,
    /// write only access
    WriteOnly,
    /// write only access, value shall be stored
    WriteOnlyStore,
    /// read and write access
    ReadWrite,
    /// read and write access, value shall be stored
    ReadWriteStore,
    /// read only access, value is constant
    Constant,
    /// variable access controlled by the device
    Conditional,
}

/// Defines if an object is mandatory or optional.
/// (Reference: EPSG DS 301, Section 6.2.1)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Category {
    Mandatory,
    Optional,
    Conditional,
}

/// Defines the PDO mapping options for an object.
/// (Reference: EPSG DS 301, Table 39)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PdoMapping {
    No,
    Optional,
    Default,
}

/// Represents a range of valid values for an object.
#[derive(Debug, Clone, PartialEq)]
pub struct ValueRange {
    pub min: ObjectValue,
    pub max: ObjectValue,
}

/// A complete entry in the Object Dictionary, containing both the data and its metadata.
/// (Reference: EPSG DS 301, Section 6.2.1)
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectEntry {
    /// The actual data, stored in the existing Object enum.
    pub object: Object,
    /// A descriptive name for the object.
    pub name: &'static str,
    /// The category of the object (Mandatory, Optional, etc.).
    pub category: Category,
    /// The access rights for this object. `None` for complex types.
    pub access: Option<AccessType>,
    /// The default value for this object. `None` for complex types.
    pub default_value: Option<ObjectValue>,
    /// The valid value range for this object. `None` for complex types.
    pub value_range: Option<ValueRange>,
    /// The PDO mapping possibility for this object. `None` for complex types.
    pub pdo_mapping: Option<PdoMapping>,
}

/// The main Object Dictionary structure.
pub struct ObjectDictionary<'a> {
    entries: BTreeMap<u16, ObjectEntry>,
    storage: Option<&'a mut dyn ObjectDictionaryStorage>,
}

impl<'a> fmt::Debug for ObjectDictionary<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObjectDictionary")
            .field("entries", &self.entries)
            .field(
                "storage",
                &if self.storage.is_some() {
                    "Some(<Storage Backend>)"
                } else {
                    "None"
                },
            )
            .finish()
    }
}

impl<'a> ObjectDictionary<'a> {
    /// Creates a new, empty OD.
    /// Call `init()` after populating with application and device defaults
    /// to load persistent parameters and finish setup.
    pub fn new(storage: Option<&'a mut dyn ObjectDictionaryStorage>) -> Self {
        Self {
            entries: BTreeMap::new(),
            storage,
        }
    }

    /// Initialises the Object Dictionary.
    /// This method must be called after the application has inserted all its
    /// default and device-specific objects. It performs the following actions:
    /// 1. Populates mandatory communication profile objects.
    /// 2. Checks if a "Restore Defaults" command was flagged in storage.
    /// 3. If so, clears storage and proceeds with firmware defaults.
    /// 4. If not, loads all stored parameters from the backend.
    pub fn init(&mut self) -> Result<(), PowerlinkError> {
        let mut restore_defaults = false;
        if let Some(s) = &mut self.storage {
            if s.restore_defaults_requested() {
                restore_defaults = true;
                s.clear_restore_defaults_flag()?;
                s.clear()?;
            }
        }

        self.populate_protocol_objects();

        if !restore_defaults {
            self.load()?;
        }
        Ok(())
    }

    /// Populates the OD with mandatory objects that define protocol mechanisms.
    /// Device-specific identification objects are left to the user to insert.
    fn populate_protocol_objects(&mut self) {
        // Add Store Parameters (1010h) as a RECORD.
        self.insert(
            0x1010,
            ObjectEntry {
                object: Object::Record(vec![
                    ObjectValue::Unsigned32(1), // Sub-index 1: Save All Parameters
                    ObjectValue::Unsigned32(1), // Sub-index 2: Save Communication Parameters
                    ObjectValue::Unsigned32(1), // Sub-index 3: Save Application Parameters
                ]),
                name: "NMT_StoreParam_REC",
                category: Category::Mandatory,
                access: None,
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        // Add Restore Default Parameters (1011h) as a RECORD.
        self.insert(
            0x1011,
            ObjectEntry {
                object: Object::Record(vec![
                    ObjectValue::Unsigned32(1), // Sub-index 1: Restore All Parameters
                    ObjectValue::Unsigned32(1), // Sub-index 2: Restore Communication Parameters
                    ObjectValue::Unsigned32(1), // Sub-index 3: Restore Application Parameters
                ]),
                name: "NMT_RestoreDefParam_REC",
                category: Category::Mandatory,
                access: None,
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        // Add current NMT state object (1F8Ch).
        self.insert(
            0x1F8C,
            ObjectEntry {
                object: Object::Variable(ObjectValue::Unsigned8(0)),
                name: "NMT_CurrNMTState_U8",
                category: Category::Mandatory,
                access: Some(AccessType::ReadOnly),
                default_value: Some(ObjectValue::Unsigned8(0)),
                value_range: None,
                pdo_mapping: Some(PdoMapping::No),
            },
        );
    }

    /// Validates that the OD contains all mandatory objects required for a node to function.
    /// Should be called from the node's constructor.
    pub fn validate_mandatory_objects(&self) -> Result<(), PowerlinkError> {
        const MANDATORY_OBJECTS: &[u16] = &[
            0x1000, // NMT_DeviceType_U32
            0x1018, // NMT_IdentityObject_REC
            0x1F82, // NMT_FeatureFlags_U32
            0x1F93, // NMT_EPLNodeID_REC
            0x1F99, // NMT_CNBasicEthernetTimeout_U32
        ];
        for &index in MANDATORY_OBJECTS {
            if !self.entries.contains_key(&index) {
                return Err(PowerlinkError::ObjectNotFound);
            }
        }
        Ok(())
    }

    /// Loads values from the persistent storage backend and overwrites any
    /// matching existing entries in the OD. This is called by `init()`.
    fn load(&mut self) -> Result<(), PowerlinkError> {
        if let Some(s) = &mut self.storage {
            let stored_params = s.load()?;
            for ((index, sub_index), value) in stored_params {
                // Attempt to write the loaded value. Ignore errors for objects
                // that might exist in storage but not in the current firmware.
                let _ = self.write_internal(index, sub_index, value, false);
            }
        }
        Ok(())
    }

    /// Inserts a new object entry into the dictionary at a given index.
    pub fn insert(&mut self, index: u16, entry: ObjectEntry) {
        self.entries.insert(index, entry);
    }

    /// Reads a value from the Object Dictionary by index and sub-index.
    pub fn read<'s>(&'s self, index: u16, sub_index: u8) -> Option<Cow<'s, ObjectValue>> {
        self.entries
            .get(&index)
            .and_then(|entry| match &entry.object {
                Object::Variable(value) => {
                    if sub_index == 0 {
                        Some(Cow::Borrowed(value))
                    } else {
                        None
                    }
                }
                Object::Array(values) | Object::Record(values) => {
                    if sub_index == 0 {
                        Some(Cow::Owned(ObjectValue::Unsigned8(values.len() as u8)))
                    } else {
                        values.get(sub_index as usize - 1).map(Cow::Borrowed)
                    }
                }
            })
    }

    // --- Start of Type-Safe Accessors ---
    pub fn read_u8(&self, index: u16, sub_index: u8) -> Option<u8> {
        self.read(index, sub_index).and_then(|cow| {
            if let ObjectValue::Unsigned8(val) = *cow {
                Some(val)
            } else {
                None
            }
        })
    }

    pub fn read_u16(&self, index: u16, sub_index: u8) -> Option<u16> {
        self.read(index, sub_index).and_then(|cow| {
            if let ObjectValue::Unsigned16(val) = *cow {
                Some(val)
            } else {
                None
            }
        })
    }

    pub fn read_u32(&self, index: u16, sub_index: u8) -> Option<u32> {
        self.read(index, sub_index).and_then(|cow| {
            if let ObjectValue::Unsigned32(val) = *cow {
                Some(val)
            } else {
                None
            }
        })
    }
    // --- End of Type-Safe Accessors ---

    /// Public write function that respects access rights and handles special command objects.
    pub fn write(
        &mut self,
        index: u16,
        sub_index: u8,
        value: ObjectValue,
    ) -> Result<(), PowerlinkError> {
        // Special case for Store Parameters command (1010h).
        if index == 0x1010 {
            if let ObjectValue::VisibleString(s) = &value {
                if s == "save" {
                    return self.store_parameters(sub_index);
                }
            }
            return Err(PowerlinkError::StorageError(
                "Invalid signature for Store Parameters",
            ));
        }

        // Special case for Restore Default Parameters command (1011h).
        if index == 0x1011 {
            if let ObjectValue::VisibleString(s) = &value {
                if s == "load" {
                    return self.restore_defaults(sub_index);
                }
            }
            return Err(PowerlinkError::StorageError(
                "Invalid signature for Restore Defaults",
            ));
        }
        self.write_internal(index, sub_index, value, true)
    }

    /// Internal write function with an option to bypass access checks.
    pub(super) fn write_internal(
        &mut self,
        index: u16,
        sub_index: u8,
        value: ObjectValue,
        check_access: bool,
    ) -> Result<(), PowerlinkError> {
        self.entries
            .get_mut(&index)
            .map_or(Err(PowerlinkError::ObjectNotFound), |entry| {
                if check_access {
                    if let Some(access) = entry.access {
                        if matches!(access, AccessType::ReadOnly | AccessType::Constant) {
                            return Err(PowerlinkError::StorageError("Object is read-only"));
                        }
                    }
                }
                match &mut entry.object {
                    Object::Variable(v) => {
                        if sub_index == 0 {
                            *v = value;
                            Ok(())
                        } else {
                            Err(PowerlinkError::SubObjectNotFound)
                        }
                    }
                    Object::Array(values) | Object::Record(values) => {
                        if sub_index == 0 {
                            Err(PowerlinkError::StorageError("Cannot write to sub-index 0"))
                        } else if let Some(v) = values.get_mut(sub_index as usize - 1) {
                            *v = value;
                            Ok(())
                        } else {
                            Err(PowerlinkError::SubObjectNotFound)
                        }
                    }
                }
            })
    }

    /// Collects all storable parameters and tells the storage backend to save them.
    fn store_parameters(&mut self, list_to_save: u8) -> Result<(), PowerlinkError> {
        if list_to_save == 0 {
            return Err(PowerlinkError::StorageError("Cannot save to sub-index 0"));
        }
        if let Some(s) = &mut self.storage {
            let mut storable_params = BTreeMap::new();
            for (&index, entry) in &self.entries {
                // Determine if this object's group (Comm, App, etc.) should be saved.
                let should_save = match list_to_save {
                    1 => true,                                     // Save All
                    2 => (0x1000..=0x1FFF).contains(&index), // Save Communication
                    3 => (0x6000..=0x9FFF).contains(&index), // Save Application
                    _ => false, // Other sub-indices are manufacturer-specific
                };

                if should_save {
                    if let Some(access) = entry.access {
                        if matches!(access, AccessType::ReadWriteStore | AccessType::WriteOnlyStore)
                        {
                            match &entry.object {
                                Object::Variable(val) => {
                                    storable_params.insert((index, 0), val.clone());
                                }
                                Object::Record(vals) | Object::Array(vals) => {
                                    for (i, val) in vals.iter().enumerate() {
                                        storable_params
                                            .insert((index, (i + 1) as u8), val.clone());
                                    }
                                }
                            }
                        }
                    }
                }
            }
            s.save(&storable_params)
        } else {
            Err(PowerlinkError::StorageError(
                "No storage backend configured",
            ))
        }
    }

    /// Tells the storage backend to set a flag to restore defaults on the next boot.
    /// The actual data clearing happens at startup.
    fn restore_defaults(&mut self, list_to_restore: u8) -> Result<(), PowerlinkError> {
        if list_to_restore == 0 {
            return Err(PowerlinkError::StorageError(
                "Cannot restore from sub-index 0",
            ));
        }
        if let Some(s) = &mut self.storage {
            // For now, any valid "load" command flags a full restore.
            // A full implementation could pass `list_to_restore` to the storage backend.
            s.request_restore_defaults()
        } else {
            Err(PowerlinkError::StorageError(
                "No storage backend configured",
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hal::ObjectDictionaryStorage;
    use alloc::string::ToString;
    use alloc::vec;

    struct MockStorage {
        saved_data: BTreeMap<(u16, u8), ObjectValue>,
        restore_requested: bool,
        save_called: bool,
        load_called: bool,
        clear_called: bool,
    }
    impl MockStorage {
        fn new() -> Self {
            Self {
                saved_data: BTreeMap::new(),
                restore_requested: false,
                save_called: false,
                load_called: false,
                clear_called: false,
            }
        }
    }
    impl ObjectDictionaryStorage for MockStorage {
        fn load(&mut self) -> Result<BTreeMap<(u16, u8), ObjectValue>, PowerlinkError> {
            self.load_called = true;
            Ok(self.saved_data.clone())
        }
        fn save(
            &mut self,
            params: &BTreeMap<(u16, u8), ObjectValue>,
        ) -> Result<(), PowerlinkError> {
            self.save_called = true;
            self.saved_data = params.clone();
            Ok(())
        }
        fn clear(&mut self) -> Result<(), PowerlinkError> {
            self.clear_called = true;
            self.saved_data.clear();
            Ok(())
        }
        fn restore_defaults_requested(&self) -> bool {
            self.restore_requested
        }
        fn request_restore_defaults(&mut self) -> Result<(), PowerlinkError> {
            self.restore_requested = true;
            Ok(())
        }
        fn clear_restore_defaults_flag(&mut self) -> Result<(), PowerlinkError> {
            self.restore_requested = false;
            Ok(())
        }
    }

    #[test]
    fn test_read_variable() {
        let mut od = ObjectDictionary::new(None);
        od.insert(
            0x1006,
            ObjectEntry {
                object: Object::Variable(ObjectValue::Unsigned32(12345)),
                name: "TestVar",
                category: Category::Mandatory,
                access: Some(AccessType::ReadWrite),
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        let value = od.read(0x1006, 0).unwrap();
        assert_eq!(*value, ObjectValue::Unsigned32(12345));
    }

    #[test]
    fn test_read_write_array_element() {
        let mut od = ObjectDictionary::new(None);
        od.insert(
            0x2000,
            ObjectEntry {
                object: Object::Array(vec![ObjectValue::Unsigned16(100)]),
                name: "TestArray",
                category: Category::Mandatory,
                access: None, // Access is per-element for arrays
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        od.write(0x2000, 1, ObjectValue::Unsigned16(999)).unwrap();
        let value = od.read(0x2000, 1).unwrap();
        assert_eq!(*value, ObjectValue::Unsigned16(999));
    }

    #[test]
    fn test_read_sub_index_zero_returns_owned_length() {
        let mut od = ObjectDictionary::new(None);
        od.insert(
            0x2000,
            ObjectEntry {
                object: Object::Array(vec![
                    ObjectValue::Unsigned16(100),
                    ObjectValue::Unsigned16(200),
                ]),
                name: "TestArray",
                category: Category::Mandatory,
                access: None,
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        let value = od.read(0x2000, 0).unwrap();
        assert_eq!(*value, ObjectValue::Unsigned8(2));
        assert!(matches!(value, Cow::Owned(_)));
    }

    #[test]
    fn test_write_to_readonly_fails() {
        let mut od = ObjectDictionary::new(None);
        od.insert(
            0x1008,
            ObjectEntry {
                object: Object::Variable(ObjectValue::Unsigned8(10)),
                name: "ReadOnlyVar",
                category: Category::Mandatory,
                access: Some(AccessType::ReadOnly),
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        let result = od.write(0x1008, 0, ObjectValue::Unsigned8(42));
        assert!(result.is_err());
        assert_eq!(*od.read(0x1008, 0).unwrap(), ObjectValue::Unsigned8(10));
    }

    #[test]
    fn test_save_command() {
        let mut storage = MockStorage::new();
        {
            let mut od = ObjectDictionary::new(Some(&mut storage));
            od.insert(
                0x6000,
                ObjectEntry {
                    object: Object::Variable(ObjectValue::Unsigned32(123)),
                    name: "StorableVar",
                    category: Category::Optional,
                    access: Some(AccessType::ReadWriteStore),
                    default_value: None,
                    value_range: None,
                    pdo_mapping: None,
                },
            );

            od.write(0x1010, 1, ObjectValue::VisibleString("save".to_string()))
                .unwrap();
        }

        assert!(storage.save_called);
        assert_eq!(
            storage.saved_data.get(&(0x6000, 0)),
            Some(&ObjectValue::Unsigned32(123))
        );
    }

    #[test]
    fn test_restore_defaults_command_flags_for_reboot() {
        let mut storage = MockStorage::new();
        let mut od = ObjectDictionary::new(Some(&mut storage));
        assert!(!od.storage.as_ref().unwrap().restore_defaults_requested());
        od.write(0x1011, 1, ObjectValue::VisibleString("load".to_string()))
            .unwrap();
        // After the write, the storage inside od is now borrowed mutably.
        // To check its state, we must borrow it again immutably.
        assert!(od.storage.as_ref().unwrap().restore_defaults_requested());
    }

    #[test]
    fn test_loading_from_storage_on_init() {
        let mut storage = MockStorage::new();
        storage
            .saved_data
            .insert((0x6000, 0), ObjectValue::Unsigned32(999));

        let mut od = ObjectDictionary::new(Some(&mut storage));
        od.insert(
            0x6000,
            ObjectEntry {
                object: Object::Variable(ObjectValue::Unsigned32(0)),
                name: "StorableVar",
                category: Category::Optional,
                access: Some(AccessType::ReadWriteStore),
                default_value: None,
                value_range: None,
                pdo_mapping: None,
            },
        );

        od.init().unwrap();

        assert_eq!(od.read_u32(0x6000, 0).unwrap(), 999);
    }

    #[test]
    fn test_init_restores_defaults_if_flagged() {
        let mut storage = MockStorage::new();
        storage
            .saved_data
            .insert((0x6000, 0), ObjectValue::Unsigned32(999));
        storage.restore_requested = true;

        {
            let mut od = ObjectDictionary::new(Some(&mut storage));
            od.insert(
                0x6000,
                ObjectEntry {
                    object: Object::Variable(ObjectValue::Unsigned32(0)), // Firmware default
                    name: "StorableVar",
                    category: Category::Optional,
                    access: Some(AccessType::ReadWriteStore),
                    default_value: None,
                    value_range: None,
                    pdo_mapping: None,
                },
            );
            od.init().unwrap();
            assert_eq!(od.read_u32(0x6000, 0).unwrap(), 0); // Back to default
        }

        assert!(storage.clear_called);
        assert!(!storage.save_called);
        assert!(!storage.restore_requested);
    }
}