Skip to main content

powerlink_rs/node/
cn.rs

1use super::{handler::FrameHandler, Node, NodeAction};
2use crate::frame::basic::MacAddress;
3use crate::frame::{
4    deserialize_frame,
5    error::{CnErrorCounters, DllErrorManager, NoOpErrorHandler},
6    ASndFrame, Codec, DllCsStateMachine, DllError, NmtAction, PowerlinkFrame, PResFrame,
7};
8use crate::nmt::cn_state_machine::CnNmtStateMachine;
9use crate::nmt::state_machine::NmtStateMachine;
10use crate::nmt::states::{NmtEvent, NmtState};
11use crate::od::ObjectDictionary;
12use crate::sdo::server::SdoServer;
13use crate::types::{NodeId, C_ADR_MN_DEF_NODE_ID};
14use crate::PowerlinkError;
15use alloc::vec;
16use alloc::vec::Vec;
17
18/// Represents a complete POWERLINK Controlled Node (CN).
19/// This struct owns and manages all protocol layers and state machines.
20pub struct ControlledNode<'s> {
21    pub(super) od: ObjectDictionary<'s>,
22    pub(super) nmt_state_machine: CnNmtStateMachine,
23    dll_state_machine: DllCsStateMachine,
24    dll_error_manager: DllErrorManager<CnErrorCounters, NoOpErrorHandler>,
25    mac_address: MacAddress,
26    sdo_server: SdoServer,
27}
28
29impl<'s> ControlledNode<'s> {
30    /// Creates a new Controlled Node.
31    ///
32    /// The application is responsible for creating and populating the Object Dictionary
33    /// with device-specific parameters (e.g., Identity Object 0x1018) before passing
34    /// it to this constructor. This function will then read the necessary configuration
35    /// from the OD to initialize the NMT state machine.
36    pub fn new(
37        mut od: ObjectDictionary<'s>,
38        mac_address: MacAddress,
39    ) -> Result<Self, PowerlinkError> {
40        // Initialise the OD, which involves loading from storage or applying defaults.
41        od.init()?;
42
43        // Validate that the user-provided OD contains all mandatory objects.
44        od.validate_mandatory_objects()?;
45
46        // The NMT state machine's constructor is now fallible because it must
47        // read critical parameters from the fully configured OD.
48        let nmt_state_machine = CnNmtStateMachine::from_od(&od)?;
49
50        Ok(Self {
51            od,
52            nmt_state_machine,
53            dll_state_machine: DllCsStateMachine::new(),
54            dll_error_manager: DllErrorManager::new(CnErrorCounters::new(), NoOpErrorHandler),
55            mac_address,
56            sdo_server: SdoServer::new(),
57        })
58    }
59
60    /// Internal function to process a deserialized `PowerlinkFrame`.
61    fn process_frame(&mut self, frame: PowerlinkFrame) -> NodeAction {
62        // Special handling for SDO frames.
63        if let PowerlinkFrame::ASnd(asnd_frame) = &frame {
64            if asnd_frame.service_id == crate::frame::ServiceId::Sdo {
65                match self
66                    .sdo_server
67                    .handle_request(&asnd_frame.payload, &mut self.od)
68                {
69                    Ok(response_payload) => {
70                        let response_asnd = ASndFrame::new(
71                            self.mac_address,
72                            asnd_frame.eth_header.source_mac,
73                            asnd_frame.source,
74                            self.nmt_state_machine.node_id,
75                            crate::frame::ServiceId::Sdo,
76                            response_payload,
77                        );
78                        let mut buf = vec![0u8; 1500];
79                        if let Ok(size) = response_asnd.serialize(&mut buf) {
80                            buf.truncate(size);
81                            return NodeAction::SendFrame(buf);
82                        }
83                    }
84                    Err(_) => {
85                        // TODO: Handle SDO error properly (e.g., log it).
86                    }
87                }
88                return NodeAction::NoAction;
89            }
90        }
91
92        // 1. Update NMT state machine based on the frame type.
93        if let Some(event) = frame.nmt_event() {
94            self.nmt_state_machine.process_event(event, &mut self.od);
95        }
96
97        // 2. Update DLL state machine based on the frame type.
98        if let Some(errors) = self.dll_state_machine.process_event(
99            frame.dll_event(),
100            self.nmt_state_machine.current_state(),
101        ) {
102            // If the DLL detects an error (like a lost frame), pass it to the error manager.
103            for error in errors {
104                if self.dll_error_manager.handle_error(error) != NmtAction::None {
105                    // Per Table 27, most DLL errors on a CN trigger an NMT state change to PreOp1.
106                    self.nmt_state_machine
107                        .process_event(NmtEvent::Error, &mut self.od);
108                }
109            }
110        }
111
112        // 3. Delegate response logic to the frame handler.
113        if let Some(response_frame) = frame.handle_cn(self) {
114            let mut buf = vec![0u8; 1500];
115            let serialize_result = match response_frame {
116                PowerlinkFrame::Soc(frame) => frame.serialize(&mut buf),
117                PowerlinkFrame::PReq(frame) => frame.serialize(&mut buf),
118                PowerlinkFrame::PRes(frame) => frame.serialize(&mut buf),
119                PowerlinkFrame::SoA(frame) => frame.serialize(&mut buf),
120                PowerlinkFrame::ASnd(frame) => frame.serialize(&mut buf),
121            };
122            if let Ok(size) = serialize_result {
123                buf.truncate(size);
124                return NodeAction::SendFrame(buf);
125            }
126        }
127
128        NodeAction::NoAction
129    }
130
131    /// Builds an `ASnd` frame for the `IdentResponse` service.
132    /// This function is typically called by the `FrameHandler` implementation for `SoAFrame`.
133    pub(super) fn build_ident_response(&self, soa: &crate::frame::SoAFrame) -> PowerlinkFrame {
134        let payload = self.build_ident_response_payload();
135        let asnd = ASndFrame::new(
136            self.mac_address,
137            soa.eth_header.source_mac,
138            NodeId(C_ADR_MN_DEF_NODE_ID),
139            self.nmt_state_machine.node_id,
140            crate::frame::ServiceId::IdentResponse,
141            payload,
142        );
143        PowerlinkFrame::ASnd(asnd)
144    }
145
146    /// Builds a `PRes` frame in response to being polled by a `PReq`.
147    /// This function is typically called by the `FrameHandler` implementation for `PReqFrame`.
148    pub(super) fn build_pres_response(&self, _preq: &crate::frame::PReqFrame) -> PowerlinkFrame {
149        let payload = Vec::new();
150        let pres = PResFrame::new(
151            self.mac_address,
152            self.nmt_state_machine.node_id,
153            self.nmt_state_machine.current_state(),
154            Default::default(),
155            crate::pdo::PDOVersion(0),
156            payload,
157        );
158        PowerlinkFrame::PRes(pres)
159    }
160
161    /// Constructs the detailed payload for an `IdentResponse` frame by reading from the OD.
162    /// The structure is defined in EPSG DS 301, Section 7.3.3.2.1.
163    fn build_ident_response_payload(&self) -> Vec<u8> {
164        let mut payload = vec![0u8; 110]; // Minimum size for IdentResponse
165
166        // NMTState (Octet 2)
167        payload[2] = self.nmt_state_machine.current_state() as u8;
168
169        // EPLVersion (Octet 4) - from 0x1F83
170        if let Some(val) = self.od.read_u8(0x1F83, 0) {
171            payload[4] = val;
172        }
173
174        // FeatureFlags (Octets 6-9) - from 0x1F82
175        payload[6..10].copy_from_slice(&self.nmt_state_machine.feature_flags.0.to_le_bytes());
176
177        // MTU (Octets 10-11) - from 0x1F98, sub-index 8
178        if let Some(val) = self.od.read_u16(0x1F98, 8) {
179            payload[10..12].copy_from_slice(&val.to_le_bytes());
180        }
181
182        // DeviceType (Octets 22-25) - from 0x1000
183        payload[22..26]
184            .copy_from_slice(&self.od.read_u32(0x1000, 0).unwrap_or(0).to_le_bytes());
185
186        // Identity Object (Octets 26-41) - from 0x1018
187        payload[26..30]
188            .copy_from_slice(&self.od.read_u32(0x1018, 1).unwrap_or(0).to_le_bytes()); // VendorID
189        payload[30..34]
190            .copy_from_slice(&self.od.read_u32(0x1018, 2).unwrap_or(0).to_le_bytes()); // ProductCode
191        payload[34..38]
192            .copy_from_slice(&self.od.read_u32(0x1018, 3).unwrap_or(0).to_le_bytes()); // RevisionNo
193        payload[38..42]
194            .copy_from_slice(&self.od.read_u32(0x1018, 4).unwrap_or(0).to_le_bytes()); // SerialNo
195
196        // Other fields like IPAddress, HostName etc. would be populated similarly in a full implementation.
197
198        payload
199    }
200}
201
202impl<'s> Node for ControlledNode<'s> {
203    fn process_raw_frame(&mut self, buffer: &[u8]) -> NodeAction {
204        match deserialize_frame(buffer) {
205            Ok(frame) => self.process_frame(frame),
206            Err(PowerlinkError::InvalidPlFrame) | Err(PowerlinkError::InvalidEthernetFrame) => {
207                if self
208                    .dll_error_manager
209                    .handle_error(DllError::InvalidFormat)
210                    != NmtAction::None
211                {
212                    self.nmt_state_machine
213                        .process_event(NmtEvent::Error, &mut self.od);
214                }
215                NodeAction::NoAction
216            }
217            Err(_) => NodeAction::NoAction,
218        }
219    }
220
221    fn tick(&mut self) -> NodeAction {
222        if self.nmt_state() == NmtState::NmtNotActive {
223            // Check if the BasicEthernetTimeout has expired.
224            // A real implementation would use a timer provided by the HAL.
225            // For now, we simulate this by checking a condition.
226            // If it has expired:
227            self.nmt_state_machine
228                .process_event(NmtEvent::Timeout, &mut self.od);
229        }
230        NodeAction::NoAction
231    }
232
233    fn nmt_state(&self) -> NmtState {
234        self.nmt_state_machine.current_state()
235    }
236}