#![cfg(target_os = "linux")]
use log::{debug, error, info, trace, warn};
use pnet::datalink::interfaces;
use powerlink_io_linux::LinuxPnetInterface;
use powerlink_rs::{
ControlledNode,
NetworkInterface,
Node,
NodeAction,
PowerlinkError,
common::{NetTime, RelativeTime},
deserialize_frame,
frame::{
ASndFrame, Codec, PowerlinkFrame, RequestedServiceId, ServiceId, SoAFrame, SocFrame,
basic::MacAddress,
},
nmt::{flags::FeatureFlags, states::NmtState},
od::{AccessType, Category, Object, ObjectDictionary, ObjectEntry, ObjectValue, PdoMapping},
sdo::{
command::{CommandId, CommandLayerHeader, SdoCommand, Segmentation},
sequence::{ReceiveConnState, SendConnState, SequenceLayerHeader},
},
types::{C_ADR_MN_DEF_NODE_ID, EPLVersion, NodeId},
};
use std::{
env,
num::ParseIntError,
thread,
time::{Duration, Instant},
};
const TEST_INTERFACE: &str = "eth0"; const FALLBACK_INTERFACE: &str = "lo"; const SLEEP_DURATION: Duration = Duration::from_millis(200); const TEST_TIMEOUT: Duration = Duration::from_secs(20);
fn find_test_interface() -> String {
interfaces()
.into_iter()
.find(|iface| iface.name == TEST_INTERFACE)
.map(|iface| iface.name.clone())
.unwrap_or_else(|| {
warn!("Interface 'eth0' not found, falling back to 'lo'.");
FALLBACK_INTERFACE.to_string()
})
}
fn get_cn_node_id() -> Result<u8, ParseIntError> {
env::var("POWERLINK_CN_NODE_ID")
.expect("Missing POWERLINK_CN_NODE_ID environment variable")
.parse()
}
fn get_test_od(node_id: u8) -> ObjectDictionary<'static> {
let mut od = ObjectDictionary::new(None);
od.insert(
0x1000, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned32(0x000F0191)), name: "NMT_DeviceType_U32",
category: Category::Mandatory,
access: Some(AccessType::Constant),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1006, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned32(10000)), name: "NMT_CycleLen_U32",
category: Category::Mandatory,
access: Some(AccessType::ReadWriteStore),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1008, ObjectEntry {
object: Object::Variable(ObjectValue::VisibleString("powerlink-rs CN Test".into())),
name: "NMT_ManufactDevName_VS",
category: Category::Optional, access: Some(AccessType::Constant),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1018, ObjectEntry {
object: Object::Record(vec![
ObjectValue::Unsigned32(0x12345678), ObjectValue::Unsigned32(0x00000001), ObjectValue::Unsigned32(0x00010000), ObjectValue::Unsigned32(0xABCDEF01), ]),
name: "NMT_IdentityObject_REC",
category: Category::Mandatory,
access: None,
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1F93, ObjectEntry {
object: Object::Record(vec![
ObjectValue::Unsigned8(node_id),
ObjectValue::Boolean(0), ]),
name: "NMT_EPLNodeID_REC",
category: Category::Mandatory,
access: None,
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
let flags = FeatureFlags::ISOCHRONOUS | FeatureFlags::SDO_ASND | FeatureFlags::SDO_UDP;
od.insert(
0x1F82, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned32(flags.0)),
name: "NMT_FeatureFlags_U32",
category: Category::Mandatory,
access: Some(AccessType::Constant),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1C14, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned32(100000)), name: "DLL_CNLossOfSocTolerance_U32",
category: Category::Mandatory, access: Some(AccessType::ReadWriteStore),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1F99, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned32(5_000_000)), name: "NMT_CNBasicEthernetTimeout_U32",
category: Category::Mandatory,
access: Some(AccessType::ReadWriteStore),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1F8C, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned8(NmtState::NmtGsInitialising as u8)),
name: "NMT_CurrNMTState_U8",
category: Category::Mandatory,
access: Some(AccessType::ReadOnly),
default_value: None,
value_range: None,
pdo_mapping: Some(PdoMapping::No),
},
);
od.insert(
0x1F83, ObjectEntry {
object: Object::Variable(ObjectValue::Unsigned8(0x15)), name: "NMT_EPLVersion_U8",
category: Category::Mandatory,
access: Some(AccessType::Constant),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1F98, ObjectEntry {
object: Object::Record(vec![
ObjectValue::Unsigned16(1490), ObjectValue::Unsigned16(1490), ObjectValue::Unsigned32(10000), ObjectValue::Unsigned16(100), ObjectValue::Unsigned16(100), ObjectValue::Unsigned32(20000), ObjectValue::Unsigned8(0), ObjectValue::Unsigned16(300), ObjectValue::Unsigned16(2), ]),
name: "NMT_CycleTiming_REC",
category: Category::Mandatory,
access: None,
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1020, ObjectEntry {
object: Object::Record(vec![
ObjectValue::Unsigned32(0), ObjectValue::Unsigned32(0), ]),
name: "CFM_VerifyConfiguration_REC",
category: Category::Mandatory,
access: None,
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1F52, ObjectEntry {
object: Object::Record(vec![
ObjectValue::Unsigned32(0), ObjectValue::Unsigned32(0), ]),
name: "PDL_LocVerApplSw_REC",
category: Category::Conditional,
access: None,
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1E40, ObjectEntry {
object: Object::Record(vec![
ObjectValue::Unsigned16(1), ObjectValue::Unsigned32(0xC0A86400 | node_id as u32), ObjectValue::Unsigned32(0xFFFFFF00), ObjectValue::Unsigned16(1500), ObjectValue::Unsigned32(0xC0A864FE), ]),
name: "NWL_IpAddrTable_0h_REC",
category: Category::Conditional,
access: None,
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od.insert(
0x1F9A, ObjectEntry {
object: Object::Variable(ObjectValue::VisibleString(format!("{}-TestHost", node_id))),
name: "NMT_HostName_VSTR",
category: Category::Conditional,
access: Some(AccessType::ReadWriteStore),
default_value: None,
value_range: None,
pdo_mapping: None,
},
);
od
}
fn setup_node<'a>(
interface_name: &str,
node_id: u8,
od: ObjectDictionary<'a>,
) -> (LinuxPnetInterface, ControlledNode<'a>) {
let interface = match LinuxPnetInterface::new(interface_name, node_id) {
Ok(iface) => iface,
Err(e) => {
error!("Failed to create interface '{}': {}", interface_name, e);
panic!("Interface creation failed.");
}
};
let mac = interface.local_mac_address();
let node = match ControlledNode::new(od, mac.into()) {
Ok(n) => n,
Err(e) => {
error!("Failed to create ControlledNode: {:?}", e);
panic!("Node creation failed.");
}
};
(interface, node)
}
fn send_frame_helper(interface: &mut LinuxPnetInterface, frame_bytes: &[u8], frame_name: &str) {
info!("[MN] Sending {}...", frame_name);
if let Err(e) = interface.send_frame(frame_bytes) {
error!("[MN] Failed to send {}: {:?}", frame_name, e);
panic!("Failed to send {}", frame_name);
}
}
fn build_sdo_payload(seq_header: SequenceLayerHeader, cmd: SdoCommand) -> Vec<u8> {
let mut payload = vec![0u8; 1500]; let mut offset = 0;
offset += seq_header
.serialize(&mut payload[offset..offset + 4])
.unwrap_or_else(|e| {
error!("Error serializing Seq Header: {:?}", e);
0
});
offset += cmd.serialize(&mut payload[offset..]).unwrap_or_else(|e| {
error!("Error serializing SDO Command: {:?}", e);
0
});
payload.truncate(offset); payload
}
fn receive_frame_helper<F>(
interface: &mut LinuxPnetInterface,
filter_mac: [u8; 6],
description: &str,
mut condition: F,
) -> Result<PowerlinkFrame, String>
where
F: FnMut(&PowerlinkFrame) -> bool, {
let mut buffer = [0u8; 1518];
let start_time = Instant::now();
info!("Waiting for {}...", description);
while start_time.elapsed() < TEST_TIMEOUT {
match interface.receive_frame(&mut buffer) {
Ok(bytes) if bytes > 0 => {
let received_slice = &buffer[..bytes];
if bytes >= 12 && received_slice[6..12] == filter_mac {
continue;
}
match deserialize_frame(received_slice) {
Ok(frame) => {
if condition(&frame) {
info!("Received expected {}: {:?}", description, frame);
return Ok(frame); } else {
trace!("Received other frame: {:?}", frame);
}
}
Err(PowerlinkError::InvalidEthernetFrame) => {
trace!("Received non-POWERLINK frame.");
}
Err(e) => {
warn!("Error deserializing received frame: {:?}", e);
}
}
}
Ok(_) => { }
Err(PowerlinkError::IoError) => { }
Err(e) => {
error!("Receive error: {:?}", e);
}
}
thread::sleep(Duration::from_millis(10)); }
Err(format!("Timeout waiting for {}", description))
}
fn run_cn_logic(interface_name: &str) {
env_logger::try_init().ok();
let cn_node_id = get_cn_node_id().expect("Failed to parse CN Node ID from environment");
info!(
"[CN] Thread started. Node ID: {}. Interface: {}",
cn_node_id, interface_name
);
let od = get_test_od(cn_node_id);
let (mut cn_interface, mut node) = setup_node(interface_name, cn_node_id, od);
let cn_mac = cn_interface.local_mac_address();
info!("[CN] Initial NMT state: {:?}", node.nmt_state());
let mut buffer = [0u8; 1518];
let start_time = Instant::now();
loop {
if start_time.elapsed() > TEST_TIMEOUT {
error!("[CN] Test timed out.");
panic!("[CN] Test timed out.");
}
let current_time_us = start_time.elapsed().as_micros() as u64;
let action;
match cn_interface.receive_frame(&mut buffer) {
Ok(bytes) => {
if bytes > 0 {
trace!("[CN] Received {} bytes.", bytes);
let received_slice = &buffer[..bytes];
if bytes >= 12 && received_slice[6..12] == cn_mac {
trace!("[CN] Ignoring received frame from self.");
continue;
}
action = node.process_raw_frame(received_slice, current_time_us);
debug!(
"[CN] NMT state after processing frame: {:?}",
node.nmt_state()
);
} else {
action = node.tick(current_time_us);
debug!("[CN] NMT state after tick: {:?}", node.nmt_state());
}
}
Err(PowerlinkError::IoError) => {
action = node.tick(current_time_us);
}
Err(e) => {
error!("[CN] Receive error: {:?}", e);
action = NodeAction::NoAction;
}
}
if let NodeAction::SendFrame(response) = action {
info!("[CN] Sending response ({} bytes)...", response.len());
if let Err(e) = cn_interface.send_frame(&response) {
error!("[CN] Failed to send response: {:?}", e);
}
}
}
}
fn run_mn_logic(interface_name: &str, test_to_run: &str) {
env_logger::try_init().ok();
let cn_node_id = get_cn_node_id().expect("Failed to parse CN Node ID from environment");
info!(
"[MN] Starting MN logic. Target CN ID: {}. Interface: {}. Test: {}",
cn_node_id, interface_name, test_to_run
);
let mut mn_interface = match LinuxPnetInterface::new(interface_name, C_ADR_MN_DEF_NODE_ID) {
Ok(iface) => iface,
Err(e) => {
error!("[MN] Failed to create interface: {}", e);
panic!("[MN] Interface creation failed.");
}
};
let mn_mac = mn_interface.local_mac_address();
thread::sleep(Duration::from_millis(700));
let net_time = NetTime {
seconds: 0,
nanoseconds: 0,
};
let relative_time = RelativeTime {
seconds: 0,
nanoseconds: 0,
};
let soc_frame = SocFrame::new(mn_mac.into(), Default::default(), net_time, relative_time);
let mut soc_buffer = vec![0u8; 64];
let soc_size = soc_frame.serialize(&mut soc_buffer).unwrap();
soc_buffer.truncate(soc_size);
send_frame_helper(&mut mn_interface, &soc_buffer, "SoC (1st)");
thread::sleep(SLEEP_DURATION);
let soa = SoAFrame::new(
mn_mac.into(),
NmtState::NmtPreOperational1,
Default::default(),
RequestedServiceId::IdentRequest,
NodeId(cn_node_id),
EPLVersion(0x15),
);
let mut soa_buffer = vec![0u8; 64];
let soa_size = soa.serialize(&mut soa_buffer).unwrap();
soa_buffer.truncate(soa_size);
send_frame_helper(&mut mn_interface, &soa_buffer, "SoA(IdentRequest)");
let _ident_response = receive_frame_helper(
&mut mn_interface,
mn_mac,
"ASnd(IdentResponse)",
|frame| match frame {
PowerlinkFrame::ASnd(asnd)
if asnd.source == NodeId(cn_node_id)
&& asnd.destination == NodeId(C_ADR_MN_DEF_NODE_ID)
&& asnd.service_id == ServiceId::IdentResponse =>
{
true }
_ => false,
},
)
.expect("Did not receive IdentResponse");
match test_to_run {
"test_cn_responds_to_ident_request" => {
info!("[MN] IdentResponse test successful.");
}
"test_sdo_read_by_index_over_asnd" => {
run_sdo_test_logic(&mut mn_interface, mn_mac, cn_node_id, &soc_buffer);
}
_ => panic!("Unknown test case: {}", test_to_run),
}
info!(
"[MN] Test logic completed successfully for '{}'.",
test_to_run
);
}
fn run_sdo_test_logic(
mn_interface: &mut LinuxPnetInterface,
mn_mac: [u8; 6],
cn_node_id: u8,
soc_buffer: &[u8],
) {
info!("[MN] Running SDO test logic...");
send_frame_helper(mn_interface, soc_buffer, "SoC (2nd for SDO)");
thread::sleep(SLEEP_DURATION);
let mut current_mn_sdo_seq: u8 = 0;
let mut last_acked_cn_sdo_seq: u8 = 63;
let init_cmd = SdoCommand {
header: Default::default(),
data_size: None,
payload: Vec::new(),
};
let init_seq_header = SequenceLayerHeader {
send_sequence_number: current_mn_sdo_seq,
send_con: SendConnState::Initialization,
receive_sequence_number: last_acked_cn_sdo_seq, receive_con: ReceiveConnState::NoConnection,
};
let init_sdo_payload = build_sdo_payload(init_seq_header, init_cmd.clone());
let init_asnd = ASndFrame::new(
mn_mac.into(),
MacAddress([0x01, 0x11, 0x1E, 0x00, 0x00, cn_node_id]),
NodeId(cn_node_id),
NodeId(C_ADR_MN_DEF_NODE_ID),
ServiceId::Sdo,
init_sdo_payload,
);
let mut init_asnd_buffer = vec![0u8; 1500];
let init_asnd_size = init_asnd.serialize(&mut init_asnd_buffer).unwrap();
init_asnd_buffer.truncate(init_asnd_size);
send_frame_helper(mn_interface, &init_asnd_buffer, "ASnd(SDO Init Request)");
let _init_ack_frame = receive_frame_helper(
mn_interface,
mn_mac,
"ASnd(SDO Init ACK)",
|frame| match frame {
PowerlinkFrame::ASnd(asnd) if asnd.service_id == ServiceId::Sdo => {
SequenceLayerHeader::deserialize(&asnd.payload[0..4])
.ok()
.and_then(|seq| {
if seq.send_con == SendConnState::Initialization
&& seq.receive_sequence_number == current_mn_sdo_seq
{
last_acked_cn_sdo_seq = seq.send_sequence_number; Some(true) } else {
None
} })
.unwrap_or(false) }
_ => false,
},
)
.expect("Did not receive SDO Init ACK");
current_mn_sdo_seq = current_mn_sdo_seq.wrapping_add(1) % 64;
let sdo_read_cmd = SdoCommand {
header: CommandLayerHeader {
transaction_id: 1, is_response: false,
is_aborted: false,
segmentation: Segmentation::Expedited,
command_id: CommandId::ReadByIndex,
segment_size: 4, },
data_size: None,
payload: vec![0x08, 0x10, 0x00, 0x00], };
let read_seq_header = SequenceLayerHeader {
send_sequence_number: current_mn_sdo_seq,
send_con: SendConnState::ConnectionValid,
receive_sequence_number: last_acked_cn_sdo_seq, receive_con: ReceiveConnState::ConnectionValid,
};
let read_sdo_payload = build_sdo_payload(read_seq_header, sdo_read_cmd);
let read_asnd = ASndFrame::new(
mn_mac.into(),
MacAddress([0x01, 0x11, 0x1E, 0x00, 0x00, cn_node_id]),
NodeId(cn_node_id),
NodeId(C_ADR_MN_DEF_NODE_ID),
ServiceId::Sdo,
read_sdo_payload,
);
let mut read_asnd_buffer = vec![0u8; 1500];
let read_asnd_size = read_asnd.serialize(&mut read_asnd_buffer).unwrap();
read_asnd_buffer.truncate(read_asnd_size);
send_frame_helper(
mn_interface,
&read_asnd_buffer,
"ASnd(SDO Read Request + Valid ACK)",
);
let sdo_response_frame = receive_frame_helper(
mn_interface,
mn_mac,
"ASnd(SDO Data Response)",
|frame| match frame {
PowerlinkFrame::ASnd(asnd) if asnd.service_id == ServiceId::Sdo => {
SequenceLayerHeader::deserialize(&asnd.payload[0..4])
.ok()
.and_then(|seq| {
if seq.receive_sequence_number == current_mn_sdo_seq {
last_acked_cn_sdo_seq = seq.send_sequence_number; SdoCommand::deserialize(&asnd.payload[4..])
.ok()
.and_then(|cmd| {
if cmd.header.is_response && !cmd.header.is_aborted {
Some(true) } else {
warn!("Received SDO Abort or non-response cmd: {:?}", cmd);
None }
})
} else {
None
} })
.unwrap_or(false) }
_ => false,
},
)
.expect("Did not receive valid SDO Data Response");
if let PowerlinkFrame::ASnd(asnd) = sdo_response_frame {
let sdo_cmd = SdoCommand::deserialize(&asnd.payload[4..]).unwrap();
let expected_name = "powerlink-rs CN Test";
assert_eq!(sdo_cmd.payload, expected_name.as_bytes());
info!(
"[MN] SDO Read test successful. Received name: {}",
expected_name
);
} else {
panic!("Received frame was not an ASnd");
}
}
fn run_test_logic(test_name: &str) {
let test_interface_name = find_test_interface();
let role = env::var("POWERLINK_TEST_ROLE").unwrap_or_else(|_| "MN".to_string());
if role == "CN" {
run_cn_logic(&test_interface_name);
} else {
run_mn_logic(&test_interface_name, test_name);
}
}
#[test]
#[ignore]
fn test_cn_responds_to_ident_request() {
run_test_logic("test_cn_responds_to_ident_request");
}
#[test]
#[ignore]
fn test_sdo_read_by_index_over_asnd() {
run_test_logic("test_sdo_read_by_index_over_asnd");
}