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:
downloadlets the underlying layer allocate the buffer and return the data according tofile_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.
| Method | Type | Semantics |
|---|---|---|
| isSupported() | boolean | Returns true only when support is confirmed; an unknown capability returns false (no support is claimed without evidence) |
| supportsFoE() | Boolean | Tri-state: TRUE supported, FALSE confirmed unsupported, null unknown |
| supportState() | Boolean | Unified entry point of IMailboxProtocol; same source and same conclusion as supportsFoE() |
| isSupportKnown() | boolean | Whether 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
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Default parameters | defaultTimeoutMs() / defaultTimeoutMs(int) | int | read/write | Default timeout (milliseconds), default 5000 (5 seconds) |
| defaultPassword() / defaultPassword(int) | int | read/write | Default 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;nullor an empty string is treated as a failure straight awaypassword(Integer) — FoE password (usesdefaultPassword()when omitted)timeoutMs(Integer) — timeout (milliseconds, usesdefaultTimeoutMs()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 returnsbyte[0], a failure returnsnull
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;nullor an empty string is treated as a failure straight awayfileData(byte[]) — file data to write;nullor an empty array is treated as a failure straight away, and an empty file cannot be uploadedpassword(Integer) — FoE password (usesdefaultPassword()when omitted)timeoutMs(Integer) — timeout (milliseconds, usesdefaultTimeoutMs()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—trueon success, otherwisefalse(again usegetLastError()/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 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 indexpacketNumber(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 throughestimatePacketCount
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; passingnullis equivalent todisableProgressHook()estimatedTotalPackets(int) — estimated total packet count (used to compute theprogressPercentpercentage and obtainable fromestimatePacketCount);0means 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—estimatedTotalPacketsis negativeIllegalStateException— 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 whenfileSize <= 0ormailboxSize <= 0. WhenmailboxSizeis 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—truemeans 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—truemeans 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() 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.
enableProgressHook— local progress estimate based on the packet number; it does not depend on slave reports and works with any FoE slavesetBusyHook— 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;nullclears 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
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 value | Value | Description |
|---|---|---|
| NOT_DEFINED | 0x8000 | Undefined error |
| NOT_FOUND | 0x8001 | File not found |
| ACCESS_DENIED | 0x8002 | Access denied |
| DISK_FULL | 0x8003 | Disk full |
| ILLEGAL | 0x8004 | Illegal operation |
| PACKET_NUMBER_WRONG | 0x8005 | Wrong packet number |
| ALREADY_EXISTS | 0x8006 | File already exists |
| NO_USER | 0x8007 | No such user |
| BOOTSTRAP_ONLY | 0x8008 | Only available in Bootstrap mode |
| NOT_BOOTSTRAP | 0x8009 | Not in Bootstrap mode |
| NO_RIGHTS | 0x800A | Insufficient rights |
| PROGRAM_ERROR | 0x800B | Program 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.
| Method | Type | Semantics |
|---|---|---|
| getLastError() | FoEErrorCode | FoE 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() | long | Most recent protocol-layer error code; 0 = no error, and a failure is always other than 0 |
| getLastStatus() | MailboxStatus | Status 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).
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol identification | getProtocolType() | byte | read-only | Protocol type constant (FoE=0x04) |
| getProtocolName() | String | read-only | Protocol name ("FoE") | |
| isSupported() | boolean | read-only | Whether the slave supports this protocol; returns false when the capability is unknown (fail-closed) | |
| supportState() | Boolean | read-only | Capability tri-state: TRUE=supported, FALSE=confirmed unsupported, null=unknown; same source as supportsFoE() | |
| isSupportKnown() | boolean | read-only | Whether the capability conclusion is known (supportState() != null) | |
| Transaction status | getLastStatus() | MailboxStatus | read-only | Unified status of the most recent mailbox transaction |
| getLastErrorCode() | long | read-only | Most recent protocol-layer error code (0=no error) | |
| Statistics | getStatistics() | MailboxStatistics | read-only | Mailbox statistics snapshot |
| resetStatistics() | void | write-only | Resets 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
| Symptom | Cause | Handling |
|---|---|---|
| A transfer produces no result for a long time and the slave keeps returning BUSY | The slave is flashing and has not given its final confirmation yet | Wait for flashing to finish and do not start upload again |
| Transfer timeout | The file is large, the mailbox is congested, or the default timeout is too short | Increase defaultTimeoutMs, or pass timeoutMs explicitly on the call |
| The error code says the file was not found | The file name does not exist on the slave | Check the file name and its case; if necessary, confirm with download first |
| The error code says no such user or insufficient rights | The FoE password is wrong | Retry with the password configured on the slave |
download returns null / upload returns false | The transfer failed, or an argument is invalid | Check 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 FoEProtocolException | The asynchronous transfer failed | Get the exception with ex.getCause() and read errorCode; when it carries NOT_DEFINED, check getLastStatus() as well |
| The result after cancelling is unknown | cancel() is request-based and the transfer exits only later | Wait 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 it | The capability could not be read and was folded into false | Use supportsFoE() / isSupportKnown() to tell "unknown" from "confirmed unsupported" |
| Uploading an empty file fails outright | An empty file is not valid upload content | The file must be at least 1 byte long; only the download result of an empty file is byte[0] |