Skip to main content

powerlink_rs/
hal.rs

1use crate::od::ObjectValue;
2use crate::pdo::PayloadSizeError;
3use crate::types::{InvalidMessageTypeError, NodeIdError};
4use alloc::collections::BTreeMap;
5use core::array::TryFromSliceError;
6use core::fmt;
7
8/// Defines a portable, descriptive Error type for the POWERLINK stack.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum PowerlinkError {
11    /// The provided buffer is too small for the operation.
12    BufferTooShort,
13    /// An underlying I/O error occurred.
14    IoError,
15    /// A received frame is fundamentally invalid (e.g., wrong EtherType, bad message type).
16    InvalidEthernetFrame,
17    /// A received powerlink frame is fundamentally invalid (e.g., too short to contain required headers).
18    InvalidPlFrame,
19    /// A value in the frame is not a valid MessageType.
20    InvalidMessageType(u8),
21    /// A value in the frame is not a valid NMT State.
22    InvalidNmtState(u8),
23    /// A value in the frame is not a valid ServiceId.
24    InvalidServiceId(u8),
25    /// A value in the frame is not a valid RequestedServiceId.
26    InvalidRequestedServiceId(u8),
27    /// A value in the frame is not a valid NodeId.
28    InvalidNodeId(u8),
29    /// A value in the frame is not a valid PayloadSize.
30    InvalidPayloadSize(u16),
31    /// A value in a frame is not a valid enum variant.
32    InvalidEnumValue,
33    /// A multi-byte value could not be parsed from a slice.
34    SliceConversion,
35    /// The frame size exceeds the maximum physical or configured MTU.
36    FrameTooLarge,
37    /// The device is not yet configured or ready to transmit/receive.
38    NotReady,
39    /// The requested Object Dictionary index does not exist.
40    ObjectNotFound,
41    /// The requested sub-index does not exist for the given object.
42    SubObjectNotFound,
43    /// An attempt was made to write a value with an incorrect data type to an object.
44    TypeMismatch,
45    /// An error occurred in the storage backend.
46    StorageError(&'static str),
47    /// A mandatory object was missing from the Object Dictionary during validation.
48    ValidationError(&'static str),
49    /// SDO Sequence number was unexpected (e.g., a lost frame was detected).
50    SdoSequenceError,
51    /// SDO command layer received an abort message.
52    SdoAborted,
53}
54
55impl fmt::Display for PowerlinkError {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            Self::BufferTooShort => write!(f, "Buffer is too short for the frame"),
59            Self::IoError => write!(f, "An underlying I/O error occurred"),
60            Self::InvalidEthernetFrame => write!(f, "Frame is not a valid Ethernet II frame"),
61            Self::InvalidPlFrame => write!(f, "Frame is not a valid POWERLINK frame"),
62            Self::InvalidMessageType(v) => write!(f, "Invalid MessageType value: {v:#04x}"),
63            Self::InvalidNmtState(v) => write!(f, "Invalid NMT State value: {v:#04x}"),
64            Self::InvalidServiceId(v) => write!(f, "Invalid ServiceId value: {v:#04x}"),
65            Self::InvalidRequestedServiceId(v) => write!(f, "Invalid RequestedServiceId value: {v:#04x}"),
66            Self::InvalidNodeId(v) => write!(f, "Invalid NodeId value: {v}"),
67            Self::InvalidPayloadSize(v) => write!(f, "Invalid PayloadSize value: {v}"),
68            Self::SliceConversion => write!(f, "Failed to convert slice to a fixed-size array"),
69            Self::FrameTooLarge => write!(f, "Frame size exceeds maximum allowed MTU"),
70            Self::NotReady => write!(f, "Device is not ready or configured"),
71            Self::ObjectNotFound => write!(f, "The requested Object Dictionary index was not found"),
72            Self::SubObjectNotFound => write!(f, "The requested sub-index was not found for this object"),
73            Self::TypeMismatch => write!(f, "The provided value's type does not match the object's type"), 
74            Self::InvalidEnumValue => write!(f, "A value in the frame is not a valid enum variant"),
75            Self::StorageError(s) => write!(f, "Storage error: {}", s),
76            Self::ValidationError(s) => write!(f, "OD Validation Error: {}", s),
77            Self::SdoSequenceError => write!(f, "SDO sequence number mismatch detected"),
78            Self::SdoAborted => write!(f, "SDO transfer was aborted"),
79        }
80    }
81}
82
83#[cfg(feature = "std")]
84impl std::error::Error for PowerlinkError {}
85
86// --- From Implementations for Error Conversion ---
87
88impl From<InvalidMessageTypeError> for PowerlinkError {
89    fn from(_: InvalidMessageTypeError) -> Self {
90        PowerlinkError::InvalidEnumValue
91    }
92}
93
94impl From<TryFromSliceError> for PowerlinkError {
95    fn from(_: TryFromSliceError) -> Self {
96        PowerlinkError::SliceConversion
97    }
98}
99
100impl From<NodeIdError> for PowerlinkError {
101    fn from(err: NodeIdError) -> Self {
102        match err {
103            NodeIdError::InvalidRange(val) => PowerlinkError::InvalidNodeId(val),
104        }
105    }
106}
107
108impl From<PayloadSizeError> for PowerlinkError {
109    fn from(err: PayloadSizeError) -> Self {
110        match err {
111            PayloadSizeError::InvalidRange(val) => PowerlinkError::InvalidPayloadSize(val),
112        }
113    }
114}
115
116impl From<&'static str> for PowerlinkError {
117    fn from(s: &'static str) -> Self {
118        PowerlinkError::StorageError(s)
119    }
120}
121
122/// Hardware Abstraction Layer (HAL) for raw Ethernet packet transmission.
123///
124/// This trait abstracts the physical sending and receiving of raw Ethernet frames,
125/// enabling the core POWERLINK protocol logic to remain platform-agnostic (no_std).
126pub trait NetworkInterface {
127    /// Sends a raw Ethernet frame (including Ethernet header) over the network.
128    ///
129    /// `frame`: The byte slice containing the complete Ethernet frame.
130    fn send_frame(&mut self, frame: &[u8]) -> Result<(), PowerlinkError>;
131
132    /// Attempts to receive a single raw Ethernet frame into the provided buffer.
133    /// This function should block until a frame is received or return an error/None
134    /// if non-blocking operation is configured.
135    ///
136    /// Returns the number of bytes read if successful, or an error.
137    /// The buffer must be large enough to hold the maximum possible Ethernet frame (e'g', 1518 bytes).
138    fn receive_frame(&mut self, buffer: &mut [u8]) -> Result<usize, PowerlinkError>;
139
140    /// Returns the Node ID assigned to this local device (Managing Node or Controlled Node).
141    fn local_node_id(&self) -> u8;
142
143    /// Returns the local MAC address of the interface.
144    fn local_mac_address(&self) -> [u8; 6];
145}
146
147/// A trait for abstracting the non-volatile storage of OD parameters.
148/// This abstraction is crucial for the "Restore Defaults" functionality,
149/// which must persist across device reboots.
150pub trait ObjectDictionaryStorage {
151    /// Loads storable parameters from non-volatile memory.
152    /// Returns a map of (Index, SubIndex) -> Value.
153    fn load(&mut self) -> Result<BTreeMap<(u16, u8), ObjectValue>, PowerlinkError>;
154
155    /// Saves the given storable parameters to non-volatile memory.
156    fn save(&mut self, parameters: &BTreeMap<(u16, u8), ObjectValue>) -> Result<(), PowerlinkError>;
157    
158    /// Clears all stored parameters from non-volatile memory.
159    fn clear(&mut self) -> Result<(), PowerlinkError>;
160
161    /// Checks if a "Restore Defaults" operation has been requested and is pending a reboot.
162    /// This should check for a persistent flag set by `request_restore_defaults`.
163    fn restore_defaults_requested(&self) -> bool;
164
165    /// Sets a persistent flag to indicate that defaults should be restored on the next boot.
166    /// This is called when the "load" signature is written to OD entry 0x1011.
167    fn request_restore_defaults(&mut self) -> Result<(), PowerlinkError>;
168
169    /// Clears the persistent "Restore Defaults" flag. This should be called
170    /// after the restore operation has been completed on boot.
171    fn clear_restore_defaults_flag(&mut self) -> Result<(), PowerlinkError>;
172}