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#[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 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 _ => vec![],
56 }
57 }
58
59 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 _ => Err(PowerlinkError::TypeMismatch),
100 }
101 }
102}
103
104#[derive(Debug, Clone, PartialEq)]
106pub enum Object {
107 Variable(ObjectValue),
108 Array(Vec<ObjectValue>),
109 Record(Vec<ObjectValue>),
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub enum AccessType {
115 ReadOnly,
117 WriteOnly,
119 WriteOnlyStore,
121 ReadWrite,
123 ReadWriteStore,
125 Constant,
127 Conditional,
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Category {
135 Mandatory,
136 Optional,
137 Conditional,
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum PdoMapping {
144 No,
145 Optional,
146 Default,
147}
148
149#[derive(Debug, Clone, PartialEq)]
151pub struct ValueRange {
152 pub min: ObjectValue,
153 pub max: ObjectValue,
154}
155
156#[derive(Debug, Clone, PartialEq)]
159pub struct ObjectEntry {
160 pub object: Object,
162 pub name: &'static str,
164 pub category: Category,
166 pub access: Option<AccessType>,
168 pub default_value: Option<ObjectValue>,
170 pub value_range: Option<ValueRange>,
172 pub pdo_mapping: Option<PdoMapping>,
174}
175
176pub 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 pub fn new(storage: Option<&'a mut dyn ObjectDictionaryStorage>) -> Self {
203 Self {
204 entries: BTreeMap::new(),
205 storage,
206 }
207 }
208
209 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 fn populate_protocol_objects(&mut self) {
237 self.insert(
239 0x1010,
240 ObjectEntry {
241 object: Object::Record(vec![
242 ObjectValue::Unsigned32(1), ObjectValue::Unsigned32(1), ObjectValue::Unsigned32(1), ]),
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 self.insert(
257 0x1011,
258 ObjectEntry {
259 object: Object::Record(vec![
260 ObjectValue::Unsigned32(1), ObjectValue::Unsigned32(1), ObjectValue::Unsigned32(1), ]),
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 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 pub fn validate_mandatory_objects(&self) -> Result<(), PowerlinkError> {
291 const MANDATORY_OBJECTS: &[u16] = &[
292 0x1000, 0x1018, 0x1F82, 0x1F93, 0x1F99, ];
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 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 let _ = self.write_internal(index, sub_index, value, false);
315 }
316 }
317 Ok(())
318 }
319
320 pub fn insert(&mut self, index: u16, entry: ObjectEntry) {
322 self.entries.insert(index, entry);
323 }
324
325 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 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 pub fn write(
381 &mut self,
382 index: u16,
383 sub_index: u8,
384 value: ObjectValue,
385 ) -> Result<(), PowerlinkError> {
386 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 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 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 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 let should_save = match list_to_save {
463 1 => true, 2 => (0x1000..=0x1FFF).contains(&index), 3 => (0x6000..=0x9FFF).contains(&index), _ => false, };
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 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 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, 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 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)), 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); }
750
751 assert!(storage.clear_called);
752 assert!(!storage.save_called);
753 assert!(!storage.restore_requested);
754 }
755}