Skip to main content

FoE (File over EtherCAT)

The FoE protocol performs file transfer with EtherCAT slaves. It covers firmware updates, configuration file upload and download, and similar scenarios.

Accessed through slave.foe(). The sub-object is created lazily and always returns an instance (never null); check whether the slave supports FoE with slave.foe().isSupported(), and treat an unknown capability as unsupported. A transfer can carry a password and a CRC32 check, and a progress callback can report the progress of every packet.​

Honest boundaries​

  • Read buffer / file size: download lets the underlying layer allocate the buffer and return the data according to file_size; 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 FoE Error 0x00008001, not an ACK. Do not describe a WRQ failure as an ACK

Capability query​

isSupported() / supportsFoE() / supportState() / isSupportKnown()​

public boolean  isSupported()
public Boolean supportsFoE()
public Boolean supportState()
public boolean isSupportKnown()

Whether the slave supports FoE. The four entry points share one capability conclusion; they differ only in how "unknown" is expressed.

MethodTypeSemantics
isSupported()booleanReturns true only when support is confirmed; an unknown capability returns false (no support is claimed without evidence)
supportsFoE()BooleanTri-state: TRUE supported, FALSE confirmed unsupported, null unknown
supportState()BooleanUnified entry point of IMailboxProtocol; same source and same conclusion as supportsFoE()
isSupportKnown()booleanWhether the conclusion is known; false means unknown, which is not the same as unsupported

Example:

FoE foe = slave.foe();

if (!foe.isSupportKnown()) {
System.out.println("FoE 能力未知(读不到从站能力信息),先按不支持处理"); // FoE capability unknown (slave capability info could not be read), treat as unsupported for now
} else if (foe.supportsFoE() == Boolean.FALSE) {
System.out.println("从站确认不支持 FoE"); // Slave confirms FoE is not supported
}

The slave level also offers the same-source entry points slave.supportsFoE() / slave.foeSupportState() (see Slave API).

Properties​

CategoryPropertyTypeRead/writeDescription
Default parametersdefaultTimeoutMs() / defaultTimeoutMs(int)intread/writeDefault timeout (milliseconds), default 5000 (5 seconds)
defaultPassword() / defaultPassword(int)intread/writeDefault password, default 0

Calls that do not pass password / timeoutMs explicitly use these two values. The properties are read and written through overloaded methods: a call without arguments reads, a call with an argument writes. A write is stored only in this instance and performs no range check; values passed explicitly to download / upload take precedence.

File transfer​

download(String filename, Integer password, Integer timeoutMs)​

public byte[] download(String filename)
public byte[] download(String filename, Integer password, Integer timeoutMs)
public byte[] download(String filename, Integer password, Integer timeoutMs, boolean enableCrc)

Downloads (reads) a file from the slave device. The SDK allocates the buffer according to the actual file size and returns the complete content; it is not a fixed-size buffer supplied by the caller.

Parameters:

  • filename (String) — file name on the slave; null or an empty string is treated as a failure straight away
  • password (Integer) — FoE password (uses defaultPassword() when omitted)
  • timeoutMs (Integer) — timeout (milliseconds, uses defaultTimeoutMs() when omitted)
  • enableCrc (boolean) — whether to enable the CRC32 check; overloads without this parameter do not check by default

Returns:

  • byte[] — file content byte array; an empty file returns byte[0], a failure returns null

On failure: when null is returned, get the reason from getLastError() / getLastErrorCode() / getLastStatus() (see Error handling).

Example:

FoE foe = slave.foe();
byte[] data = foe.download("firmware.bin"); // default password / timeout
byte[] data2 = foe.download("firmware.bin", 0x1234, 10000); // explicit password and timeout
byte[] data3 = foe.downloadWithCrc("firmware.bin"); // with CRC32 check

upload(String filename, byte[] fileData, Integer password, Integer timeoutMs, boolean enableCrc)​

public boolean upload(String filename, byte[] fileData)
public boolean upload(String filename, byte[] fileData, Integer password, Integer timeoutMs)
public boolean upload(String filename, byte[] fileData, Integer password, Integer timeoutMs, boolean enableCrc)

Uploads (writes) a file to the slave device.

Parameters:

  • filename (String) — file name to upload; null or an empty string is treated as a failure straight away
  • fileData (byte[]) — file data to write; null or an empty array is treated as a failure straight away, and an empty file cannot be uploaded
  • password (Integer) — FoE password (uses defaultPassword() when omitted)
  • timeoutMs (Integer) — timeout (milliseconds, uses defaultTimeoutMs() when omitted)
  • enableCrc (boolean) — enables the CRC32 check (the checksum information is appended automatically); overloads without this parameter do not check by default

Returns:

  • boolean — true on success, otherwise false (again use getLastError() / getLastErrorCode() / getLastStatus() to get the reason)

Example:

FoE foe = slave.foe();
byte[] fileData = Files.readAllBytes(Path.of("firmware.bin"));
boolean ok = foe.upload("firmware.bin", fileData);
boolean ok2 = foe.upload("firmware.bin", fileData, 0x1234, 10000, true);

CRC overloads​

public byte[]  downloadWithCrc(String filename)
public byte[] downloadWithCrc(String filename, Integer password, Integer timeoutMs)
public boolean uploadWithCrc(String filename, byte[] fileData)
public boolean uploadWithCrc(String filename, byte[] fileData, Integer password, Integer timeoutMs)

The *WithCrc methods are wrappers that enable the CRC32 check, equivalent to download/upload(..., enableCrc=true).

Asynchronous transfer​

public CompletableFuture<byte[]>  downloadAsync(String filename)
public CompletableFuture<byte[]> downloadAsync(String filename, Integer password, Integer timeoutMs)
public CompletableFuture<Boolean> uploadAsync(String filename, byte[] fileData)
public CompletableFuture<Boolean> uploadAsync(String filename, byte[] fileData, Integer password, Integer timeoutMs)

Asynchronous download/upload. The task runs on the common thread pool (a subclass can override defaultExecutor() to change the pool) and does not block the calling thread. When a transfer fails, the returned CompletableFuture completes exceptionally with FoEProtocolException, which is obtained with ex.getCause(). Cancelling the future calls cancel() as well, so the transfer exits on its next iteration.

Cancelling a firmware flash asynchronously

Cancelling a firmware flash midway can leave Flash partially written, and the complete firmware must be uploaded again.

Example:

FoE foe = slave.foe();
byte[] firmware = Files.readAllBytes(Path.of("firmware.bin"));

CompletableFuture<Boolean> task = foe.uploadAsync("firmware.bin", firmware);
task.thenAccept(ok -> System.out.println("上传完成: " + ok)) // Upload complete:
.exceptionally(ex -> {
if (ex.getCause() instanceof FoE.FoEProtocolException) {
FoE.FoEProtocolException fe = (FoE.FoEProtocolException) ex.getCause();
System.err.println("FoE 失败: " + FoE.getErrorDescription(fe.errorCode)); // FoE failed:
}
return null;
});

Transfer progress​

ProgressCallback interface​

@FunctionalInterface
public interface ProgressCallback {
void onProgress(short slave, int packetNumber, int dataSize, int progressPercent);
}

FoE transfer progress callback interface (a functional interface, so lambda expressions are supported).

Callback parameters:

  • slave (short) — slave index
  • packetNumber (int) — current packet number (starting at 1 and increasing)
  • dataSize (int) — data size of the current packet (bytes)
  • progressPercent (int) — estimated progress percentage (0-100); it is meaningful only when the total packet count is supplied through estimatePacketCount

Percentage rules: when the total packet count is greater than 0, the value is computed as packet number × 100 / estimated total packets and capped at 100; when the total packet count is 0, no total is estimated and the value is capped at 99 by packet number, so 100 is never reported early.

Thread contract: it is invoked on the transfer callback thread; do not perform blocking or long-running I/O inside it. An exception thrown by the callback does not interrupt the transfer; it is logged and then swallowed.

enableProgressHook(ProgressCallback callback, int estimatedTotalPackets)​

public void enableProgressHook(ProgressCallback callback, int estimatedTotalPackets)

Enables the FoE progress callback. Once enabled, download / upload operations report transfer progress automatically through the callback.

Parameters:

  • callback (ProgressCallback) — progress callback function; passing null is equivalent to disableProgressHook()
  • estimatedTotalPackets (int) — estimated total packet count (used to compute the progressPercent percentage and obtainable from estimatePacketCount); 0 means no total is estimated

Registration constraints: the progress callback has a single slot per master; a later registration on the same master overwrites the registration of the previous instance.

Throws:

  • IllegalArgumentException — estimatedTotalPackets is negative
  • IllegalStateException — registration is rejected (the runtime library returned a failure)
  • UnsupportedOperationException — the current runtime library does not have this capability

disableProgressHook()​

public void disableProgressHook()

Disables the FoE progress callback and clears the registered callback function. Call this method after a transfer completes to release the callback reference; it is safe to call even when no callback has been registered.

estimatePacketCount(int fileSize, int mailboxSize)​

public int estimatePacketCount(int fileSize)
public int estimatePacketCount(int fileSize, int mailboxSize)

Estimates the number of packets required for a file transfer. The formula is ceil(fileSize / (mailboxSize - 6)), where the 6 bytes are the FoE protocol header overhead.

Parameters:

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

Returns:

  • int — estimated packet count; returns 0 when fileSize <= 0 or mailboxSize <= 0. When mailboxSize is smaller than 6 bytes (the protocol header fills the mailbox), the estimate uses 128 bytes per packet rather than returning 0

Example:

FoE foe = slave.foe();
byte[] fileData = Files.readAllBytes(Path.of("firmware.bin"));

// Estimate the packet count
int packets = foe.estimatePacketCount(fileData.length);
System.out.println("预计传输 " + packets + " 个数据包"); // Expecting to transfer {packets} packets

// Enable the progress callback (lambda expression)
foe.enableProgressHook((slaveNo, packetNum, dataSize, percent) -> {
// Show the progress percentage and current packet information
System.out.printf("\r传输进度: %d%% (包 %d/%d, 本包 %d 字节)", // Transfer progress: %d%% (packet %d/%d, %d bytes in this packet)
percent, packetNum, packets, dataSize);
}, packets);

// Perform the upload
boolean ok = foe.upload("firmware.bin", fileData);

// Disable the progress callback after the transfer completes
foe.disableProgressHook();
System.out.println(ok ? "\n上传完成!" : "\n上传失败!"); // Upload complete! / upload failed!

Complete progress callback flow​

FoE foe = slave.foe();
foe.defaultTimeoutMs(30000); // use a longer timeout for large file transfers

byte[] firmware = Files.readAllBytes(Path.of("new_firmware.bin"));

// 1. Estimate the total packet count
int totalPackets = foe.estimatePacketCount(firmware.length);

// 2. Register the progress callback
foe.enableProgressHook((slaveNo, packetNum, dataSize, percent) -> {
// build a progress bar
int barLen = 30;
int filled = barLen * percent / 100;
StringBuilder bar = new StringBuilder("[");
for (int i = 0; i < barLen; i++)
bar.append(i < filled ? "#" : "-");
bar.append("]");
System.out.printf("\r%s %d%% (包 %d/%d)", bar, percent, packetNum, totalPackets);
}, totalPackets);

// 3. Perform the firmware upload (with CRC check)
boolean success = foe.upload("firmware.bin", firmware, null, null, true);

// 4. Clean up the callback
foe.disableProgressHook();

if (success) {
System.out.println("\n固件更新成功"); // Firmware update succeeded
} else {
// check the failure reason
FoEErrorCode error = foe.getLastError();
System.out.println("\n固件更新失败: " + FoE.getErrorDescription(error)); // Firmware update failed:
}

Cancelling transfers​

The user side can request cancellation while a transfer is in progress; the SDK layer exits on the next iteration of the transfer main loop. Typical uses: the user clicks the "Cancel" button, the watchdog expires, or the host machine shuts down.

cancel()​

public boolean cancel()

Requests cancellation of the current FoE transfer. The SDK exits on the next iteration of the transfer main loop.

Returns:

  • boolean — true means the SDK has accepted the cancellation request

clearCancel()​

public boolean clearCancel()

Clears the FoE cancellation flag. Normally the download / upload entry points clear it automatically; call it only on the exceptional manual-reset path.

Returns:

  • boolean — true means the flag was cleared

Example (asynchronous CompletableFuture combined with cancel):

FoE foe = slave.foe();

// Start the asynchronous upload
byte[] firmware = Files.readAllBytes(Path.of("firmware.bin"));
CompletableFuture<Boolean> task = CompletableFuture.supplyAsync(
() -> foe.upload("firmware.bin", firmware));

// When the user clicks the cancel button
cancelButton.addActionListener(e -> {
if (foe.cancel()) {
System.out.println("已请求取消, 等待传输退出..."); // Cancellation requested, waiting for the transfer to exit...
}
});

// Wait for the task to finish (success, failure or cancellation)
boolean ok = task.get();
if (!ok) {
FoEErrorCode err = foe.getLastError();
System.out.println("上传失败/取消: " + FoE.getErrorDescription(err)); // Upload failed/cancelled:
}
cancel() is request-based

cancel() only sets the cancellation flag; it does not interrupt the transfer immediately. The actual exit point depends on whether the current frame has already entered the NIC send queue. The caller should get() the future and wait until the task really returns.

BUSY progress callback​

The FoE protocol (ETG.1000.6 Table 93) lets a slave return BUSY frames while flashing, reporting the completed amount / total amount / optional text. After a listener is registered with setBusyHook, the host machine can refresh the progress bar each time a BUSY frame arrives.

BUSY vs ProgressCallback
  • enableProgressHook — local progress estimate based on the packet number; it does not depend on slave reports and works with any FoE slave
  • setBusyHook — based on the Done/Entire values actually reported by the slave; it is more accurate but requires the slave to implement BUSY frames (most firmware-flashing devices do)

Both can be enabled at the same time and complement each other.

setBusyHook(FoEBusyListener listener)​

public void setBusyHook(FoEBusyListener listener)

Sets the FoE BUSY callback. Passing null disables it.

Parameters:

  • listener (FoEBusyListener) — BUSY listener; null clears the hook

Registration constraints: one listener per instance, and setting it again overwrites the previous one. When the current runtime library does not have this capability, setBusyHook neither throws nor returns an error, it only writes a log entry — whether BUSY callbacks arrive depends on actual runtime behavior.

FoEBusyListener interface​

@FunctionalInterface
public interface FoEBusyListener {
void onBusy(FoEBusyEventArgs args);
}

FoEBusyEventArgs​

public static class FoEBusyEventArgs {
public short Slave; // slave index
public int Done; // completed amount reported by the slave
public int Entire; // total amount reported by the slave
public String Text; // optional BusyText (may be empty)
public int RetryIdx; // retry index
}

Done / Entire are the amounts reported by the slave as 16-bit values (0-65535); when Text is absent it is an empty string, not null. The callback is triggered on the FoE callback thread; do not block. An exception in a single callback does not interrupt the transfer.

Example:

FoE foe = slave.foe();

// Register the BUSY callback: compute the percentage from the Done/Entire values actually reported by the slave
foe.setBusyHook(args -> {
double percent = args.Entire > 0
? 100.0 * args.Done / args.Entire
: 0.0;
String text = (args.Text == null || args.Text.isEmpty())
? "烧写中..." : args.Text; // Flashing...
System.out.printf("\r[BUSY] %.1f%% (%d/%d, retry=%d) %s",
percent, args.Done, args.Entire, args.RetryIdx, text);
});

// asynchronous upload
byte[] firmware = Files.readAllBytes(Path.of("firmware.bin"));
CompletableFuture<Boolean> task = CompletableFuture.supplyAsync(
() -> foe.upload("firmware.bin", firmware));

// user cancel button
if (userWantsCancel) {
foe.cancel();
}

boolean ok = task.get();
foe.setBusyHook(null); // clean up the callback
System.out.println(ok ? "\n上传完成" : "\n上传失败/取消"); // Upload complete / upload failed/cancelled
Event field naming

The event fields of FoEBusyListener use PascalCase (Slave / Done / Entire / Text / RetryIdx).

Error handling​

The FoE protocol defines the error codes FoEErrorCode, used to diagnose transfer failures:

Enum valueValueDescription
NOT_DEFINED0x8000Undefined error
NOT_FOUND0x8001File not found
ACCESS_DENIED0x8002Access denied
DISK_FULL0x8003Disk full
ILLEGAL0x8004Illegal operation
PACKET_NUMBER_WRONG0x8005Wrong packet number
ALREADY_EXISTS0x8006File already exists
NO_USER0x8007No such user
BOOTSTRAP_ONLY0x8008Only available in Bootstrap mode
NOT_BOOTSTRAP0x8009Not in Bootstrap mode
NO_RIGHTS0x800AInsufficient rights
PROGRAM_ERROR0x800BProgram error

Use errorCode.getValue() (int) to get the numeric value and FoEErrorCode.fromValue(int) to look it up by number; an unknown number returns NOT_DEFINED.

getErrorDescription(FoEErrorCode errorCode)​

public static String getErrorDescription(FoEErrorCode errorCode)

Gets the Chinese description text for a FoE error code. When errorCode is null it returns unknown error; a value not covered by the enum returns unknown error (0xNNNN).

getLastError() / getLastErrorCode() / getLastStatus()​

public FoEErrorCode  getLastError()
public long getLastErrorCode()
public MailboxStatus getLastStatus()

The three-part status of the most recent operation; it is reset at the start of every download / upload call.

MethodTypeSemantics
getLastError()FoEErrorCodeFoE error code of the most recent failure; it stays NOT_DEFINED on success, or when the failure has no dedicated error code (for example a timeout)
getLastErrorCode()longMost recent protocol-layer error code; 0 = no error, and a failure is always other than 0
getLastStatus()MailboxStatusStatus of the most recent mailbox transaction, used to tell a timeout / an invalid argument / a mailbox error apart

The MailboxStatus values and the MailboxStatistics field table are in CoE · MailboxStatus enum and CoE · Mailbox statistics; the seven mailbox protocols share the same set. The values commonly seen on the FoE path are SUCCESS / TIMEOUT / MAILBOX_ERROR / INVALID_ARG.

Example:

FoE foe = slave.foe();
byte[] data = foe.download("firmware.bin");
if (data == null) {
FoEErrorCode error = foe.getLastError();
String desc = FoE.getErrorDescription(error);
System.out.println("下载失败: " + desc); // Download failed:
}

FoEProtocolException​

public static class FoEProtocolException extends RuntimeException {
public final FoEErrorCode errorCode; // FoE error code
}

Thrown by downloadAsync / uploadAsync on failure (carrying the last FoE error code). The asynchronous future completes with this exception and it can be obtained through ex.getCause(); the message also carries error=<枚举名>.

errorCode is taken from getLastError() at the moment of failure: a failure such as a timeout, which has no dedicated FoE error code, carries NOT_DEFINED, in which case use getLastStatus() / getLastErrorCode() to tell the causes apart (the same applies when a synchronous method returns null / false).

Mailbox statistics​

FoE implements the unified IMailboxProtocol interface. As of 2.5.x, getStatistics() / resetStatistics() return real statistics (earlier versions returned an empty placeholder snapshot).

CategoryMethodTypeRead/writeDescription
Protocol identificationgetProtocolType()byteread-onlyProtocol type constant (FoE=0x04)
getProtocolName()Stringread-onlyProtocol name ("FoE")
isSupported()booleanread-onlyWhether the slave supports this protocol; returns false when the capability is unknown (fail-closed)
supportState()Booleanread-onlyCapability tri-state: TRUE=supported, FALSE=confirmed unsupported, null=unknown; same source as supportsFoE()
isSupportKnown()booleanread-onlyWhether the capability conclusion is known (supportState() != null)
Transaction statusgetLastStatus()MailboxStatusread-onlyUnified status of the most recent mailbox transaction
getLastErrorCode()longread-onlyMost recent protocol-layer error code (0=no error)
StatisticsgetStatistics()MailboxStatisticsread-onlyMailbox statistics snapshot
resetStatistics()voidwrite-onlyResets the mailbox statistics counters

getStatistics() returns a statistics snapshot of this slave FoE mailbox transactions, and a snapshot of all 0s when statistics are unavailable; besides resetting the counters, resetStatistics() also clears the most recent status and error code back to their initial values. The MailboxStatistics field table is in CoE · Mailbox statistics.

Example:

FoE foe = slave.foe();
foe.upload("firmware.bin", firmware);

MailboxStatistics stats = foe.getStatistics();
System.out.printf("FoE 邮箱: 发送=%d, 超时=%d, 错误=%d%n", // FoE mailbox: sent=%d, timeouts=%d, errors=%d%n
stats.totalSent, stats.totalTimeout, stats.totalMailboxError);

Full example​

FoE foe = slave.foe();
foe.defaultTimeoutMs(10000);

// Back up the firmware
byte[] backup = foe.download("firmware.bin");
if (backup != null)
Files.write(Path.of("backup.bin"), backup);

// Upload the new firmware
byte[] newFirmware = Files.readAllBytes(Path.of("new_firmware.bin"));
boolean ok = foe.upload("firmware.bin", newFirmware);
System.out.println(ok ? "更新成功" : "更新失败"); // Update succeeded / update failed

Failures and handling​

SymptomCauseHandling
A transfer produces no result for a long time and the slave keeps returning BUSYThe slave is flashing and has not given its final confirmation yetWait for flashing to finish and do not start upload again
Transfer timeoutThe file is large, the mailbox is congested, or the default timeout is too shortIncrease defaultTimeoutMs, or pass timeoutMs explicitly on the call
The error code says the file was not foundThe file name does not exist on the slaveCheck the file name and its case; if necessary, confirm with download first
The error code says no such user or insufficient rightsThe FoE password is wrongRetry with the password configured on the slave
download returns null / upload returns falseThe transfer failed, or an argument is invalidCheck getLastStatus() first: INVALID_ARG is an argument problem (empty file name, uploading empty data), TIMEOUT is a timeout, and otherwise check getLastError()
The asynchronous future throws FoEProtocolExceptionThe asynchronous transfer failedGet the exception with ex.getCause() and read errorCode; when it carries NOT_DEFINED, check getLastStatus() as well
The result after cancelling is unknowncancel() is request-based and the transfer exits only laterWait until the future or upload really returns before deciding, and do not start the upload again
isSupported() returns false even though the device actually supports itThe capability could not be read and was folded into falseUse supportsFoE() / isSupportKnown() to tell "unknown" from "confirmed unsupported"
Uploading an empty file fails outrightAn empty file is not valid upload contentThe file must be at least 1 byte long; only the download result of an empty file is byte[0]