FoE (File over EtherCAT)
The FoE protocol transfers files to and from EtherCAT slaves; typical uses are firmware updates and uploading or downloading configuration files.
Obtained from slave.GetFoE(), which returns a FoE& reference.
Honest boundaries
- Read buffer / file size:
Downloadhas the runtime library allocate the buffer and copyfile_sizebytes into astd::vector; it is not a user buffer of arbitrary size - Mailbox gateway WRQ: stateful write sessions are not implemented. Write Request (opcode 0x02) / Data / Ack fail with FoE Error
0x00008001, not an ACK. Do not describe a failed WRQ as an ACK
File read (download)
Download()
std::vector<uint8_t> Download(const std::string& filename,
int64_t password = -1,
int timeoutMs = 0,
bool enableCrc = false);
Reads (downloads) a file from the slave device. Returns an empty vector on failure. The runtime library allocates the buffer and copies file_size bytes; it is not a user buffer of arbitrary size.
Parameters:
filename— name of the file to readpassword— FoE password (int64_t;-1= use the default passwordDefaultPassword();>=0is used directly as the password)timeoutMs— timeout (0 = use the default timeout)enableCrc— enable CRC segment checking (internally takes theDownloadExpath)
Download / Upload / DownloadEx / UploadEx and their *Async versions all update the last_error_ internal state, so they are not const methods.
Example:
auto& foe = master.GetSlave(1).GetFoE();
// Read the configuration file
auto config = foe.Download("config.xml");
if (!config.empty()) {
printf("配置内容 (%zu 字节):\n%.*s\n", // Configuration content (%zu bytes):\n%.*s
config.size(), (int)config.size(), config.data());
}
File write (upload)
Upload()
bool Upload(const std::string& filename, const uint8_t* data, int dataLen,
int64_t password = -1, int timeoutMs = 0);
bool Upload(const std::string& filename, const std::vector<uint8_t>& data,
int64_t password = -1, int timeoutMs = 0);
Uploads (writes) a file to the slave device. Both a raw pointer and a std::vector are supported. password is an int64_t; -1 = use the default password.
Example:
auto& foe = master.GetSlave(1).GetFoE();
// Write configuration
std::string new_config = "<Config><Param1>100</Param1></Config>";
std::vector<uint8_t> data(new_config.begin(), new_config.end());
bool ok = foe.Upload("config.xml", data, 0x12345678);
printf("%s\n", ok ? "写入成功" : "写入失败"); // Write succeeded / write failed
Default parameters
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Timeout | DefaultTimeoutMs | int | read/write | default timeout in milliseconds, 5000 at construction |
| Timeout | DefaultTimeoutUs | int | read/write | the default timeout expressed in microseconds; reading returns milliseconds × 1000, writing divides by 1000 and converts back to milliseconds |
| Password | DefaultPassword | uint32_t | read/write | the default password used when no password is passed explicitly |
| Options | FoEOptions.Defaults | FoEOptions | read-only | static helper that returns the preset options: StrictMode and AutoAppendCrc set to 1, everything else cleared |
auto& foe = master.GetSlave(1).GetFoE();
// Default timeout
foe.DefaultTimeoutMs(10000); // 10 seconds
printf("默认超时: %d ms\n", foe.DefaultTimeoutMs()); // Default timeout: %d ms
// Default password
foe.DefaultPassword(0x12345678);
printf("默认密码: 0x%08X\n", foe.DefaultPassword()); // Default password: 0x%08X
DefaultTimeoutUs()
int DefaultTimeoutUs() const;
void DefaultTimeoutUs(int v);
The default timeout expressed in microseconds, as a read/write pair. Reading returns DefaultTimeoutMs() * 1000; writing stores v / 1000 as milliseconds, and the integer division truncates, so a value that is not a whole number of milliseconds loses the remainder. The constructor's timeoutMs defaults to 5000, that is 5 000 000 microseconds.
Parameters (write overload):
v(int) — timeout in microseconds, divided by 1000 and stored as milliseconds
Returns (read overload):
int— the default timeout in microseconds
Example:
printf("默认超时: %d us\n", foe.DefaultTimeoutUs()); // Default timeout: %d us
foe.DefaultTimeoutUs(2000000); // Converted to 2000 ms
FoEOptions.Defaults()
static FoEOptions Defaults();
Static helper that returns a preset set of FoE extension options. The whole structure is cleared first, then StrictMode and AutoAppendCrc are set to 1; EnableCrc stays 0 and ExpectedCrc stays 0.
Returns:
FoEOptions— a copy of the preset options
Example:
auto opts = FoEOptions::Defaults();
opts.EnableCrc = 1; // CRC is not verified by default; turn it on yourself if needed
The FoEOptions in data/structures.hpp carries Defaults() and also has reserved areas and callback slots; the FoE::FoEOptions nested in the FoE class is what DownloadEx / UploadEx actually accept, and it has only four fields: EnableCrc / StrictMode / AutoAppendCrc / ExpectedCrc. The two are different types and cannot be assigned to each other: Defaults() returns the former, while options passed to DownloadEx / UploadEx must be FoE::FoEOptions.
Transfer progress
SetProgressCallback()
void SetProgressCallback(FoEProgressCallback cb);
Sets the file transfer progress callback. Note: in the 2.11.0 C++ headers the callback is only stored and never fires (the progress hook underneath is not wired up); for transfer progress use SetBusyHook() (triggered by BUSY frames) or estimate the percentage yourself with EstimatePacketCount().
Callback type:
using FoEProgressCallback = std::function<void(
uint16_t slave, int packetNumber, int dataSize, int progressPercent)>;
Callback parameters:
slave(uint16_t) — slave indexpacketNumber(int) — current data packet number (starts at 1 and increments)dataSize(int) — size of the data carried in the current packet (bytes)progressPercent(int) — estimated progress percentage (0-100)
EstimatePacketCount()
static int EstimatePacketCount(int fileSize, int mailboxSize = 512);
Estimates the number of data packets a file transfer needs. The FoE protocol header takes 6 bytes, so each packet carries mailboxSize - 6 bytes of data. Can be used to compute a progress percentage.
Parameters:
fileSize(int) — file size in bytesmailboxSize(int) — mailbox size in bytes, default 512
Returns:
int— the estimated number of data packets
Basic usage
auto& foe = master.GetSlave(1).GetFoE();
// Set the progress callback
foe.SetProgressCallback([](uint16_t slave, int pkt, int sz, int percent) {
printf("\r从站 %d 传输进度: %d%% (包 %d, %d 字节)", slave, percent, pkt, sz); // Slave %d transfer progress: %d%% (packet %d, %d bytes)
fflush(stdout);
});
// Upload a file
bool ok = foe.Upload("firmware.bin", firmware);
printf("\n%s\n", ok ? "上传完成" : "上传失败"); // Upload finished / upload failed
Full example: firmware update with progress and error handling
#include "ethercat.hpp"
#include <fstream>
#include <iterator>
using namespace darra;
int main() {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
master.SetState(EcState::OP);
master.Start();
auto& foe = master.GetSlave(1).GetFoE();
// Set the timeout and password
foe.DefaultTimeoutMs(30000);
// Load the firmware file
std::ifstream file("new_firmware.bin", std::ios::binary);
std::vector<uint8_t> firmware(
(std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// Estimated packet count
int totalPackets = FoE::EstimatePacketCount(static_cast<int>(firmware.size()));
printf("文件大小: %zu 字节, 预计 %d 个数据包\n", firmware.size(), totalPackets); // File size: %zu bytes, %d packets expected
// Set the progress callback (with percentage calculation)
foe.SetProgressCallback([totalPackets](uint16_t slave, int pkt, int sz, int percent) {
// percent is computed automatically by the SDK; you can also compute it manually:
// int manualPercent = totalPackets > 0 ? (pkt * 100) / totalPackets : 0;
printf("\r固件上传: %d%% (包 %d/%d)", percent, pkt, totalPackets); // Firmware upload: %d%% (packet %d/%d)
fflush(stdout);
});
// Upload firmware
bool ok = foe.Upload("firmware.bin", firmware);
printf("\n");
if (ok) {
printf("固件更新成功\n"); // Firmware update succeeded
} else {
// Get the error details
auto error = foe.LastErrorCode();
auto desc = FoE::GetErrorDescription(error);
printf("固件更新失败: %s (0x%04X)\n", desc.c_str(), static_cast<uint16_t>(error)); // Firmware update failed: %s (0x%04X)
}
getchar();
return 0;
}
Download with CRC checking
auto& foe = master.GetSlave(1).GetFoE();
// Set the progress callback
foe.SetProgressCallback([](uint16_t slave, int pkt, int sz, int percent) {
printf("\r下载进度: %d%% (包 %d)", percent, pkt); // Download progress: %d%% (packet %d)
fflush(stdout);
});
// Verify the downloaded file with CRC
auto data = foe.Download("config.bin", -1, 0, true /* enableCrc */);
printf("\n");
if (!data.empty()) {
printf("下载成功: %zu 字节\n", data.size()); // Download succeeded: %zu bytes
} else {
printf("下载失败: %s\n", // Download failed: %s
FoE::GetErrorDescription(foe.LastErrorCode()).c_str());
}
Asynchronous API (std::future)
A long FoE transfer (a firmware upgrade easily runs to several MB and several minutes) blocks the calling thread, so besides the synchronous Download / Upload / DownloadEx / UploadEx the C++ SDK provides 4 std::future-style asynchronous entry points that hand the synchronous call to a background thread with std::async(std::launch::async).
A std::future on its own cannot interrupt a background thread. To end a transfer early, pair it with Cancel(): future.get() returns as soon as the background std::async thread exits its next mailbox iteration. Callbacks registered with SetBusyHook() also fire on the *Async paths.
DownloadAsync()
std::future<std::vector<uint8_t>> DownloadAsync(
const std::string& filename,
int64_t password = -1,
int timeoutMs = 0,
bool enableCrc = false);
Asynchronously reads (downloads) a file from the slave. On failure the future holds an empty vector, and the error code can still be queried with LastErrorCode().
UploadAsync()
std::future<bool> UploadAsync(
const std::string& filename,
std::vector<uint8_t> data,
int64_t password = -1,
int timeoutMs = 0);
Asynchronously uploads (writes) a file to the slave. data is captured by value, so the original object can be destroyed right after the call.
DownloadExAsync() / UploadExAsync()
std::future<std::vector<uint8_t>> DownloadExAsync(
const std::string& filename, FoEOptions opts,
int64_t password = -1, int timeoutMs = 0);
std::future<bool> UploadExAsync(
const std::string& filename, std::vector<uint8_t> data,
FoEOptions opts, int64_t password = -1, int timeoutMs = 0);
Asynchronous versions of the *Ex series; options such as CRC checking are passed in a FoEOptions structure (EnableCrc / StrictMode / AutoAppendCrc / ExpectedCrc).
Example (upgrading several slaves in parallel):
#include <future>
#include <vector>
auto& foeA = master.GetSlave(1).GetFoE();
auto& foeB = master.GetSlave(2).GetFoE();
std::vector<uint8_t> fwA = /* Bytes of the firmware file a.bin*/;
std::vector<uint8_t> fwB = /* Bytes of the firmware file b.bin*/;
auto fa = foeA.UploadAsync("firmware.bin", std::move(fwA));
auto fb = foeB.UploadAsync("firmware.bin", std::move(fwB));
bool okA = fa.get(); // Block until slave 1 completes
bool okB = fb.get(); // Block until slave 2 completes
printf("A=%d B=%d\n", okA, okB);
// Use with std::future_status::ready for polling / UI progress
auto fut = foeA.DownloadAsync("config.bin");
while (fut.wait_for(std::chrono::milliseconds(50)) != std::future_status::ready) {
UpdateUiProgressBar();
}
auto data = fut.get();
Error handling
The FoEErrorCode enumeration defines the diagnostic error codes for failed transfers:
| Enum value | Value | Description |
|---|---|---|
| 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 |
GetErrorDescription()
static std::string GetErrorDescription(FoEErrorCode errorCode);
Returns the Chinese description text for an FoE error code.
LastErrorCode() / GetLastError()
FoEErrorCode LastErrorCode() const;
FoEErrorCode GetLastError() const;
Gets the error code of the most recent FoE operation. When Download / Upload fails, this gives the specific cause.
Example:
auto& foe = master.GetSlave(1).GetFoE();
auto data = foe.Download("firmware.bin");
if (data.empty()) {
auto error = foe.LastErrorCode();
auto desc = FoE::GetErrorDescription(error);
printf("下载失败: %s\n", desc.c_str()); // Download failed: %s
}
Full example
Firmware update
#include "ethercat.hpp"
#include <fstream>
#include <iterator>
using namespace darra;
int main() {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
master.SetState(EcState::OP);
master.Start();
auto& foe = master.GetSlave(1).GetFoE();
// Set the timeout
foe.DefaultTimeoutMs(30000); // 30 seconds
// Load the firmware file
std::ifstream file("new_firmware.bin", std::ios::binary);
std::vector<uint8_t> firmware(
(std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
// Upload firmware
bool ok = foe.Upload("firmware.bin", firmware);
printf("%s\n", ok ? "固件更新成功" : "固件更新失败"); // Firmware update succeeded / firmware update failed
getchar();
return 0;
}
FoE Cancel / BusyHook
A long FoE transfer (a firmware upgrade can take minutes) needs two capabilities: user cancellation (abort the transfer when a dialog closes, a timeout expires or an emergency stop occurs) and fine-grained progress (current packet position, retry count and a text description). The SDK provides Cancel() / ClearCancel() / SetBusyHook() to be used together.
FoEBusyEvent
struct FoEBusyEvent {
int slaveIndex = 0; // Slave index
uint16_t done = 0; // Amount completed
uint16_t entire = 0; // Total
std::string text; // Optional description ("Downloading" / "Erasing flash" / "Verifying" and so on, ASCII)
int retryIndex = 0; // Retry round (0 means the first attempt, >0 means the Nth retry)
double Percent() const { // Completion percentage (0.0 ~ 100.0)
return entire > 0 ? 100.0 * done / entire : 0.0;
}
};
Cancel()
bool Cancel() const;
Requests cancellation of the FoE transfer currently in progress. It sets an internal cancel flag; the SDK aborts the transfer and returns an error once it sees the flag at the next packet boundary. A return of true means the cancel flag was set (it does not mean the transfer has actually stopped; the transfer thread still has to respond).
ClearCancel()
bool ClearCancel() const;
Clears the cancel flag and prepares for the next transfer. The Download / Upload entry points already clear it automatically; this method is only for resetting after an abnormal case.
SetBusyHook()
using BusyCallback = std::function<void(const FoEBusyEvent&)>;
bool SetBusyHook(BusyCallback cb);
Registers the Busy callback; true means it was set (false = the runtime is not ready or the call was rejected). Unlike SetProgressCallback, the BusyHook provides finer-grained status information, including the retry count and a text description, and fires when the slave sends a BUSY frame (ETG.1000.6 Table 93, flash programming cycle reporting), which suits a UI progress bar. The companion ClearBusyHook() clears the hook.
Example (C++20 std::jthread + stop_token cancellation):
using namespace std::chrono_literals;
auto& foe = master.GetSlave(1).GetFoE();
// Set BusyHook to show detailed progress
foe.SetBusyHook([](const FoEBusyEvent& e) {
std::cout << "[从站 " << e.slaveIndex << "] " // [Slave
<< e.Percent() << "% "
<< e.text;
if (e.retryIndex > 0)
std::cout << " (重试 " << e.retryIndex << ")"; // (retry
std::cout << std::endl;
});
// Clear the old cancellation flag
foe.ClearCancel();
// Start the firmware upload with std::jthread, supporting external cancellation
std::vector<uint8_t> firmware = /* Firmware file bytes*/;
std::jthread worker([&](std::stop_token st) {
auto fut = std::async(std::launch::async, [&] {
return foe.Upload("firmware.bin", firmware);
});
// Poll the stop_token and trigger the cancel
while (fut.wait_for(100ms) == std::future_status::timeout) {
if (st.stop_requested()) {
foe.Cancel();
break;
}
}
bool ok = fut.get();
std::cout << (ok ? "上传完成" : "上传取消或失败") << "\n"; // Upload finished / upload cancelled or failed
});
// User clicked the cancel button / timeout and similar cases
std::this_thread::sleep_for(30s);
worker.request_stop(); // jthread joins automatically
Cancel()only sets the flag; the actual abort happens at the next packet boundary (delayed by at most one packet's transfer time, usually <100ms)- after cancellation,
UploadreturnsfalseandDownloadreturns an empty vector;LastErrorCode()gives the specific reason - cancelling in the middle of a firmware write can leave the slave flash partially written, so the complete firmware has to be uploaded again
- ProgressCallback (
SetProgressCallback): simple percentage + packet number + byte count; in 2.11.0 it is only stored and never fires - BusyHook (
SetBusyHook): adds a text description and retry count, fires on BUSY frames, suited to a GUI status bar or a log - the two can be registered at the same time and do not affect each other
ETG.1020 §15 FoE cancellation semantics; ETG.5003 §8 firmware upgrade best practice.