Skip to main content

Mailbox Gateway

The mailbox gateway implements the ETG.8200 standard and lets external diagnostic tools access the object dictionaries of the EtherCAT master and slaves over UDP/IP.

Entry point MailboxGateway::new(master.index()). master.mailbox_gateway() returns MailboxGatewayService.​

ETG.8200 standard

The mailbox gateway service conforms to the ETG.8200 specification, uses the standard UDP port 0x88A4 (34980), and its frame structure fully meets the requirements of Table 1.

Service control​

MailboxGatewayService is the legacy public entry point returned by master.mailbox_gateway(); its implementation now forwards everything to the lower-layer MailboxGateway, so the Rust side no longer holds copies of the UDP listener thread, frame parsing or response construction.

port() / set_port()​

pub fn port(&self) -> u16
pub fn set_port(&mut self, port: u16)

UDP port number, default 0x88A4 (34980). While running it returns the actually bound port of the lower layer; when not running it returns the configured port.

Automatic offset for multiple instances

When several master instances run, the port is offset automatically according to master_number (the master number, starting at 1) to avoid port conflicts:

  • Master 1: 34980 (default)
  • Master N: 34980 + (N - 1)

To specify the port manually, call set_port() before start() to override the automatic value.

Strict port — no automatic fallback anymore

start() uses the lower layer's strict port policy: the ETG.8200 default port must be bound exclusively, and a failed bind returns Err; unlike the old implementation it does not silently move to port+0..+9 or a system-assigned port. When the port is occupied, call set_port() explicitly and retry.

The port number must be set before the service starts; set_port() calls while running are ignored.

is_running()​

pub fn is_running(&self) -> bool

Whether the service is running (reads the real value from the lower layer).

start()​

pub fn start(&mut self) -> Result<()>

Starts the mailbox gateway service. When it is already running this idempotently returns Ok (but the handle is not marked as "started by this handle"; see the ownership note below). The target master must already be open, otherwise start-up fails.

Example:

let mut gw = master.mailbox_gateway();
gw.start()?; // Failure cases such as an occupied port return Err, propagated with ? (the enclosing function returns Result)
println!("邮箱网关已启动,端口: {}", gw.port()); // Mailbox gateway started, port: {}

stop()​

pub fn stop(&mut self)

Stops the mailbox gateway service and releases the UDP port.

  • The return type is () (legacy signature, unchanged). A timeout while waiting for this stop cannot be reported through the return value; it is written to an Error log instead, and stop() can be called again to retry (at most two attempts).
  • The lower layer's stop waits at most about 2 seconds (drain deadline).
  • Ownership: only a handle that itself started the gateway successfully stops it on stop() / Drop. The gateway may have been started by another handle or another language, so destroying a bystander handle must not shut it down.

Supported protocols​

ProtocolTypeDescription
CoE0x03SDO read/write, covering the master (ETG.1510) and slave object dictionaries
FoE0x04File transfer (currently single-packet only)
SoE0x05IDN parameter read/write (ETG.1020 standard)
VoE0x0FVendor-specific protocol pass-through
Address routing
  • Address = 0x0000 -> access the master object dictionary (CoE only)
  • Address = slave station address -> pass through to the corresponding slave (CoE / SoE / FoE / VoE)

Slave mailbox transactions (CoE / SoE / FoE / VoE forwarding) are now all executed by the lower-layer gateway; the old Rust implementation's 5-second default timeout was removed together with the local implementation, so timeout behavior follows the lower layer.

Frame layout​

EtherCAT Header:

  • Length: total length of Mailbox Header + Data
  • Data Type: fixed to 0x05 (Mailbox communication)

Mailbox Header:

  • Length: length of the mailbox data part
  • Address: 0x0000=master, anything else=slave station address
  • Type: 0x03=CoE, 0x04=SoE, 0x05=FoE, 0x0F=VoE
  • Cnt: mailbox counter (cycles 1-7)

Runtime statistics (MailboxGatewayStats)​

Accumulated statistics since the mailbox gateway started (packets received/sent / routing counts / drop counts), used for monitoring panels and alarm thresholds. Get a live snapshot with MailboxGatewayService::get_statistics(); clear the counters with reset_statistics().

get_statistics() / reset_statistics()​

pub fn get_statistics(&self) -> MailboxGatewayStats
pub fn reset_statistics(&self)

get_statistics() returns a snapshot of the current accumulated statistics — all of it comes from the lower-layer statistics interface, the same counters as the other five language SDKs; reset_statistics() clears them.

When the lower-layer statistics read fails (master not open / invalid index), get_statistics() returns an all-zero snapshot — the public return type is a struct rather than an Option, so it cannot be turned into a failure channel; that failure is already logged as ERROR at the lower layer.

MailboxGatewayStats structure​

#[derive(Debug, Default, Clone, Copy)]
pub struct MailboxGatewayStats {
pub rx_packets: u64, // UDP packets received
pub tx_packets: u64, // Response packets sent
pub rx_bytes: u64, // Bytes received
pub tx_bytes: u64, // Bytes sent
pub master_od_requests: u64, // Requests routed to the master OD
pub slave_requests: u64, // Requests routed to slave mailboxes
pub drop_malformed: u64, // Incremented per frame that fails ETG.8200 header/length validation
pub drop_timeout: u64, // Drops due to slave response timeout
}
drop_timeout semantics now match the lower layer

In the old local Rust implementation drop_timeout counted "UDP response send failures", whereas the lower layer counts "slave response timeouts". After the local implementation was removed, this aligns with the other five language SDKs on the lower-layer semantics, and there is no second set of local counters.

Example:

let mut gw = master.mailbox_gateway();
gw.start()?; // Failure returns Err, propagated with ?

// ... clients send requests for a while ...

let s = gw.get_statistics();
println!(
"收包 {} / 发包 {} | 主站OD={} 从站={} | 丢弃(格式错误)={} 丢弃(超时)={}", // Rx packets {} / tx packets {} | master OD={} slave={} | dropped (bad format)={} dropped (timeout)={}
s.rx_packets, s.tx_packets,
s.master_od_requests, s.slave_requests,
s.drop_malformed, s.drop_timeout,
);

let total = s.rx_packets;
if total > 0 {
let dropped = s.drop_malformed + s.drop_timeout;
let rate = dropped as f64 / total as f64;
if rate > 0.05 {
eprintln!("警告: 邮箱网关丢弃率过高 {:.1}%", rate * 100.0); // Warning: mailbox gateway drop rate too high: {:.1}%
}
}

MailboxGateway​

The complete wrapper around the ETG.8200 mailbox gateway, 1:1 with the runtime and with no extra processing. UDP/TCP listening, frame parsing, CoE/SoE/FoE/VoE forwarding, the ETG.1510 master OD and Discovery-based master selection are all done by the runtime.

MailboxGatewayService (master.mailbox_gateway()) now forwards to this type as well; both call the same implementation, so it is no longer either/or.

Lower-layer preconditions

The target master must already be open, otherwise start-up fails.

MailboxGateway::new()​

pub fn new(master_index: u16) -> Self

Creates a lower-layer mailbox gateway handle.

Parameters:

  • master_index (u16) — master index (≥1; 0 is invalid, master indexes start at 1); master initialization must already be complete before the call

Example:

use darra_ethercat::MailboxGateway;

let gw = MailboxGateway::new(master.index());
gw.start_default()?;

start() / start_default()​

pub fn start(&self, udp_port: u16) -> Result<()>
pub fn start_default(&self) -> Result<()>

Starts the UDP mailbox gateway. start_default() uses the standard port 0x88A4 (34980).

The port policy is the strict port one (ETG.8200): an occupied port fails immediately; the port is never switched silently. Already running → idempotently returns Ok.

Parameters:

  • udp_port (u16) — UDP port; 0 = use the default port 0x88A4

Returns:

  • Result<()> — a value other than 0 from the lower layer means success; failures return Err and are not wrapped as Ok

stop()​

pub fn stop(&self) -> Result<()>

Stops the UDP mailbox gateway (idempotent). An Err corresponds only to this stop timing out: it could not stop fully within 2 seconds; calling stop() again retries safely (it does not reuse the previous-generation handle, nor allow the next generation to start early).

is_running() / port()​

pub fn is_running(&self) -> bool
pub fn port(&self) -> u16

is_running() queries whether the UDP gateway is running. port() gets the actual UDP port; it returns 0 when not started.

statistics() / reset_statistics()​

pub fn statistics(&self) -> Option<MbgNativeStats>
pub fn reset_statistics(&self)

statistics() gets the current statistics snapshot and returns None on failure. reset_statistics() clears the counters (no return value).

Related structures:

pub struct MbgNativeStats {
pub rx_packets: u64,
pub rx_bytes: u64,
pub tx_packets: u64,
pub tx_bytes: u64,
pub forwarded_ok: u64,
pub forwarded_failed: u64,
pub timeout_count: u64,
pub invalid_frame: u64,
pub unknown_target: u64,
pub unsupported_type: u64,
pub master_requests: u64,
pub udp_port: u16,
pub is_running: bool,
pub discovery_requests: u64,
pub tcp_connections: u64,
pub tcp_active: u64,
pub tcp_port: u16,
pub tcp_running: bool,
pub selected_master: u8,
pub master_od_requests: u64,
pub slave_requests: u64,
pub drop_malformed: u64,
pub drop_timeout: u64,
}

Example:

let gw = MailboxGateway::new(master.index());
gw.start_default()?;
if let Some(s) = gw.statistics() {
println!("收包 {} / 发包 {}", s.rx_packets, s.tx_packets); // Rx packets {} / tx packets {}
}

start_tcp() / stop_tcp()​

pub fn start_tcp(&self, tcp_port: u16) -> Result<()>
pub fn stop_tcp(&self) -> Result<()>

Starts / stops the TCP mailbox gateway. stop_tcp() has the same Err semantics as stop() (-5 = drain timeout, retryable); both directions are idempotent.

Parameters:

  • tcp_port (u16) — TCP port; 0 = default 0x88A4

The port policy is the same as start() (strict port).

tcp_is_running() / tcp_port()​

pub fn tcp_is_running(&self) -> bool
pub fn tcp_port(&self) -> u16

Queries whether the TCP channel is running, plus the actual TCP port (returns 0 when not started).

selected_master() / set_selected_master()​

pub fn selected_master(&self) -> u16
pub fn set_selected_master(&self, selected: u16) -> Result<()>

Reads / sets the master index selected by Discovery (ETG.8200 §7.6 / §7.5). selected_master() returns 0xFFFF when master_index is invalid; set_selected_master returns Err when "master_index is invalid / selected is out of range / the selected master is not yet open".

Complete example​

Scenario A — integrating an existing configuration/debug tool​

Let a third-party configuration tool (or an engineer's tool) access the master/slave object dictionaries over UDP, without modifying the firmware of the controlled device.

Scenario B — custom diagnostics or automation scripts​

Collect slave parameters periodically, read objects in batches or perform remote configuration through a script/service.

Scenario C — remote monitoring and alarm collection​

Use the gateway for remote passive monitoring (periodic reads or subscriptions) and report key data to a central monitoring system.

Start the mailbox gateway​

use darra_ethercat::EtherCATMaster;

let mut master = EtherCATMaster::from_json_file("config.json")?;

master.set_state(EcState::Operational)?;

// Start the mailbox gateway (optional: custom port)
let mut gw = master.mailbox_gateway();
// gw.set_port(12345); // Default is 34980; set before start if you need to change it
gw.start()?;
println!("邮箱网关已启动,端口: {}", gw.port()); // Mailbox gateway started, port: {}

// PDO runs automatically on a background thread; the gateway serves the mailbox in OP
// ... waiting ...

gw.stop();
// master is released automatically when it goes out of scope

External Rust client​

use std::net::UdpSocket;

/// ETG.8200 mailbox gateway UDP client
struct MailboxGatewayClient {
socket: UdpSocket,
gateway_addr: String,
}

impl MailboxGatewayClient {
fn new(host: &str, port: u16) -> std::io::Result<Self> {
let socket = UdpSocket::bind("0.0.0.0:0")?;
socket.set_read_timeout(Some(std::time::Duration::from_secs(3)))?;
Ok(Self {
socket,
gateway_addr: format!("{}:{}", host, port),
})
}

/// Build an ETG.8200 frame: EtherCAT Header (2) + Mailbox Header (6) + Data
fn build_frame(&self, address: u16, mb_type: u8, mb_data: &[u8]) -> Vec<u8> {
let mb_len = mb_data.len() as u16;
let ecat_len = 6 + mb_len;

let mut frame = Vec::with_capacity(2 + 6 + mb_data.len());

// EtherCAT Header: Length[10:0] | DataType[15:12]=0x05
let ecat_header: u16 = (0x05 << 12) | (ecat_len & 0x07FF);
frame.extend_from_slice(&ecat_header.to_le_bytes());

// Mailbox Header
frame.extend_from_slice(&mb_len.to_le_bytes()); // Length
frame.extend_from_slice(&address.to_le_bytes()); // Address
frame.push(0x00); // Channel + Priority
frame.push(mb_type << 4); // Type[7:4]

// Mailbox Data
frame.extend_from_slice(mb_data);
frame
}

/// Send a request and receive the response
fn send_request(&self, address: u16, mb_type: u8, mb_data: &[u8]) -> std::io::Result<Vec<u8>> {
let frame = self.build_frame(address, mb_type, mb_data);
self.socket.send_to(&frame, &self.gateway_addr)?;

let mut buf = [0u8; 4096];
let (len, _) = self.socket.recv_from(&mut buf)?;
Ok(buf[..len].to_vec())
}

/// CoE SDO Upload (read the object dictionary)
/// address: 0x0000=master, anything else=slave station address
fn coe_sdo_read(&self, address: u16, index: u16, subindex: u8) -> std::io::Result<Vec<u8>> {
let mut co_data = vec![0u8; 8];
co_data[1] = 0x20; // CoE Type: SDO Request
co_data[2] = 0x40; // SDO Upload (Read)
co_data[3..5].copy_from_slice(&index.to_le_bytes());
co_data[5] = subindex;
self.send_request(address, 0x03, &co_data) // 0x03 = CoE
}

/// CoE SDO Download (write the object dictionary)
fn coe_sdo_write(&self, address: u16, index: u16, subindex: u8, value: &[u8]) -> std::io::Result<Vec<u8>> {
let mut co_data = vec![0u8; 6 + value.len()];
co_data[1] = 0x20; // CoE Type: SDO Request
co_data[2] = 0x20; // SDO Download (Write)
co_data[3..5].copy_from_slice(&index.to_le_bytes());
co_data[5] = subindex;
co_data[6..6 + value.len()].copy_from_slice(value);
self.send_request(address, 0x03, &co_data)
}

/// SoE Read (read an IDN parameter)
/// element_flags: 0x00=Name, 0x01=Attribute, 0x02=Unit, 0x03=Min, 0x04=Max, 0x05=Value, 0x06=Default, 0x07=DataType
fn soe_read(&self, address: u16, idn: u16, drive_no: u8, element: u8) -> std::io::Result<Vec<u8>> {
let mut soe_data = vec![0u8; 4];
soe_data[0] = 0x01; // OpCode: Read
soe_data[1] = (drive_no << 3) | (element & 0x07);
soe_data[2..4].copy_from_slice(&idn.to_le_bytes());
self.send_request(address, 0x04, &soe_data) // 0x04 = SoE
}

/// SoE Write (write an IDN parameter)
fn soe_write(&self, address: u16, idn: u16, value: &[u8], drive_no: u8, element: u8) -> std::io::Result<Vec<u8>> {
let mut soe_data = vec![0u8; 4 + value.len()];
soe_data[0] = 0x02; // OpCode: Write
soe_data[1] = (drive_no << 3) | (element & 0x07);
soe_data[2..4].copy_from_slice(&idn.to_le_bytes());
soe_data[4..4 + value.len()].copy_from_slice(value);
self.send_request(address, 0x04, &soe_data)
}

/// FoE Read (download a file from the slave; single packet only)
fn foe_read(&self, address: u16, filename: &str) -> std::io::Result<Vec<u8>> {
let name_bytes = filename.as_bytes();
let mut foe_data = vec![0u8; 5 + name_bytes.len() + 1];
foe_data[0] = 0x01; // OpCode: Read Request
foe_data[5..5 + name_bytes.len()].copy_from_slice(name_bytes);
foe_data[5 + name_bytes.len()] = 0x00; // null terminator
self.send_request(address, 0x05, &foe_data) // 0x05 = FoE
}

/// VoE send/receive (vendor-specific protocol)
fn voe_send(&self, address: u16, vendor_id: u32, vendor_type: u16, data: &[u8]) -> std::io::Result<Vec<u8>> {
let mut voe_data = vec![0u8; 6 + data.len()];
voe_data[0..4].copy_from_slice(&vendor_id.to_le_bytes()); // VendorID
voe_data[4..6].copy_from_slice(&vendor_type.to_le_bytes()); // VendorType
voe_data[6..6 + data.len()].copy_from_slice(data);
self.send_request(address, 0x0F, &voe_data) // 0x0F = VoE
}
}

// --- Usage example ---
let client = MailboxGatewayClient::new("192.168.1.100", 0x88A4)?;

// CoE: read the master object dictionary (address=0x0000)
let resp = client.coe_sdo_read(0x0000, 0x1018, 0x01)?;
println!("主站 VendorID: {:02X?}", resp); // Master VendorID: {:02X?}

// CoE: read/write the slave object dictionary
let resp = client.coe_sdo_read(0x03E9, 0x6040, 0x00)?;
client.coe_sdo_write(0x03E9, 0x6040, 0x00, &0x0006u16.to_le_bytes())?;

// SoE: read a slave IDN parameter value
let resp = client.soe_read(0x03E9, 32, 0, 0x05)?;

// SoE: write a slave IDN parameter value
client.soe_write(0x03E9, 32, &1000u32.to_le_bytes(), 0, 0x05)?;

// FoE: download a file from the slave
let resp = client.foe_read(0x03E9, "firmware.bin")?;

// VoE: vendor-specific protocol
let resp = client.voe_send(0x03E9, 0x00001164, 0x0001, &[0x01, 0x02])?;

Protocol details​

CoE (CAN over EtherCAT)​

Supported operations:

  • SDO Upload (0x40) - read the object dictionary
  • SDO Download (0x20) - write the object dictionary
  • SDO Abort (0x80) - error response

Error codes:

  • 0x06020000 — object does not exist
  • 0x06010000 — unsupported access
  • 0x06010002 — write protection
  • 0x05040001 — command not implemented
  • 0x08000000 — general error

SoE (Servo over EtherCAT)​

Supported operations:

  • IDN Read (0x01) - read an IDN parameter
  • IDN Write (0x02) - write an IDN parameter

Supported elements:

  • Value (0x05) — parameter value
  • Name (0x00) — parameter name
  • Attribute (0x01) — parameter attribute
  • Unit (0x02) — unit
  • Min/Max (0x03/0x04) — minimum/maximum value
  • Default (0x06) — default value
  • Data Type (0x07) — data type

Error codes:

  • 0x8001 — service not available
  • 0x1001 — invalid command
  • 0x1009 — IDN does not exist
  • 0x3002 — invalid data size
  • 0x7002 — write failed
  • 0x8000 — general error

FoE (File over EtherCAT)​

Supported operations:

  • Read Request (0x01) - file download request
  • Write Request (0x02) - file upload preparation
  • Data (0x03) - file data transfer
  • Ack (0x04) - acknowledgement
  • Error (0x05) - error response

Current limitations:

  • Only single-packet file transfer is supported (small files)
  • Full segmented transfer requires session state management (a future version)

Error codes:

  • 0x00008001 — invalid opcode / not implemented
  • 0x00008002 — file not found
  • 0x00008003 — illegal file name
  • 0x00008000 — general error

VoE (Vendor over EtherCAT)​

Frame layout:

  • VendorID (4 bytes) — vendor identifier
  • VendorType (2 bytes) — vendor type
  • Data (n bytes) — vendor-specific data

Purpose:

  • Full pass-through to the slave VoE interface
  • Automatic request/response handling
  • Supports data of any length

Error codes:

  • An error frame is VendorID 0 + VendorType 0xFFFF (there is no separate error code field)

Error handling​

ProtocolError typeError codeDescription
CoEObject does not exist0x06020000The requested object or slave does not exist
CoEUnsupported access0x06010000The protocol type is unsupported or the slave has no such function
CoEWrite protection0x06010002Attempt to write a read-only object
CoECommand not implemented0x05040001The SDO command specifier is not supported
CoEGeneral error0x08000000Other processing error
SoEProtocol error / unsupported0x7001Malformed frame or unsupported opcode
SoEWrite failed0x7002IDN parameter write failed
FoENot implemented / frame error0x00008001Unsupported opcode or frame too short
FoEFile not found0x00008002The requested file does not exist
VoEError frame—VendorID 0 + VendorType 0xFFFF

Limitations​

Implemented features​

  • Full CoE pass-through
  • SoE IDN parameter access
  • FoE single-packet file transfer
  • VoE vendor protocol pass-through
  • Master object dictionary access
  • Slave mailbox pass-through
  • Error handling and error code mapping

Features not yet implemented​

  • FoE segmented transfer (large file support)
  • Address mapping table (+0x8000 virtual mapping)
  • Multicast/broadcast requests
  • Session state management
Network security

By default the gateway is a strong pass-through, allowing network access to the entire object dictionaries of the master and slaves. Recommendations:

  • Always use it on a controlled network, or restrict access through an IP allowlist / VPN tunnel
  • Combine it with operating system firewall rules and allow only trusted source IPs
  • Enable it with care in production environments, and avoid exposing it to the public internet
Performance impact

The mailbox gateway runs in the lower layer and has minimal impact on main-loop performance. However, a large number of synchronous SDO/mailbox operations can still affect overall latency — limit concurrency and rate appropriately.