Skip to main content

powerlink_rs/sdo/
command.rs

1// In crates/powerlink-rs/src/sdo/command.rs
2use crate::frame::Codec;
3use crate::types::{UNSIGNED16, UNSIGNED32, UNSIGNED8};
4use crate::PowerlinkError;
5use alloc::vec::Vec;
6
7/// Defines the SDO command IDs.
8/// (Reference: EPSG DS 301, Table 58)
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10#[repr(u8)]
11pub enum CommandId {
12    Nil = 0x00,
13    // SDO protocol
14    WriteByIndex = 0x01,
15    ReadByIndex = 0x02,
16    WriteAllByIndex = 0x03,
17    ReadAllByIndex = 0x04,
18    WriteByName = 0x05,
19    ReadByName = 0x06,
20    // File transfer
21    FileWrite = 0x20,
22    FileRead = 0x21,
23    // Variable groups
24    WriteMultipleParamByIndex = 0x31,
25    ReadMultipleParamByIndex = 0x32,
26    // Parameter service
27    MaxSegmentSize = 0x70,
28    // Manufacturer specific from 0x80 to 0xFF
29}
30
31impl Default for CommandId {
32    fn default() -> Self {
33        CommandId::Nil
34    }
35}
36
37impl TryFrom<u8> for CommandId {
38    type Error = PowerlinkError;
39    fn try_from(value: u8) -> Result<Self, Self::Error> {
40        match value {
41            0x00 => Ok(Self::Nil),
42            0x01 => Ok(Self::WriteByIndex),
43            0x02 => Ok(Self::ReadByIndex),
44            0x03 => Ok(Self::WriteAllByIndex),
45            0x04 => Ok(Self::ReadAllByIndex),
46            0x05 => Ok(Self::WriteByName),
47            0x06 => Ok(Self::ReadByName),
48            0x20 => Ok(Self::FileWrite),
49            0x21 => Ok(Self::FileRead),
50            0x31 => Ok(Self::WriteMultipleParamByIndex),
51            0x32 => Ok(Self::ReadMultipleParamByIndex),
52            0x70 => Ok(Self::MaxSegmentSize),
53            _ => Err(PowerlinkError::InvalidEnumValue),
54        }
55    }
56}
57
58/// Defines the segmentation type for SDO transfers.
59/// (Reference: EPSG DS 301, Table 55)
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
61#[repr(u8)]
62pub enum Segmentation {
63    #[default]
64    Expedited = 0,
65    Initiate = 1,
66    Segment = 2,
67    Complete = 3,
68}
69
70impl TryFrom<u8> for Segmentation {
71    type Error = PowerlinkError;
72    fn try_from(value: u8) -> Result<Self, Self::Error> {
73        match value {
74            0 => Ok(Self::Expedited),
75            1 => Ok(Self::Initiate),
76            2 => Ok(Self::Segment),
77            3 => Ok(Self::Complete),
78            _ => Err(PowerlinkError::InvalidEnumValue),
79        }
80    }
81}
82
83/// Represents the fixed part of the SDO Command Layer header.
84/// (Reference: EPSG DS 301, Table 54)
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct CommandLayerHeader {
87    pub transaction_id: UNSIGNED8,
88    pub is_response: bool,
89    pub is_aborted: bool,
90    pub segmentation: Segmentation,
91    pub command_id: CommandId,
92    pub segment_size: UNSIGNED16,
93}
94
95impl Default for CommandLayerHeader {
96    fn default() -> Self {
97        Self {
98            transaction_id: 0,
99            is_response: false,
100            is_aborted: false,
101            segmentation: Segmentation::default(),
102            command_id: CommandId::default(),
103            segment_size: 0,
104        }
105    }
106}
107
108/// Represents a complete SDO command layer frame, including the header and payload.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct SdoCommand {
111    pub header: CommandLayerHeader,
112    /// Data size is only present in Initiate Segmented Transfer frames.
113    pub data_size: Option<UNSIGNED32>,
114    /// The payload, which contains command-specific data.
115    pub payload: Vec<u8>,
116}
117
118/// Specific data for a "Read by Index" request.
119/// (Reference: EPSG DS 301, Table 61)
120pub struct ReadByIndexRequest {
121    pub index: u16,
122    pub sub_index: u8,
123}
124
125impl ReadByIndexRequest {
126    pub fn from_payload(payload: &[u8]) -> Result<Self, PowerlinkError> {
127        if payload.len() < 4 {
128            return Err(PowerlinkError::BufferTooShort);
129        }
130        Ok(Self {
131            index: u16::from_le_bytes(payload[0..2].try_into()?),
132            sub_index: payload[2],
133        })
134    }
135}
136
137/// Specific data for a "Write by Index" request.
138/// (Reference: EPSG DS 301, Table 59)
139pub struct WriteByIndexRequest<'a> {
140    pub index: u16,
141    pub sub_index: u8,
142    pub data: &'a [u8],
143}
144
145impl<'a> WriteByIndexRequest<'a> {
146    pub fn from_payload(payload: &'a [u8]) -> Result<Self, PowerlinkError> {
147        if payload.len() < 4 {
148            return Err(PowerlinkError::BufferTooShort);
149        }
150        Ok(Self {
151            index: u16::from_le_bytes(payload[0..2].try_into()?),
152            sub_index: payload[2],
153            data: &payload[4..],
154        })
155    }
156}
157
158impl Codec for SdoCommand {
159    fn serialize(&self, buffer: &mut [u8]) -> Result<usize, PowerlinkError> {
160        let mut offset = 0;
161        if buffer.len() < 8 {
162            return Err(PowerlinkError::BufferTooShort);
163        }
164
165        buffer[offset] = 0; // Reserved
166        offset += 1;
167        buffer[offset] = self.header.transaction_id;
168        offset += 1;
169
170        let mut flags = 0u8;
171        if self.header.is_response {
172            flags |= 1 << 7;
173        }
174        if self.header.is_aborted {
175            flags |= 1 << 6;
176        }
177        flags |= (self.header.segmentation as u8) << 4;
178        buffer[offset] = flags;
179        offset += 1;
180
181        buffer[offset] = self.header.command_id as u8;
182        offset += 1;
183        buffer[offset..offset + 2].copy_from_slice(&self.header.segment_size.to_le_bytes());
184        offset += 2;
185        buffer[offset..offset + 2].copy_from_slice(&[0, 0]); // Reserved
186        offset += 2;
187
188        if let Some(data_size) = self.data_size {
189            if buffer.len() < offset + 4 {
190                return Err(PowerlinkError::BufferTooShort);
191            }
192            buffer[offset..offset + 4].copy_from_slice(&data_size.to_le_bytes());
193            offset += 4;
194        }
195
196        if buffer.len() < offset + self.payload.len() {
197            return Err(PowerlinkError::BufferTooShort);
198        }
199        buffer[offset..offset + self.payload.len()].copy_from_slice(&self.payload);
200        offset += self.payload.len();
201
202        Ok(offset)
203    }
204
205    fn deserialize(buffer: &[u8]) -> Result<Self, PowerlinkError> {
206        if buffer.len() < 8 {
207            return Err(PowerlinkError::BufferTooShort);
208        }
209
210        let transaction_id = buffer[1];
211        let flags = buffer[2];
212        let is_response = (flags & (1 << 7)) != 0;
213        let is_aborted = (flags & (1 << 6)) != 0;
214        let segmentation = Segmentation::try_from((flags >> 4) & 0b11)?;
215        let command_id = CommandId::try_from(buffer[3])?;
216        let segment_size = u16::from_le_bytes(buffer[4..6].try_into()?);
217
218        let mut offset = 8;
219        let data_size = if segmentation == Segmentation::Initiate {
220            if buffer.len() < 12 {
221                return Err(PowerlinkError::BufferTooShort);
222            }
223            offset = 12;
224            Some(u32::from_le_bytes(buffer[8..12].try_into()?))
225        } else {
226            None
227        };
228
229        let payload = buffer[offset..].to_vec();
230
231        Ok(SdoCommand {
232            header: CommandLayerHeader {
233                transaction_id,
234                is_response,
235                is_aborted,
236                segmentation,
237                command_id,
238                segment_size,
239            },
240            data_size,
241            payload,
242        })
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use alloc::vec;
250
251    #[test]
252    fn test_sdo_command_expedited_roundtrip() {
253        let original = SdoCommand {
254            header: CommandLayerHeader {
255                transaction_id: 1,
256                is_response: false,
257                is_aborted: false,
258                segmentation: Segmentation::Expedited,
259                command_id: CommandId::WriteByIndex,
260                segment_size: 8,
261            },
262            data_size: None,
263            payload: vec![0x10, 0x18, 0x01, 0x00, 0xDE, 0xAD, 0xBE, 0xEF],
264        };
265
266        let mut buffer = [0u8; 64];
267        let bytes_written = original.serialize(&mut buffer).unwrap();
268        let deserialized = SdoCommand::deserialize(&buffer[..bytes_written]).unwrap();
269
270        assert_eq!(original, deserialized);
271    }
272
273    #[test]
274    fn test_sdo_command_segmented_initiate_roundtrip() {
275        let original = SdoCommand {
276            header: CommandLayerHeader {
277                transaction_id: 2,
278                is_response: false,
279                is_aborted: false,
280                segmentation: Segmentation::Initiate,
281                command_id: CommandId::WriteByIndex,
282                segment_size: 4,
283            },
284            data_size: Some(1000),
285            payload: vec![0x10, 0x60, 0x00, 0x00],
286        };
287
288        let mut buffer = [0u8; 64];
289        let bytes_written = original.serialize(&mut buffer).unwrap();
290        let deserialized = SdoCommand::deserialize(&buffer[..bytes_written]).unwrap();
291
292        assert_eq!(original, deserialized);
293        assert_eq!(deserialized.data_size, Some(1000));
294    }
295
296    #[test]
297    fn test_read_by_index_request_parser() {
298        let payload = vec![0x06, 0x10, 0x01, 0x00]; // Read 0x1006 sub 1
299        let req = ReadByIndexRequest::from_payload(&payload).unwrap();
300        assert_eq!(req.index, 0x1006);
301        assert_eq!(req.sub_index, 1);
302
303        let short_payload = vec![0x06, 0x10, 0x01];
304        assert!(ReadByIndexRequest::from_payload(&short_payload).is_err());
305    }
306
307    #[test]
308    fn test_write_by_index_request_parser() {
309        let payload = vec![0x00, 0x60, 0x00, 0x00, 0xAA, 0xBB]; // Write 0x6000 sub 0 with data
310        let req = WriteByIndexRequest::from_payload(&payload).unwrap();
311        assert_eq!(req.index, 0x6000);
312        assert_eq!(req.sub_index, 0);
313        assert_eq!(req.data, &[0xAA, 0xBB]);
314    }
315
316    #[test]
317    fn test_enum_try_from() {
318        assert_eq!(CommandId::try_from(0x01), Ok(CommandId::WriteByIndex));
319        assert!(CommandId::try_from(0xFF).is_err());
320        assert_eq!(
321            Segmentation::try_from(0x02),
322            Ok(Segmentation::Segment)
323        );
324        assert!(Segmentation::try_from(0x04).is_err());
325    }
326}