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
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| File read | Download | byte[]? | read-only | Reads the entire file back from the slave; returns null on failure |
| File write | Upload | bool | write-only | Writes file contents to the slave |
| State switch | EnsureBootState | bool | write-only | Switches to the Bootstrap state; must be called before writing firmware |
| Transfer progress | ProgressChanged | EventHandler | read-only | Reports progress per packet during a transfer |
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol capability | IsSupported | bool | read-only | bool view of FoESupport == true: true only for "known to be supported", false when the conclusion is unknown |
| FoESupport | bool? | read-only | FoE capability tri-state: true = supported, false = SII was actually read and does not declare it, null = unknown | |
| IsSupportedKnown | bool | read-only | Whether the capability conclusion is known; false = unknown (not the same as unsupported) | |
| ProtocolType | byte | read-only | Mailbox protocol type code (FoE = 0x04) | |
| ProtocolName | string | read-only | Protocol name ("FoE") | |
| Default parameters | DefaultTimeoutMs | int | read/write | Default timeout in milliseconds, default 5000 (5 s) |
| DefaultTimeoutUs | int | read/write | Default timeout in microseconds, equal to DefaultTimeoutMs × 1000; a value set here is converted back to ms | |
| DefaultPassword | uint | read/write | Default password, default 0 | |
| Errors | LastErrorCode | FoEErrorCode? | read-only | Error code of the most recent FoE operation (FoEErrorCode enum); null on success or when nothing has started |
| State | LastStatus | MailboxStatus | read-only | Unified state of the most recent mailbox transaction (IMailboxProtocol, shared by all seven protocols) |
| Statistics | Statistics | MailboxStatistics | read-only | Mailbox transaction statistics snapshot; an empty snapshot (all 0) is returned when none is available |
| Limits | MaxDownloadSize | int | read-only | Maximum number of file bytes a single Download can read (65536, 64 KiB); constant |
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 downloadpassword(uint?) — FoE password (usesDefaultPasswordwhen not specified)timeoutMs(int?) — timeout in milliseconds (usesDefaultTimeoutMswhen not specified)enableCrc(bool) — enable CRC verification (data integrity is checked automatically)
Return value:
byte[]?— file content as a byte array;nullon 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 uploadfileData(byte[]) — file data to writepassword(uint?) — FoE password (usesDefaultPasswordwhen not specified)timeoutMs(int?) — timeout in milliseconds (usesDefaultTimeoutMswhen not specified)enableCrc(bool) — enable CRC verification (checksum information is appended automatically)
Return value:
bool—trueon 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—truewhen the slave is already in Boot or the switch succeeded;falsewhen the switch failed, withLastErrorCode = 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 indexPacketNumber(int) — packet sequence numberDataSize(int) — data size in bytesProgressPercent(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—trueon 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—trueon 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—trueon 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 bytesmailboxSize(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 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 slaveBusyEntire(int) — total bytes, as reported by the slaveBusyText(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();
}
Cancellation + BUSY combined (recommended)
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
ProgressChangedsubscription in place, theDownload/Uploadentry points register the progress hook automatically; a manualEnableProgressHookmust 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
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Default parameters | DefaultTimeoutMs | int | read/write | FoE default timeout in milliseconds, default 5000 |
| DefaultTimeoutUs | int | read/write | FoE default timeout in microseconds, derived from DefaultTimeoutMs * 1000. Setting it computes ms in reverse | |
| DefaultPassword | uint | read/write | FoE 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
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).
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
| Symptom | Cause | Handling |
|---|---|---|
| Download returns null and LastErrorCode is NotFound | The file name does not exist on the slave | Check the actual file name and its case in the slave file system, then retry |
| Upload fails and LastErrorCode is BootstrapOnly | The firmware area is writable only in the Bootstrap state | Call EnsureBootState first and run Upload after it succeeds |
| The transfer fails midway and the slave keeps returning BUSY | The slave is erasing or writing flash | Wait until BUSY ends, then retry with a larger timeoutMs |
| The operation times out | The file is large and a single transfer exceeds the default timeout | Retry with a larger timeoutMs |
| LastErrorCode is AccessDenied | The password does not match what the slave requires | Set DefaultPassword, or pass password explicitly on the call |