Skip to main content

powerlink_rs_linux/
lib.rs

1// crates/powerlink-io-linux/src/lib.rs
2#![cfg(target_os = "linux")]
3
4use pnet::datalink::{self, Channel, NetworkInterface as PnetInterface};
5use powerlink_rs::{NetworkInterface, PowerlinkError};
6use std::io;
7use std::sync::Mutex;
8use std::time::Duration;
9
10pub struct LinuxPnetInterface {
11    tx: Mutex<Box<dyn datalink::DataLinkSender>>,
12    rx: Mutex<Box<dyn datalink::DataLinkReceiver>>,
13    pnet_iface: PnetInterface, // Store the interface for re-configuration
14    node_id: u8,
15    mac_address: [u8; 6],
16}
17
18impl LinuxPnetInterface {
19    pub fn new(interface_name: &str, node_id: u8) -> Result<Self, String> {
20        let interface = datalink::interfaces()
21            .into_iter()
22            .find(|iface: &PnetInterface| iface.name == interface_name)
23            .ok_or_else(|| format!("Interface '{}' not found", interface_name))?;
24
25        let mac_address = interface.mac.ok_or("Interface has no MAC address")?.into();
26
27        // Configure the channel to be promiscuous and have a default read timeout.
28        let config = datalink::Config {
29            read_timeout: Some(Duration::from_millis(100)),
30            promiscuous: true,
31            ..Default::default()
32        };
33
34        let (tx, rx) = match datalink::channel(&interface, config) {
35            Ok(Channel::Ethernet(tx, rx)) => (tx, rx),
36            Ok(_) => return Err("Unsupported channel type".to_string()),
37            Err(e) => return Err(e.to_string()),
38        };
39
40        Ok(Self {
41            tx: Mutex::new(tx),
42            rx: Mutex::new(rx),
43            pnet_iface: interface, // Store the interface
44            node_id,
45            mac_address,
46        })
47    }
48
49    /// Sets the read timeout for the underlying network channel.
50    /// This re-creates the channel, as pnet config is set at creation time.
51    pub fn set_read_timeout(&mut self, duration: Duration) -> Result<(), PowerlinkError> {
52        let config = datalink::Config {
53            read_timeout: Some(duration),
54            promiscuous: true,
55            ..Default::default()
56        };
57
58        match datalink::channel(&self.pnet_iface, config) {
59            Ok(Channel::Ethernet(tx, rx)) => {
60                // Replace the old sender and receiver with the new ones
61                *self.tx.lock().unwrap() = tx;
62                *self.rx.lock().unwrap() = rx;
63                Ok(())
64            }
65            Ok(_) => Err(PowerlinkError::IoError),
66            Err(e) => {
67                println!("Failed to set read timeout: {}", e);
68                Err(PowerlinkError::IoError)
69            }
70        }
71    }
72}
73
74impl NetworkInterface for LinuxPnetInterface {
75    fn send_frame(&mut self, frame: &[u8]) -> Result<(), PowerlinkError> {
76        self.tx
77            .lock()
78            .unwrap()
79            .send_to(frame, None)
80            .ok_or(PowerlinkError::IoError)? // For channel closed
81            .map_err(|_| PowerlinkError::IoError)?; // For OS error
82        Ok(())
83    }
84
85    fn receive_frame(&mut self, buffer: &mut [u8]) -> Result<usize, PowerlinkError> {
86        // 1. Acquire the lock and bind it.
87        let mut rx_guard = self.rx.lock().unwrap();
88
89        // 2. Call next() on the guard.
90        match rx_guard.next() {
91            Ok(frame) => {
92                let len = frame.len();
93                if buffer.len() >= len {
94                    buffer[..len].copy_from_slice(frame);
95                    Ok(len)
96                } else {
97                    Err(PowerlinkError::BufferTooShort)
98                }
99            }
100            Err(e) => {
101                if e.kind() == io::ErrorKind::TimedOut {
102                    Ok(0) // Return 0 bytes on timeout, not an error
103                } else {
104                    Err(PowerlinkError::IoError)
105                }
106            }
107        }
108    }
109
110    fn local_node_id(&self) -> u8 {
111        self.node_id
112    }
113
114    fn local_mac_address(&self) -> [u8; 6] {
115        self.mac_address
116    }
117}