Skip to main content

FoE (File over EtherCAT)

FoE reads and writes files on a slave. Typical uses are firmware upgrades and uploading or downloading configuration files. Normal scanning and PDO control do not need it; it is only used when upgrading firmware or changing a device configuration file.

Accessed through slave.FoE. It is null when the slave does not support FoE.​

Method overview​

CategoryMethodTypeRead/writeDescription
File readDownloadbyte[]?read-onlyReads the entire file back from the slave; returns null on failure
File writeUploadboolwrite-onlyWrites file contents to the slave
State switchEnsureBootStateboolwrite-onlySwitches to the Bootstrap state; must be called before writing firmware
Transfer progressProgressChangedEventHandlerread-onlyReports progress per packet during a transfer

Properties​

CategoryPropertyTypeRead/writeDescription
Protocol capabilityIsSupportedboolread-onlybool view of FoESupport == true: true only for "known to be supported", false when the conclusion is unknown
FoESupportbool?read-onlyFoE capability tri-state: true = supported, false = SII was actually read and does not declare it, null = unknown
IsSupportedKnownboolread-onlyWhether the capability conclusion is known; false = unknown (not the same as unsupported)
ProtocolTypebyteread-onlyMailbox protocol type code (FoE = 0x04)
ProtocolNamestringread-onlyProtocol name ("FoE")
Default parametersDefaultTimeoutMsintread/writeDefault timeout in milliseconds, default 5000 (5 s)
DefaultTimeoutUsintread/writeDefault timeout in microseconds, equal to DefaultTimeoutMs × 1000; a value set here is converted back to ms
DefaultPassworduintread/writeDefault password, default 0
ErrorsLastErrorCodeFoEErrorCode?read-onlyError code of the most recent FoE operation (FoEErrorCode enum); null on success or when nothing has started
StateLastStatusMailboxStatusread-onlyUnified state of the most recent mailbox transaction (IMailboxProtocol, shared by all seven protocols)
StatisticsStatisticsMailboxStatisticsread-onlyMailbox transaction statistics snapshot; an empty snapshot (all 0) is returned when none is available
LimitsMaxDownloadSizeintread-onlyMaximum number of file bytes a single Download can read (65536, 64 KiB); constant
Capability tri-state and the unified interface

FoESupport returns bool?: true = supported, false = SII was actually read and does not declare FoE, null = unknown (could not be read). To tell "confirmed unsupported" from "unknown", check FoESupport / IsSupportedKnown rather than IsSupported alone. FoEInstance implements the unified IMailboxProtocol interface (all seven mailbox protocol instances share one contract, see Unified mailbox protocol interface): the interface's uint LastErrorCode and this class's FoEErrorCode? LastErrorCode come from the same source and are reached through IMailboxProtocol; for ResetStatistics() see "Mailbox statistics".

File transfer​

Download(string filename, uint? password = null, int? timeoutMs = null, bool enableCrc = false)​

public byte[]? Download(string filename, uint? password = null, int? timeoutMs = null, bool enableCrc = false)

Downloads (reads) a file from the slave device. One call reads at most MaxDownloadSize (64 KiB): the remote file size is unknown before the transfer starts, so when the limit is exceeded the call returns null and logs at Error level (truncated content is never returned); for larger files use the chunked or large-file read tool provided by the slave vendor.

Parameters:

  • filename (string) — name of the file to download
  • password (uint?) — FoE password (uses DefaultPassword when not specified)
  • timeoutMs (int?) — timeout in milliseconds (uses DefaultTimeoutMs when not specified)
  • enableCrc (bool) — enable CRC verification (data integrity is checked automatically)

Return value:

  • byte[]? — file content as a byte array; null on failure

Example:

// Basic download
byte[]? firmware = slave.FoE.Download("firmware.bin");

// Enable CRC verification
byte[]? config = slave.FoE.Download("config.xml", enableCrc: true);

Upload(string filename, byte[] fileData, uint? password = null, int? timeoutMs = null, bool enableCrc = false)​

public bool Upload(string filename, byte[] fileData, uint? password = null, int? timeoutMs = null, bool enableCrc = false)

Uploads (writes) a file to the slave device.

Parameters:

  • filename (string) — name of the file to upload
  • fileData (byte[]) — file data to write
  • password (uint?) — FoE password (uses DefaultPassword when not specified)
  • timeoutMs (int?) — timeout in milliseconds (uses DefaultTimeoutMs when not specified)
  • enableCrc (bool) — enable CRC verification (checksum information is appended automatically)

Return value:

  • bool — true on success

Example:

// Basic upload
byte[] newFirmware = File.ReadAllBytes("new_firmware.bin");
bool success = slave.FoE.Upload("firmware.bin", newFirmware);

// Enable CRC verification
bool ok = slave.FoE.Upload("firmware.bin", newFirmware, enableCrc: true);

EnsureBootState()​

public bool EnsureBootState()

Ensures the slave is in the Bootstrap (Boot) state. Transfers that write the bootloader area, such as firmware programming, must run in the Boot state; otherwise the slave returns BootstrapOnly. An ordinary configuration file only needs PreOp.

Return value:

  • bool — true when the slave is already in Boot or the switch succeeded; false when the switch failed, with LastErrorCode = BootstrapOnly

Progress events​

ProgressChanged​

public event EventHandler<FoEProgressEventArgs>? ProgressChanged;

FoE transfer progress event. Once subscribed, Download / Upload operations report progress automatically.

FoEProgressEventArgs​

Related structures:

  • Slave (ushort) — slave index
  • PacketNumber (int) — packet sequence number
  • DataSize (int) — data size in bytes
  • ProgressPercent (int) — estimated progress percentage (0-100)

Example:

slave.FoE.ProgressChanged += (sender, e) =>
{
Console.Write($"\r传输进度: {e.ProgressPercent}% (包 {e.PacketNumber})"); // \rTransfer progress: {e.ProgressPercent}% (packet {e.PacketNumber})
};

byte[] firmware = File.ReadAllBytes("new_firmware.bin");
bool success = slave.FoE.Upload("firmware.bin", firmware, enableCrc: true);
Console.WriteLine(success ? "\n上传完成!" : "\n上传失败!"); // \nUpload complete! / \nUpload failed!

Transfer progress​

EnableProgressHook(int estimatedTotalPackets = 0)​

public bool EnableProgressHook(int estimatedTotalPackets = 0)

Enables the FoE progress hook and sets the total packet estimate. Normally a ProgressChanged subscription is all that is needed: the Download / Upload entry points register the hook automatically and override the estimate (Upload estimates with EstimatePacketCount, Download passes 0).

Parameters:

  • estimatedTotalPackets (int) — estimated total packet count (used to compute the progress percentage; 0 = no estimate)

Return value:

  • bool — true on success

DisableProgressHook()​

public bool DisableProgressHook()

Disables the FoE progress hook and stops progress reporting. This is an instance-level operation: the master-level hook is removed only when this instance owns it.

Return value:

  • bool — true on success

ClearMasterProgressHook(ushort masterIndex)​

public static bool ClearMasterProgressHook(ushort masterIndex)

Releases the progress / BUSY hook on a master unconditionally. Difference from DisableProgressHook: that method is instance-level and acts only when the instance owns the hook. Call this before closing a master, hot-plugging a slave or replacing a slave, to clear leftover registrations.

Parameters:

  • masterIndex (ushort) — master index

Return value:

  • bool — true on success

EstimatePacketCount(int fileSize, int mailboxSize = 512)​

public int EstimatePacketCount(int fileSize, int mailboxSize = 512)

Estimates the number of packets a file transfer needs. Can be used for the EnableProgressHook parameter of estimatedTotalPackets.

Parameters:

  • fileSize (int) — file size in bytes
  • mailboxSize (int) — mailbox size in bytes, default 512

Return value:

  • int — estimated packet count

Example:

// Enable the progress callback
slave.FoE.ProgressChanged += (sender, e) =>
{
Console.Write($"\r传输进度: {e.ProgressPercent}% (包 {e.PacketNumber}, {e.DataSize} 字节)"); // \rTransfer progress: {e.ProgressPercent}% (packet {e.PacketNumber}, {e.DataSize} bytes)
};

byte[] firmware = File.ReadAllBytes("new_firmware.bin");
int packets = slave.FoE.EstimatePacketCount(firmware.Length);
slave.FoE.EnableProgressHook(packets);

bool success = slave.FoE.Upload("firmware.bin", firmware);
slave.FoE.DisableProgressHook();

Console.WriteLine(success ? "\n上传完成!" : "\n上传失败!"); // \nUpload complete! / \nUpload failed!

Error handling​

FoEInstance.GetErrorDescription(FoEErrorCode errorCode)​

public static string GetErrorDescription(FoEErrorCode errorCode)

Returns the Chinese description text for a FoE error code.

Parameters:

  • errorCode (FoEErrorCode) — FoE protocol error code

Return value:

  • string — Chinese description text

Related structures:

public enum FoEErrorCode : ushort
{
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:

byte[]? data = slave.FoE.Download("firmware.bin");
if (data == null)
{
string desc = DarraEtherCAT.Slave.FoEInstance.GetErrorDescription(DarraEtherCAT.Slave.FoEInstance.FoEErrorCode.NotFound);
Console.WriteLine($"下载失败: {desc}"); // Download failed: {desc}
}

LastErrorCode​

public FoEErrorCode? LastErrorCode { get; }

Error code of the most recent FoE operation (ETG.1000.6 Table 92). The Download / Upload entry points reset it first and leave it null on success; on failure the error code is mapped into this property (for example NotFound / AccessDenied / BootstrapOnly; failures that cannot be classified are recorded as NotDefined). Combine it with the return value (null / false) to determine the concrete cause.

Example:

byte[]? data = slave.FoE.Download("firmware.bin");
if (data == null && slave.FoE.LastErrorCode is DarraEtherCAT.Slave.FoEInstance.FoEErrorCode err)
{
Console.WriteLine($"下载失败: {DarraEtherCAT.Slave.FoEInstance.GetErrorDescription(err)}"); // Download failed: {DarraEtherCAT.Slave.FoEInstance.GetErrorDescription(err)}
}

Mailbox statistics​

FoEInstance implements the unified IMailboxProtocol interface, which provides statistics and state views for this slave's FoE mailbox transactions. Statistics (the "Statistics" row of the property table) returns the current snapshot on every read; when the statistics interface is unavailable it returns an empty snapshot (all 0, LastErrorTime is null), and that must not be read as "no traffic". Full definitions of MailboxStatus / MailboxStatistics are in CoE · MailboxStatus enum and CoE · Statistics / ResetStatistics(); all seven mailbox protocols share one set.

ResetStatistics()​

public void ResetStatistics()

Resets the mailbox statistics counters of this instance. On success LastStatus returns to Pending; when the reset fails (runtime unavailable, for example) the counters are not cleared, LastStatus becomes MailboxError and an Error log entry is written. Throws ObjectDisposedException when the slave instance has already been released.

Example:

slave.FoE.Upload("firmware.bin", firmware);

MailboxStatistics stats = slave.FoE.Statistics;
Console.WriteLine($"FoE 邮箱: 发送={stats.TotalSent}, 超时={stats.TotalTimeout}, 错误={stats.TotalMailboxError}"); // FoE mailbox: sent={stats.TotalSent}, timeouts={stats.TotalTimeout}, errors={stats.TotalMailboxError}

slave.FoE.ResetStatistics(); // Reset and start collecting again

Cancelling transfers and the BUSY hook​

A firmware upgrade or a large configuration transfer often runs for tens of seconds or even minutes. Two useful capabilities:

  • Cancel midway — 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 (CancellationToken)​

Cancel through the DownloadAsync parameter of UploadAsync / cancellationToken; when it fires, the Task<T> throws OperationCanceledException.

Signatures:

public Task<byte[]?> DownloadAsync(string filename, uint? password = null, int? timeoutMs = null,
bool enableCrc = false, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
public Task<bool> UploadAsync(string filename, byte[] fileData, uint? password = null, int? timeoutMs = null,
bool enableCrc = false, IProgress<int>? progress = null, CancellationToken cancellationToken = default)
Firmware upgrade caveat

Firmware programming commands may already have been sent to the slave in part; after cancelling, send the complete firmware again.

Example — download with cancellation:

var cts = new CancellationTokenSource();

// Start an asynchronous download (non-blocking)
var progress = new Progress<int>(p => Console.Write($"\r进度: {p}%")); // \rProgress: {p}%
var task = slave.FoE.DownloadAsync(
"firmware.bin",
progress: progress,
cancellationToken: cts.Token);

// User presses the "Cancel" button:
// cts.Cancel();

try
{
byte[]? data = await task;
Console.WriteLine(data != null ? "\n下载完成" : "\n下载失败"); // \nDownload complete / \nDownload failed
}
catch (OperationCanceledException)
{
Console.WriteLine("\n用户取消传输"); // \nTransfer cancelled by user
}

Example — upload (firmware upgrade) with cancellation:

var cts = new CancellationTokenSource();
byte[] firmware = File.ReadAllBytes("fw.bin");

var progress = new Progress<int>(p => Console.Write($"\r烧写: {p}%")); // \rFlashing: {p}%
var task = slave.FoE.UploadAsync(
"firmware.bin",
firmware,
enableCrc: true,
progress: progress,
cancellationToken: cts.Token);

// User cancels midway:
// cts.Cancel();

try
{
bool ok = await task;
Console.WriteLine(ok ? "\n固件烧写成功" : "\n固件烧写失败"); // \nFirmware flash succeeded / \nFirmware flash failed
}
catch (OperationCanceledException)
{
Console.WriteLine("\n已取消; 固件可能已部分写入, 需重新升级"); // \nCancelled; the firmware may be partially written, re-run the upgrade
}

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 the same ProgressChanged event; the BUSY-related fields are extended properties on FoEProgressEventArgs:

  • BusyDone (int) — bytes already done, as reported by the slave
  • BusyEntire (int) — total bytes, as reported by the slave
  • BusyText (string) — status text reported by the slave (for example "Erasing flash..." / "Programming sector 3/8")

When BusyEntire > 0, the current progress comes from BUSY frames (otherwise it is packet-count progress from the DATA phase). EnableProgressHook() registers both the DATA and BUSY callbacks, so no extra API is needed.

Example — firmware upgrade progress bar (with BUSY programming display):

if (slave.FoE == null) return;

slave.FoE.ProgressChanged += (sender, e) =>
{
if (e.BusyEntire > 0)
{
// BUSY phase: the slave is erasing or writing flash
double pct = 100.0 * e.BusyDone / e.BusyEntire;
Console.Write(
$"\r[烧写中] {pct:F1}% ({e.BusyDone}/{e.BusyEntire}) {e.BusyText} "); // \r[Flashing] {pct:F1}% ({e.BusyDone}/{e.BusyEntire}) {e.BusyText}
}
else
{
// DATA phase: the master is pushing file data
Console.Write($"\r[传输中] {e.ProgressPercent}% (包 {e.PacketNumber}, {e.DataSize}B) "); // \r[Transferring] {e.ProgressPercent}% (packet {e.PacketNumber}, {e.DataSize}B)
}
};

byte[] firmware = File.ReadAllBytes("fw.bin");
int packets = slave.FoE.EstimatePacketCount(firmware.Length);
slave.FoE.EnableProgressHook(packets);

try
{
bool ok = slave.FoE.Upload("firmware.bin", firmware, enableCrc: true);
Console.WriteLine(ok ? "\n烧写完成" : "\n烧写失败"); // \nFlash complete / \nFlash failed
}
finally
{
slave.FoE.DisableProgressHook();
}

The practical combination for a firmware upgrade: asynchronous call + progress bar + BUSY hook + user cancellation. The user sees real programming progress and can cancel when a sector stalls for a long time, instead of waiting indefinitely.

var cts = new CancellationTokenSource();

slave.FoE.ProgressChanged += (s, e) =>
{
if (e.BusyEntire > 0)
Console.Write($"\r烧写 {100.0 * e.BusyDone / e.BusyEntire:F1}% {e.BusyText} "); // \rFlashing {100.0 * e.BusyDone / e.BusyEntire:F1}% {e.BusyText}
else
Console.Write($"\r传输 {e.ProgressPercent}% "); // \rTransfer {e.ProgressPercent}%
};

int packets = slave.FoE.EstimatePacketCount(firmware.Length);
slave.FoE.EnableProgressHook(packets);

var task = slave.FoE.UploadAsync(
"firmware.bin", firmware, enableCrc: true,
cancellationToken: cts.Token);

// Timeout fallback: auto-cancel when a single sector stalls for more than 30 s
_ = Task.Delay(TimeSpan.FromSeconds(30), cts.Token).ContinueWith(_ =>
{
if (!task.IsCompleted) cts.Cancel();
}, TaskScheduler.Default);

try { await task; }
catch (OperationCanceledException) { Console.WriteLine("\n已取消"); } // \nCancelled
finally { slave.FoE.DisableProgressHook(); }

Notes​

  • Whether BUSY frames are sent is up to the slave; some low-end slaves do not implement the BUSY phase, and the host stays silent for a few seconds until the FoE ACK arrives
  • A cancel request takes effect on the next processing cycle; the flash write the slave is currently executing is not interrupted
  • With a ProgressChanged subscription in place, the Download / Upload entry points register the progress hook automatically; a manual EnableProgressHook must be called before the transfer starts, otherwise the first round of progress callbacks is lost
  • When the runtime does not support BUSY progress callbacks, the log records "BUSY progress information will be unavailable"; other functions are unaffected

Default parameters​

CategoryPropertyTypeRead/writeDescription
Default parametersDefaultTimeoutMsintread/writeFoE default timeout in milliseconds, default 5000
DefaultTimeoutUsintread/writeFoE default timeout in microseconds, derived from DefaultTimeoutMs * 1000. Setting it computes ms in reverse
DefaultPassworduintread/writeFoE default password, default 0. Used as a fallback when Download / Upload is called without a password
public int DefaultTimeoutMs { get; set; } = 5000;
public int DefaultTimeoutUs { get; set; } // = DefaultTimeoutMs * 1000
public uint DefaultPassword { get; set; } = 0;

Example:

slave.FoE.DefaultTimeoutMs = 10000;
slave.FoE.DefaultPassword = 0xCAFE0001;
byte[]? data = slave.FoE.Download("firmware.bin"); // Uses the default timeout and default password

Cancelling a transfer​

Cancel()​

public bool Cancel()

Requests cancellation of the current FoE download or upload transaction. Can be called from any thread (equivalent to CancellationToken, but without async). The cancel request takes effect on the next processing cycle, and Download / Upload then return early.

Return value:

  • bool — true = request accepted; false = the runtime does not support cancellation or the call failed
warning

Interrupting firmware programming can leave the slave flash partially written; upload the complete firmware again.

Example:

var task = Task.Run(() => slave.FoE.Upload("firmware.bin", data));
await Task.Delay(2000);
slave.FoE.Cancel(); // Any thread; no cancellationToken required

ClearCancel()​

public bool ClearCancel()

Clears the cancel flag so that a new FoE transaction can start. The Download / Upload entry points clear it automatically; call this only for an abnormal reset or an external manual operation.

Return value:

  • bool — true = cleared successfully

BUSY frame events​

BusyReceived​

public event EventHandler<FoEBusyEventArgs>? BusyReceived;

Raised when the slave returns BUSY frames (reported periodically while firmware flash is being programmed). Same source as ProgressChanged.BusyDone/BusyEntire/BusyText; use either one. The BUSY hook is registered automatically on the first subscription and unregistered when the last subscriber unsubscribes (unless ProgressChanged still holds the hook).

note

The callback does not run on the UI thread; the UI should use Invoke to get back to the main thread.

Related structures:

public sealed class FoEBusyEventArgs : EventArgs
{
public ushort SlaveIndex { get; init; }
public ushort Done { get; init; } // bytes done
public ushort Entire { get; init; } // total bytes
public string Text { get; init; } // slave text
public int RetryIndex { get; init; } // retry index
public double Percent { get; } // = Entire > 0 ? 100.0 * Done / Entire : 0
}

Example:

slave.FoE.BusyReceived += (s, e) =>
{
Console.WriteLine($"[BUSY] {e.Done}/{e.Entire} ({e.Percent:F1}%) {e.Text}");
};

byte[] fw = File.ReadAllBytes("firmware.bin");
slave.FoE.Upload("firmware.bin", fw);

Full example​

Firmware upgrade​

if (slave.FoE != null)
{
// Transfer progress
slave.FoE.ProgressChanged += (sender, e) =>
Console.Write($"\r进度 {e.ProgressPercent}% (包 {e.PacketNumber})"); // \rProgress {e.ProgressPercent}% (packet {e.PacketNumber})

// Read back the current firmware and save it
byte[]? firmware = slave.FoE.Download("firmware.bin");
if (firmware == null)
{
Console.WriteLine($"\n读取失败: {slave.FoE.LastErrorCode}"); // \nRead failed: {slave.FoE.LastErrorCode}
return;
}

File.WriteAllBytes("firmware_backup.bin", firmware);
Console.WriteLine($"\n已备份 {firmware.Length} 字节"); // \nBacked up {firmware.Length} bytes

// Write the new firmware: the firmware area requires the Bootstrap state
if (!slave.FoE.EnsureBootState())
{
Console.WriteLine("切换 Bootstrap 失败"); // Failed to switch to Bootstrap
return;
}

byte[] newFirmware = File.ReadAllBytes("new_firmware.bin");
bool ok = slave.FoE.Upload("firmware.bin", newFirmware, enableCrc: true);
Console.WriteLine(ok ? "写入成功" : "写入失败"); // write succeeded / write failed
}

Configuration file transfer​

if (slave.FoE != null)
{
slave.FoE.DefaultPassword = 0x12345678;
slave.FoE.DefaultTimeoutMs = 10000; // 10 s

// Read the configuration
byte[]? config = slave.FoE.Download("config.xml");
if (config != null)
{
string xmlContent = System.Text.Encoding.UTF8.GetString(config);
Console.WriteLine($"配置内容:\n{xmlContent}"); // Configuration content:\n{xmlContent}
}

// Write the new configuration
string newConfig = "<Config><Param1>100</Param1></Config>";
byte[] configBytes = System.Text.Encoding.UTF8.GetBytes(newConfig);
slave.FoE.Upload("config.xml", configBytes);
}

Failures and handling​

SymptomCauseHandling
Download returns null and LastErrorCode is NotFoundThe file name does not exist on the slaveCheck the actual file name and its case in the slave file system, then retry
Upload fails and LastErrorCode is BootstrapOnlyThe firmware area is writable only in the Bootstrap stateCall EnsureBootState first and run Upload after it succeeds
The transfer fails midway and the slave keeps returning BUSYThe slave is erasing or writing flashWait until BUSY ends, then retry with a larger timeoutMs
The operation times outThe file is large and a single transfer exceeds the default timeoutRetry with a larger timeoutMs
LastErrorCode is AccessDeniedThe password does not match what the slave requiresSet DefaultPassword, or pass password explicitly on the call