Skip to main content

FoE (File over EtherCAT)

The FoE protocol transfers files to and from EtherCAT slaves; it covers scenarios such as firmware updates and uploading or downloading configuration files.

Get a FoEInstance through slave.foe(), or construct one directly with FoEInstance::new(master_index, slave_index).​

Honest boundaries​

  • Read buffer / file size: download has the lower layer allocate and then copies file_size bytes into a Vec<u8>; it is not an "arbitrary size" user buffer
  • Mailbox gateway WRQ: the stateful write session is not implemented. Write Request (opcode 0x02) / Data / Ack fail with the FoE Error frame 0x00008001, not an ACK. Do not report a failed WRQ as an ACK

Public fields​

CategoryPropertyTypeRead/writeDescription
Configurationdefault_timeout_msi32read/writeDefault timeout in milliseconds, default 5000 (5 s)
default_passwordu32read/writeDefault password, default 0

File transfer​

download()​

pub fn download(&mut self, filename: &str, password: Option<u32>,
timeout_ms: Option<i32>) -> Result<Vec<u8>>

Downloads (reads) a file from the slave device. The lower layer allocates and copies file_size bytes into a Vec<u8>; it is not an arbitrary-size user buffer.

&mut self

On failure, download maps the negative error code that the lower layer returns through file_size into last_error, which is why the signature takes &mut self; bind the FoEInstance with let mut foe = ... before calling. Read the concrete failure reason with last_error() afterwards.

Parameters:

  • filename (&str) — name of the file to download
  • password (Option<u32>) — FoE password (default_password is used when None)
  • timeout_ms (Option<i32>) — timeout in milliseconds (default_timeout_ms is used when None)

Returns:

  • Result<Vec<u8>> — file content as a byte array; on failure it returns Err and writes the error code into last_error

Example:

let mut foe = slave.foe();

// Basic download
let firmware = foe.download("firmware.bin", None, None)?;

// With an explicit password and timeout
let config = foe.download("config.xml", Some(12345), Some(10000))?;

upload()​

pub fn upload(&mut self, filename: &str, file_data: &[u8], password: Option<u32>,
timeout_ms: Option<i32>) -> Result<()>

Uploads (writes) a file to the slave device.

Parameters:

  • filename (&str) — name of the file to upload
  • file_data (&[u8]) — file data to write
  • password (Option<u32>) — FoE password (default_password is used when None)
  • timeout_ms (Option<i32>) — timeout in milliseconds (default_timeout_ms is used when None)

Returns:

  • Result<()> — success or error

Example:

let mut foe = slave.foe();

// Basic upload
let new_firmware = std::fs::read("new_firmware.bin")?;
foe.upload("firmware.bin", &new_firmware, None, None)?;

// With an explicit password
foe.upload("firmware.bin", &new_firmware, Some(12345), None)?;

download_with_crc()​

pub fn download_with_crc(&mut self, filename: &str, password: Option<u32>,
timeout_ms: Option<i32>, enable_crc: bool) -> Result<Vec<u8>>

File download with a CRC option. It still returns the file content itself and does not return the CRC value separately: the CRC is checked / appended during the transfer and is not exposed to the caller.

Differences from download():

  • A single enable_crc switch controls three transfer options (CRC enabled / strict checking / automatic CRC append); passing false turns all three off instead of keeping any default combination
  • Failure detection is stricter: the call returns Err when the transfer fails, no data was obtained, or the returned length is ≤ 0. download() does not treat 「returned length = 0」 as a failure; the CRC variant does
  • On failure last_error is always recorded as NotDefined, with no error-code mapping (use download() for precise error codes); on success it is cleared to None
  • Like download() it takes &mut self (it writes last_error) and blocks until the transfer completes or times out

Parameters:

  • filename (&str) — name of the file to download
  • password (Option<u32>) — FoE password (default_password is used when None)
  • timeout_ms (Option<i32>) — timeout in milliseconds (default_timeout_ms is used when None)
  • enable_crc (bool) — whether to enable CRC checking (strict checking and automatic CRC append are enabled together)

Example:

let mut foe = slave.foe();

// Download with CRC checking enabled
let firmware = foe.download_with_crc("firmware.bin", None, None, true)?;

// Turn CRC off (all three options off)
let config = foe.download_with_crc("config.xml", Some(12345), Some(10000), false)?;

upload_with_crc()​

pub fn upload_with_crc(&mut self, filename: &str, file_data: &[u8], password: Option<u32>,
timeout_ms: Option<i32>, enable_crc: bool) -> Result<()>

File upload with a CRC option. Differences from upload():

  • A single enable_crc switch controls three transfer options (CRC enabled / strict checking / automatic CRC append); when that transfer fails it only returns Err, and the interface does not distinguish a "CRC check failure" from other failure reasons
  • On failure last_error is always recorded as NotDefined; on success it is cleared to None
  • It returns Result<()> and does not pass back a CRC value; the check result can only be inferred from success / failure
  • An empty file_data is rejected before the transfer starts (InvalidParameter), &mut self is used, and the call blocks until completion or timeout, all the same as upload()

Parameters:

  • filename (&str) — name of the file to upload
  • file_data (&[u8]) — file data to write
  • password (Option<u32>) — FoE password (default_password is used when None)
  • timeout_ms (Option<i32>) — timeout in milliseconds (default_timeout_ms is used when None)
  • enable_crc (bool) — whether to enable CRC checking (strict checking and automatic CRC append are enabled together)

Example:

let mut foe = slave.foe();
let firmware = std::fs::read("new_firmware.bin")?;

foe.upload_with_crc("firmware.bin", &firmware, None, None, true)?;

Progress events​

FoEProgressCallback​

pub type FoEProgressCallback =
extern "C" fn(slave: u16, packet_number: c_int, data_size: c_int);

The FoE transfer progress callback type. It is a bare extern "C" function pointer (not a Box<dyn Fn>), so it cannot capture environment variables; only a standalone extern "C" fn item can be passed. Callback parameters: (slave_index, packet_number, data_size). Once registered, download() / upload() push progress per data packet automatically. The callback runs on an SDK-internal thread; do not block for long or perform file I/O.

When you need to access external state from the callback (such as the total packet count or a progress-bar handle), relay it through a global static (AtomicUsize / Mutex<...>); or use the BUSY hook described below (FoEBusyCallback is an Arc<dyn Fn>, so it supports closure capture).

Example:

use std::os::raw::c_int;

extern "C" fn on_foe_progress(slave: u16, pkt: c_int, size: c_int) {
print!("\rSlave {} 包 {} ({} 字节)", slave, pkt, size); // \rSlave {} packet {} ({} bytes)
}

let foe = slave.foe();
foe.set_progress_hook(on_foe_progress);

Transfer progress​

set_progress_hook()​

pub fn set_progress_hook(&self, callback: FoEProgressCallback) -> bool

Sets the FoE transfer progress callback. callback must be a bare extern "C" fn item; a closure cannot be passed.

Callback signature: extern "C" fn(slave_index: u16, packet_number: c_int, data_size: c_int)

clear_progress_hook()​

pub fn clear_progress_hook(&self) -> bool

Clears the FoE progress callback.

estimate_packet_count()​

pub fn estimate_packet_count(file_size: usize, mailbox_size: usize) -> usize

Estimates the number of data packets a file transfer needs.

Parameters:

  • file_size (usize) — file size (bytes)
  • mailbox_size (usize) — mailbox size (bytes)

Example:

use std::os::raw::c_int;
use std::sync::atomic::{AtomicUsize, Ordering};

// The progress callback is a bare extern "C" fn and cannot capture packets, so relay through a global static
static TOTAL_PACKETS: AtomicUsize = AtomicUsize::new(1);

extern "C" fn on_progress(slave: u16, pkt: c_int, _sz: c_int) {
let total = TOTAL_PACKETS.load(Ordering::Relaxed).max(1);
let percent = std::cmp::min(100, pkt as usize * 100 / total);
print!("\rSlave {} 传输进度: {}% (包 {})", slave, percent, pkt); // \rSlave {} transfer progress: {}% (packet {})
}

let mut foe = slave.foe();

let firmware = std::fs::read("new_firmware.bin")?;
let packets = FoEInstance::estimate_packet_count(firmware.len(), 512);
TOTAL_PACKETS.store(packets, Ordering::Relaxed);

foe.set_progress_hook(on_progress);
foe.upload("firmware.bin", &firmware, None, None)?;
foe.clear_progress_hook();
println!("\n上传完成!"); // \nUpload complete!

Error handling​

last_error()​

pub fn last_error(&self) -> Option<FoEErrorCode>

Returns the error code of the most recent FoE operation. The entry of download() clears it first, and on failure it maps the negative error code that the lower layer returns through file_size into this field (on success it returns None); together with the Err branch of Result this gives the concrete failure reason.

is_supported()​

pub fn is_supported(&self) -> bool

Whether the slave supports the FoE mailbox protocol — the bool view of foe_support(): it returns true only when support is known (Some(true)), folds unknown (None) into false, and never overstates support. Use foe_support() / is_support_known() when you need to distinguish "unknown" from "not supported".

foe_support()​

pub fn foe_support(&self) -> Option<bool>

FoE capability in three states: Some(true) = supported, Some(false) = a real read confirms it is not declared, None = unknown.

  • Positive evidence: either bit0 of the FoE details or mbx_proto bit 3 (0x08) is enough for Some(true); no completeness threshold applies
  • Negative verdict (the only path that can produce Some(false)): the general information was really read + FoE details bit0 is explicitly 0 + the mailbox configuration is complete and valid — all three must hold at the same time
  • ESI declaration: <Mailbox><FoE> only upgrades unknown to Some(true); a negative in the ESI never yields false
  • Everything else stays None and is never folded into false

is_supported() is its bool view (true only for Some(true)); is_support_known() returns foe_support().is_some(), which tells "unknown" apart from "not supported". The three-state verdict is authoritative in this method; is_supported() makes no separate decision.

error_description()​

pub fn error_description(error_code: FoEErrorCode) -> &'static str

Gets the Chinese description text of a FoE error code.

Related structures:

#[repr(u16)]
pub enum FoEErrorCode {
NotDefined = 0x8000, // undefined error
NotFound = 0x8001, // file not found
AccessDenied = 0x8002, // access denied
DiskFull = 0x8003, // disk full
Illegal = 0x8004, // illegal operation
PacketNumberWrong = 0x8005, // wrong packet number
AlreadyExists = 0x8006, // file already exists
NoUser = 0x8007, // no such user
BootstrapOnly = 0x8008, // only available in Bootstrap mode
NotBootstrap = 0x8009, // not in Bootstrap mode
NoRights = 0x800A, // insufficient rights
ProgramError = 0x800B, // program error
}

Example:

let mut foe = slave.foe();
let data = foe.download("firmware.bin", None, None);
if let Err(e) = &data {
if let Some(error) = foe.last_error() {
let desc = FoEInstance::error_description(error);
println!("下载失败: {}", desc); // Download failed: {}
}
}

Mailbox protocol common interface (MailboxProtocol)​

MailboxProtocol is the common interface shared by the mailbox protocol instances (protocol identification, capability verdict, per-protocol mailbox statistics).

use darra_ethercat::abstractions::MailboxProtocol;
MethodReturnsDescription
protocol_type()u8Mailbox protocol type code, FoE = 0x04
protocol_name()&'static strProtocol name, always "FoE"
last_error_code()u32Numeric code of the most recent FoE error; 0 = no error
let proto = foe.protocol_type();   // 0x04
let name = foe.protocol_name(); // "FoE"
let code = foe.last_error_code(); // 0 = last FoE operation had no error

protocol_type() / protocol_name() return constants: they start no mailbox transaction and cannot fail; protocol_type() is also the protocol key used when querying mailbox statistics / state per protocol.

last_error_code() and last_error() read the same state: last_error() gives the FoEErrorCode enum and this method gives its numeric value — 0 means no error, and a value other than 0 falls within 0x8000..=0x800B (see the error code table above). download() / upload() and their CRC variants write that state on failure and clear it on success.

Complete example​

Firmware update​

use std::os::raw::c_int;

extern "C" fn on_progress(_slave: u16, pkt: c_int, _sz: c_int) {
print!("\r更新进度: 包 {}", pkt); // \rUpdate progress: packet {}
}

let mut foe = slave.foe();

// Progress callback (bare extern "C" fn, closures cannot be used)
foe.set_progress_hook(on_progress);

// Back up the current firmware
let backup = foe.download("firmware.bin", None, None)?;
std::fs::write("firmware_backup.bin", &backup)?;

// Upload the new firmware
let new_firmware = std::fs::read("new_firmware.bin")?;
foe.upload("firmware.bin", &new_firmware, None, None)?;
foe.clear_progress_hook();
println!("\n固件更新成功"); // \nFirmware update succeeded

Configuration file transfer​

let mut foe = slave.foe();

// Read the configuration (custom password + 10 s timeout)
let config = foe.download("config.xml", Some(0x12345678), Some(10000))?;
let xml_content = String::from_utf8(config)?;
println!("配置内容:\n{}", xml_content); // Configuration contents:\n{}

// Write the new configuration
let new_config = "<Config><Param1>100</Param1></Config>";
foe.upload("config.xml", new_config.as_bytes(), Some(0x12345678), Some(10000))?;

Cancelling transfers and the BUSY hook​

Firmware upgrades or large configuration transfers often run for tens of seconds or even minutes. Two practical capabilities:

  • Mid-transfer cancellation — lets the user press "Cancel" to stop the current transfer instead of waiting for the timeout
  • BUSY hook — while the slave erases or writes flash or programs firmware it returns FoE BUSY frames periodically (ETG.1000.6 §5.10 Table 93); the host uses them to display "xx% programmed"

Cancelling a transfer (cancel)​

pub fn cancel(&self) -> bool

Requests cancellation of the current FoE transfer; it takes effect from the next iteration of the transfer loop, and true means the cancellation request was accepted. clear_cancel(&self) -> bool clears the cancel flag; normally the download() / upload() entries clear it automatically, so call it manually only after an abnormal reset.

Firmware upgrade caution

Cancelling an FoE upload (firmware programming) midway can leave the slave flash partially written and put the device into an unbootable state. In production, call cancel() only when the user explicitly asks for it or as a timeout fallback, and upload the complete firmware again after cancelling.

Example — upload on a background thread + cancel from the main thread:

use std::sync::Arc;
use std::thread;

let mut foe = slave.foe();
let foe_cancel = slave.foe(); // multiple handles share the same slave index

let firmware = std::fs::read("fw.bin")?;
let handle = thread::spawn(move || {
foe.upload("fw.bin", &firmware, None, None)
});

// The user presses the cancel button:
// foe_cancel.cancel();

match handle.join() {
Ok(Ok(())) => println!("固件烧写成功"), // Firmware written successfully
Ok(Err(e)) => eprintln!("固件烧写失败 / 已取消: {:?}", e), // Firmware write failed / cancelled: {:?}
Err(p) => eprintln!("烧写线程异常退出: {:?}", p), // a thread panic is reported as-is
}

BUSY hook (programming progress)​

While the slave performs long-running flash operations it returns BUSY frames periodically per ETG.1000.6 Table 93; the master SDK parses them and reports them through a BUSY callback. set_busy_hook(&self, cb: FoEBusyCallback) registers a callback; several callbacks can be registered on the same master and fire in registration order; clear_busy_hooks(&self) clears all BUSY callbacks and tells the lower layer to unbind them.

Related structures:

use std::sync::Arc;

#[derive(Debug, Clone)]
pub struct FoEBusyEvent {
pub slave_index: u16, // slave index
pub done: u16, // completed progress (flash pages / bytes; the meaning is defined by the slave)
pub entire: u16, // total progress base
pub text: String, // descriptive text supplied by the slave (BusyText, empty when absent)
pub retry_idx: i32, // BUSY retry count for this event (maintained by the lower layer)
pub percent: u32, // percentage computed by the SDK (0..=100; 0 when entire=0)
}

pub type FoEBusyCallback = Arc<dyn Fn(&FoEBusyEvent) + Send + Sync>;
Read the percent field directly

Inside the callback, just read e.percent. The callback runs on an SDK-internal thread; do not block for long or perform file I/O.

Example — a BUSY callback that shows programming progress:

use std::sync::Arc;
use darra_ethercat::slave::foe::{FoEBusyEvent, FoEBusyCallback};

let mut foe = slave.foe();

let hook: FoEBusyCallback = Arc::new(|e: &FoEBusyEvent| {
print!(
"\rSlave {} [{:3}%] {} (重试 {})", // \rSlave {} [{:3}%] {} (retry {})
e.slave_index, e.percent, e.text, e.retry_idx,
);
});
foe.set_busy_hook(Arc::clone(&hook));

let firmware = std::fs::read("fw.bin")?;
foe.upload("fw.bin", &firmware, None, None)?;
foe.clear_busy_hooks();

After enabling the async-tokio feature, FoEInstance exposes the two async signatures download_async() / upload_async(), which can be combined with tokio::select! and cancel() to build long firmware upgrades the user can interrupt.

pub async fn download_async(&self, filename: String, password: Option<u32>,
timeout_ms: Option<i32>) -> Result<Vec<u8>, DarraError>

pub async fn upload_async(&self, filename: String, file_data: Vec<u8>, password: Option<u32>,
timeout_ms: Option<i32>) -> Result<(), DarraError>

*_async takes owned parameters (filename: String / file_data: Vec<u8>) and uses tokio::task::spawn_blocking internally to move the synchronous call onto the blocking thread pool.

Cargo.toml dependencies
[dependencies]
darra-ethercat-master = { path = "../darra-ethercat-master-2.13.16", features = ["async-tokio"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }

Example — progress bar + BUSY programming display + Ctrl+C cancellation:

use std::sync::Arc;
use darra_ethercat::slave::foe::{FoEBusyEvent, FoEBusyCallback};

let foe = slave.foe();

// 1. BUSY callback showing the progress bar
let hook: FoEBusyCallback = Arc::new(|e: &FoEBusyEvent| {
if e.entire > 0 {
print!("\r[烧写中] {:3}% ({}/{}) {}", e.percent, e.done, e.entire, e.text); // \r[writing] {:3}% ({}/{}) {}
}
});
foe.set_busy_hook(Arc::clone(&hook));

// 2. Upload in the background + cancel on Ctrl+C
let data = std::fs::read("fw.bin")?;
let foe_cancel = slave.foe(); // multiple handles share the same index and are used for cancel

let upload_task = tokio::spawn(async move {
foe.upload_async("fw.bin".to_string(), data, None, None).await
});

tokio::select! {
res = upload_task => {
match res {
Ok(Ok(())) => println!("\n上传完成"), // \nUpload complete
Ok(Err(e)) => eprintln!("\n上传失败: {:?}", e), // \nUpload failed: {:?}
Err(e) => eprintln!("\n任务 panic: {:?}", e), // \nTask panic: {:?}
}
}
_ = tokio::signal::ctrl_c() => {
eprintln!("\n收到 Ctrl+C, 取消 FoE 传输"); // \nCtrl+C received, FoE transfer cancelled
foe_cancel.cancel();
}
}

foe_cancel.clear_busy_hooks();

Notes​

  • Whether BUSY frames are pushed is up to the slave; some low-end slaves do not implement a BUSY phase, and the host stays "quiet" for a few seconds until the FoE ACK arrives
  • The cancel flag only affects the next iteration of the lower-layer main loop; the flash write the slave is currently executing is not interrupted
  • set_busy_hook() must be registered before upload() / download(), otherwise the first round of progress callbacks is lost
  • Some SDK versions may not support BUSY progress callbacks; the log then records "BUSY progress information will be unavailable", and other features are unaffected
  • In non-async scenarios you can run upload() on a separate thread and have the main thread call cancel() after monitoring user input; multiple FoEInstance handles share the same master/slave index and are thread-safe
Reference
  • ETG.1000.6 Table 93 — FoE BUSY frame fields (Done / Entire / BusyText)