ethercrab/command/
mod.rs

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
//! Raw EtherCAT commands, e.g. `LRW`, `BRD`, `APWR`, etc.

mod reads;
mod writes;

use ethercrab_wire::{EtherCrabWireSized, EtherCrabWireWriteSized};

pub use reads::{Reads, WrappedRead};
pub use writes::{WrappedWrite, Writes};

const NOP: u8 = 0x00;
const APRD: u8 = 0x01;
const FPRD: u8 = 0x04;
const BRD: u8 = 0x07;
const LRD: u8 = 0x0A;
const BWR: u8 = 0x08;
const APWR: u8 = 0x02;
const FPWR: u8 = 0x05;
const FRMW: u8 = 0x0E;
const LWR: u8 = 0x0B;
const LRW: u8 = 0x0c;

/// PDU command.
///
/// A command can be used in various different ways, to e.g. read a number or write a raw slice to a
/// slave device on the network.
///
/// All EtherCAT commands are implemented. It is recommended to use the methods on `Command` to
/// create them.
///
/// A `Command` won't do much on its own. To perform network operations with the command it must be
/// wrapped with either [`WrappedRead`] or [`WrappedWrite`] by calling the `wrap` method. These
/// structs add a [`Client`](crate::Client) and expose many different read/write operations. See the
/// methods on [`WrappedRead`] and [`WrappedWrite`] for more.
///
/// # Examples
///
/// ## Read a `u32` from a slave by address
///
/// ```rust
/// # use ethercrab::{ std::tx_rx_task, Client, ClientConfig, PduStorage, Timeouts };
/// use ethercrab::{ Command, RegisterAddress };
/// # static PDU_STORAGE: PduStorage<16, 1100> = PduStorage::new();
/// # let (_tx, _rx, pdu_loop) = PDU_STORAGE.try_split().expect("can only split once");
/// let client = /* ... */
/// # Client::new(pdu_loop, Timeouts::default(), ClientConfig::default());
///
/// let slave_configured_address = 0x1001u16;
///
/// # async {
/// let value = Command::fprd(slave_configured_address, RegisterAddress::SiiData.into())
///     .receive::<u32>(&client)
///     .await?;
/// # Result::<(), ethercrab::error::Error>::Ok(())
/// # };
/// ```
///
/// ## Write a slice to a given slave address and register
///
/// ```rust
/// # use ethercrab::{ std::tx_rx_task, Client, ClientConfig, PduStorage, Timeouts };
/// use ethercrab::{ Command, RegisterAddress };
/// # static PDU_STORAGE: PduStorage<16, 1100> = PduStorage::new();
/// # let (_tx, _rx, pdu_loop) = PDU_STORAGE.try_split().expect("can only split once");
/// let client = /* ... */
/// # Client::new(pdu_loop, Timeouts::default(), ClientConfig::default());
///
/// let slave_configured_address = 0x1001u16;
/// let register = 0x1234u16;
///
/// let data = [ 0xaau8, 0xbb, 0xcc, 0xdd ];
///
/// # async {
/// Command::fpwr(slave_configured_address, register)
///     .send(&client, data)
///     .await?;
/// # Result::<(), ethercrab::error::Error>::Ok(())
/// # };
/// ```
#[derive(Default, PartialEq, Eq, Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum Command {
    /// No operation.
    #[default]
    Nop,

    /// Read commands.
    Read(Reads),

    /// Write commands.
    Write(Writes),
}

impl EtherCrabWireSized for Command {
    const PACKED_LEN: usize = 4;

    type Buffer = [u8; Self::PACKED_LEN];

    fn buffer() -> Self::Buffer {
        [0u8; Self::PACKED_LEN]
    }
}

impl EtherCrabWireWriteSized for Command {
    fn pack(&self) -> Self::Buffer {
        match *self {
            Command::Nop => Self::buffer(),

            Command::Read(Reads::Aprd { address, register })
            | Command::Read(Reads::Brd { address, register })
            | Command::Read(Reads::Fprd { address, register })
            | Command::Read(Reads::Frmw { address, register })
            | Command::Write(Writes::Apwr { address, register })
            | Command::Write(Writes::Fpwr { address, register })
            | Command::Write(Writes::Bwr { address, register }) => {
                let address = address.to_le_bytes();
                let register = register.to_le_bytes();

                [address[0], address[1], register[0], register[1]]
            }
            Command::Read(Reads::Lrd { address })
            | Command::Write(Writes::Lwr { address })
            | Command::Write(Writes::Lrw { address }) => address.to_le_bytes(),
        }
    }
}

impl core::fmt::Display for Command {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Command::Nop => write!(f, "NOP"),

            Command::Read(read) => match read {
                Reads::Aprd { address, register } => {
                    write!(f, "APRD(addr {:#06x}, reg {:#06x})", address, register)
                }
                Reads::Fprd { address, register } => {
                    write!(f, "FPRD(addr {:#06x}, reg {:#06x})", address, register)
                }
                Reads::Brd { address, register } => {
                    write!(f, "BRD(addr {:#06x}, reg {:#06x})", address, register)
                }
                Reads::Lrd { address } => write!(f, "LRD(addr {:#010x})", address),
                Reads::Frmw { address, register } => {
                    write!(f, "FRMW(addr {:#06x}, reg {:#06x})", address, register)
                }
            },

            Command::Write(write) => match write {
                Writes::Bwr { address, register } => {
                    write!(f, "BWR(addr {:#06x}, reg {:#06x})", address, register)
                }
                Writes::Apwr { address, register } => {
                    write!(f, "APWR(addr {:#06x}, reg {:#06x})", address, register)
                }
                Writes::Fpwr { address, register } => {
                    write!(f, "FPWR(addr {:#06x}, reg {:#06x})", address, register)
                }

                Writes::Lwr { address } => write!(f, "LWR(addr {:#010x})", address),
                Writes::Lrw { address } => write!(f, "LRW(addr {:#010x})", address),
            },
        }
    }
}

impl Command {
    /// Create a broadcast read (BRD) command to the given register address.
    ///
    /// The configured station address is always zero when transmitted from the master.
    pub fn brd(register: u16) -> WrappedRead {
        WrappedRead::new(Reads::Brd {
            // This is a broadcast, so the address is always zero when sent from the master
            address: 0,
            register,
        })
    }

    /// Create a broadcast write (BWR) command to the given register address.
    ///
    /// The configured station address is always zero when transmitted from the master.
    pub fn bwr(register: u16) -> WrappedWrite {
        WrappedWrite::new(Writes::Bwr {
            // This is a broadcast, so the address is always zero when sent from the master
            address: 0,
            register,
        })
    }

    /// FPRD.
    pub fn fprd(address: u16, register: u16) -> WrappedRead {
        WrappedRead::new(Reads::Fprd { address, register })
    }

    /// FPWR.
    pub fn fpwr(address: u16, register: u16) -> WrappedWrite {
        WrappedWrite::new(Writes::Fpwr { address, register })
    }

    /// APRD.
    pub fn aprd(address: u16, register: u16) -> WrappedRead {
        WrappedRead::new(Reads::Aprd {
            address: 0u16.wrapping_sub(address),
            register,
        })
    }

    /// APWR.
    pub fn apwr(address: u16, register: u16) -> WrappedWrite {
        WrappedWrite::new(Writes::Apwr {
            address: 0u16.wrapping_sub(address),
            register,
        })
    }

    /// Configured address read, multiple write (FRMW).
    ///
    /// This can be used to distribute a value from one slave to all others on the network, e.g.
    /// with distributed clocks.
    pub fn frmw(address: u16, register: u16) -> WrappedRead {
        WrappedRead::new(Reads::Frmw { address, register })
    }

    /// Logical Read Write (LRW), used mainly for sending and receiving PDI.
    pub fn lrw(address: u32) -> WrappedWrite {
        WrappedWrite::new(Writes::Lrw { address })
    }

    /// Logical Write (LWR).
    pub fn lwr(address: u32) -> WrappedWrite {
        WrappedWrite::new(Writes::Lwr { address })
    }

    /// Get just the command code for a command.
    pub(crate) const fn code(&self) -> u8 {
        match self {
            Self::Nop => NOP,

            Self::Read(read) => match read {
                Reads::Aprd { .. } => APRD,
                Reads::Fprd { .. } => FPRD,
                Reads::Brd { .. } => BRD,
                Reads::Lrd { .. } => LRD,
                Reads::Frmw { .. } => FRMW,
            },

            Self::Write(write) => match write {
                Writes::Bwr { .. } => BWR,
                Writes::Apwr { .. } => APWR,
                Writes::Fpwr { .. } => FPWR,
                Writes::Lwr { .. } => LWR,
                Writes::Lrw { .. } => LRW,
            },
        }
    }
}

impl From<Reads> for Command {
    fn from(value: Reads) -> Self {
        Self::Read(value)
    }
}

impl From<Writes> for Command {
    fn from(value: Writes) -> Self {
        Self::Write(value)
    }
}

impl From<WrappedRead> for Command {
    fn from(value: WrappedRead) -> Self {
        Self::Read(value.command)
    }
}

impl From<WrappedWrite> for Command {
    fn from(value: WrappedWrite) -> Self {
        Self::Write(value.command)
    }
}