Skip to main content

FoE (File over EtherCAT)

File transfer protocol supporting firmware updates and configuration file upload and download.

FoE availability check

Use the return value of GetSlaveFoEDetails(master_index, slave) to determine whether a slave supports FoE (a value other than 0 means supported).

To distinguish supported / not supported / unknown, use the tri-state query ec_slave_get_proto_support_state(master, slave, MBXPROT_FOE). For FoE, SII General foe_details bit0 can give an authoritative negative answer (NO); when it cannot be read, report UNKNOWN.

Function naming

For FoE file transfer, prefer the public interfaces foe_upload / foe_download and their _ex versions (no handle, no function-pointer table).

Honest boundaries​

  • Read buffer / file size: foe_download requires the caller to pre-allocate out_buf; when data_size > out_buf_size nothing is copied and the call fails (*out_size reports the required size). It is not arbitrary-size.
  • 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.

Basic read and write​

foe_download()​

int foe_download(uint16_t master, uint16_t slave,
const char* filename, uint32_t password,
uint8_t* out_buf, uint32_t out_buf_size, uint32_t* out_size,
int32_t timeout_us);

Reads a file from the slave. out_buf is pre-allocated by the caller; when the buffer is too small nothing is copied and the call fails, with *out_size reporting the required size.

Return value: 0 on success; a negative value on failure (carrying the underlying FoE error code).

foe_upload()​

int foe_upload(uint16_t master, uint16_t slave,
const char* filename, uint32_t password,
const uint8_t* data, uint32_t data_size,
int32_t timeout_us);

Writes a file to the slave. Firmware upgrades usually require the slave to be in Bootstrap state; the caller must ensure this.

Example:

/* read a file */
uint8_t buf[65536];
uint32_t size = 0;
if (foe_download(master, 1, "firmware.bin", 0,
buf, sizeof(buf), &size, 30000000) == 0) {
printf("读取 %u 字节\n", size); /* Read %u bytes */
}

/* write a file */
foe_upload(master, 1, "firmware.bin", 0, file_data, file_size, 30000000);

Extended versions (with CRC)​

foe_download_ex() / foe_upload_ex()​

int foe_download_ex(uint16_t master, uint16_t slave,
const char* filename, uint32_t password,
uint8_t* out_buf, uint32_t out_buf_size, uint32_t* out_size,
int32_t timeout_us, int enable_crc);
int foe_upload_ex(uint16_t master, uint16_t slave,
const char* filename, uint32_t password,
const uint8_t* data, uint32_t data_size,
int32_t timeout_us, int enable_crc);

File transfer with CRC verification. When enable_crc != 0, strict CRC verification is enabled.

Example:

uint8_t buf[65536];
uint32_t size = 0;
if (foe_download_ex(master, 1, "firmware.bin", 0,
buf, sizeof(buf), &size, 30000000, 1) == 0) {
printf("读取成功: %u 字节\n", size); /* Read succeeded: %u bytes */
}

Transfer progress​

foe_set_progress_hook()​

int foe_set_progress_hook(uint16_t master, uint16_t slave,
foe_progress_fn callback);

Sets the FoE transfer progress callback for the given slave. Once set, foe_upload / foe_download and the _ex operations trigger it automatically, once per data packet transferred.

Callback type:

typedef void (*foe_progress_fn)(uint16_t slave, int packet_number, int data_size);

Callback parameters:

  • slave (uint16_t) — slave index
  • packet_number (int) — current packet number (increments from 1)
  • data_size (int) — size in bytes of the data carried in the current packet

foe_clear_progress_hook()​

int foe_clear_progress_hook(uint16_t master, uint16_t slave);

Clears the FoE transfer progress callback for the given slave.

Progress percentage calculation​

The progress callback provides only packet_number and data_size; the application layer must compute the progress percentage itself. Estimate the total packet count from the file size and the mailbox size:

/* estimate the total packet count */
int estimate_packet_count(int file_size, int mailbox_size) {
int per_packet = mailbox_size - 6; /* the FoE protocol header occupies 6 bytes */
if (per_packet <= 0) return 0;
return (file_size + per_packet - 1) / per_packet;
}

BUSY callback and transfer cancellation​

Unlike foe_set_progress_hook (fired per packet), the BUSY callback follows the Done/Entire/BusyText progress semantics of ETG.1000.6 Table 93. The slave pushes it during erase and write phases, together with a text description, which makes it suitable for showing friendly progress during the Flash write phase.

The SDK also offers a Cancel request, which asks to interrupt a running foe_upload / foe_download; it takes effect from the next loop iteration.

foe_busy_callback_t​

/* defined in slave/foe.h */
typedef void (*foe_busy_callback_t)(
uint16_t slave, uint16_t done, uint16_t entire,
const char* text, int retry_idx);

Callback parameters:

  • slave (uint16_t) — slave index
  • done (uint16_t) — current progress (for example, erased bytes / block count)
  • entire (uint16_t) — total amount
  • text (const char*) — BusyText string returned by the slave (valid only during the callback; copy it)
  • retry_idx (int) — current retry count

foe_set_busy_hook()​

int foe_set_busy_hook(uint16_t master, foe_busy_callback_t callback);

Sets the FoE BUSY callback. Pass NULL to unregister.

Return value:

  • int — 0 on success, -1 on failure (entry point unavailable)

foe_request_cancel()​

int foe_request_cancel(uint16_t master, uint16_t slave);

Requests cancellation of an in-progress FoE transfer. Once the cancel flag is set, it takes effect from the next protocol loop iteration (the next frame), and foe_upload / foe_download return failure.

Return value:

  • int — 0 = cancel request accepted; -1 = entry point unavailable or the call failed

foe_clear_cancel()​

int foe_clear_cancel(uint16_t master, uint16_t slave);

Clears the cancel flag. This is usually unnecessary: the foe_upload / foe_download entry points clear it automatically.

Example (firmware upgrade + progress display + user interrupt):

static volatile int g_user_cancel = 0;

void on_foe_busy(uint16_t slave, uint16_t done, uint16_t entire,
const char* text, int retry_idx)
{
double pct = (entire > 0) ? (100.0 * done / entire) : 0.0;
printf("\r[slave %u] %.1f%% (%u/%u) %s [retry=%d]",
slave, pct, done, entire, text ? text : "", retry_idx);
fflush(stdout);
}

int firmware_update(uint16_t master, uint16_t slave,
const char* fname, const char* data, int size)
{
foe_set_busy_hook(master, on_foe_busy);

/* background thread watching for the user cancel key */
/* ... omitted ... */

BOOL ok = foe_upload(master, slave, fname, 0, (const uint8_t*)data, size, 60000000) == 0;

if (!ok && g_user_cancel) {
printf("\n用户取消\n"); /* User cancelled */
} else if (!ok) {
printf("\n传输失败\n"); /* Transfer failed */
} else {
printf("\n完成\n"); /* Done */
}

/* release the hook */
foe_set_busy_hook(master, NULL);
return ok ? 0 : -1;
}

/* the user presses Ctrl+C or the cancel button */
void on_user_cancel(uint16_t master, uint16_t slave)
{
g_user_cancel = 1;
foe_request_cancel(master, slave);
}
Thread safety
  • The BUSY callback runs on an SDK worker thread; the text pointer is valid only during the callback, so copy it immediately
  • Do not perform long-running work or call other FoE APIs inside the callback
  • foe_request_cancel is a soft interrupt; cancellation may take 1-2 mailbox cycles to take effect
  • When several slaves are being written concurrently, foe_request_cancel affects only the specified slave and does not interrupt other transfers

Default timeout and password​

The C API is procedural, so this group of functions maintains the FoE default timeout and password globally within the process. The timeout_us / password arguments of foe_upload / foe_download are explicit inputs: to reuse a default, read it with the getter first and pass it in (see the example below). Changing a default does not affect requests already in flight.

int      foe_get_default_timeout_ms(void);
void foe_set_default_timeout_ms(int timeout_ms);

int foe_get_default_timeout_us(void); /* default timeout (ms) × 1000 */
void foe_set_default_timeout_us(int timeout_us);

uint32_t foe_get_default_password(void);
void foe_set_default_password(uint32_t password);

Defaults: timeout_ms = 5000, password = 0.

Example:

/* raise the FoE default timeout globally to 30 seconds (large firmware images) */
foe_set_default_timeout_ms(30000);

/* set one password for a group of slaves (required by the Beckhoff EL6900 safety module) */
foe_set_default_password(0xDEADBEEF);

/* pass the defaults explicitly at the call site (foe_download takes microseconds, so use the us getter) */
uint8_t buf[4096];
uint32_t n = 0;
foe_download(master, 1, "fw.bin", foe_get_default_password(),
buf, sizeof(buf), &n, foe_get_default_timeout_us());

FoE error codes​

Error codes defined by the FoE protocol, used to diagnose why a transfer failed.

foe_error_code_t​

/* defined in slave/foe.h (FOE_ERR_* naming).
* ethercat_types.h also provides ec_foe_error_code_t (UPPER_SNAKE naming), covering only 0x8000..0x800B with identical values;
* FOE_ERR_None / FOE_ERR_Timeout and the 0x800C..0x8012 extension codes are provided only by slave/foe.h. */
typedef enum {
FOE_ERR_None = 0, /* success / already cleared, not a timeout */
FOE_ERR_Timeout = 0xFFFF, /* timeout */
FOE_ERR_NotDefined = 0x8000, /* undefined error */
FOE_ERR_NotFound = 0x8001, /* file not found */
FOE_ERR_AccessDenied = 0x8002, /* access denied */
FOE_ERR_DiskFull = 0x8003, /* disk full */
FOE_ERR_Illegal = 0x8004, /* illegal operation */
FOE_ERR_PacketNumberWrong = 0x8005, /* wrong packet number */
FOE_ERR_AlreadyExists = 0x8006, /* file already exists */
FOE_ERR_NoUser = 0x8007, /* no such user */
FOE_ERR_BootstrapOnly = 0x8008, /* available only in Bootstrap mode */
FOE_ERR_NotBootstrap = 0x8009, /* not in Bootstrap mode */
FOE_ERR_NoRights = 0x800A, /* not enough rights */
FOE_ERR_ProgramError = 0x800B, /* program error */
FOE_ERR_ChecksumWrong = 0x800C, /* checksum failure */
FOE_ERR_FirmwareMismatch = 0x800D, /* firmware mismatch */
FOE_ERR_NoFileToRead = 0x800F, /* no readable file */
FOE_ERR_FileHeaderMissing = 0x8010, /* file header missing */
FOE_ERR_FlashProblem = 0x8011, /* Flash write problem */
FOE_ERR_FileIncompatible = 0x8012 /* incompatible file */
} foe_error_code_t;
Error-code helper functions

slave/foe_ext.h provides foe_map_dll_error(int), which maps an underlying return value to foe_error_code_t, and foe_get_error_description(foe_error_code_t), which returns a Chinese description.

Full example​

#include "ethercat.h"
#include <stdio.h>
#include <stdlib.h>

/* globals: estimated total packet count (used to compute the percentage) */
static int g_total_packets = 0;

/* progress callback function */
void on_foe_progress(uint16_t slave, int packet_number, int data_size) {
int percent = 0;
if (g_total_packets > 0)
percent = (packet_number * 100) / g_total_packets;
if (percent > 100) percent = 100;

printf("\r从站 %d 传输进度: %d%% (包 %d/%d, 当前包 %d 字节)", /* Slave %d transfer progress: %d%% (packet %d/%d, current packet %d bytes) */
slave, percent, packet_number, g_total_packets, data_size);
fflush(stdout);
}

int estimate_packet_count(int file_size, int mailbox_size) {
int per_packet = mailbox_size - 6;
if (per_packet <= 0) return 0;
return (file_size + per_packet - 1) / per_packet;
}

int main(void)
{
uint16_t master = Initialize();
SetNetwork(master, "\\Device\\NPF_{...}", "");
SetStateSequence(master, EC_STATE_BOOT, 5000);

uint16_t slave = 1;

/* load the firmware file */
FILE* f = fopen("new_firmware.bin", "rb");
fseek(f, 0, SEEK_END);
int file_size = (int)ftell(f);
fseek(f, 0, SEEK_SET);
char* file_data = (char*)malloc(file_size);
fread(file_data, 1, file_size, f);
fclose(f);

/* estimate the packet count (assume a 512-byte mailbox) */
g_total_packets = estimate_packet_count(file_size, 512);
printf("文件大小: %d 字节, 预计 %d 个数据包\n", file_size, g_total_packets); /* File size: %d bytes, %d packets expected */

/* enable the progress callback */
foe_set_progress_hook(master, slave, on_foe_progress);

/* perform the firmware upload */
BOOL ok = foe_upload(master, slave, "firmware.bin", 0,
(const uint8_t*)file_data, file_size, 30000000) == 0;
printf("\n%s\n", ok ? "固件更新成功" : "固件更新失败"); /* Firmware update succeeded, or firmware update failed */

/* disable the progress callback */
foe_clear_progress_hook(master, slave);

free(file_data);
Dispose(master);
return 0;
}

FoE dx_* interface​

The 6 dx_foe_* functions in slave/foe.h are the low-level FoE file-transfer channel: raw file read / write entry points plus the progress hook. The header notes that the upper layer foe_download_ex calls dx_foe_read_ex (strict mode) when enable_crc is a value other than 0, and falls back to dx_foe_read when the low-level entry point is missing.

CategoryFunctionReturn typeRead/writeDescription
File readdx_foe_readBOOLread-onlyReads a file from the slave by filename + password; *file_data is allocated by the runtime and its length is in *file_size; it must be released with FreeMemory()
File writedx_foe_writeBOOLwrite-onlyWrites to the slave by filename + password; file_data stays owned by the caller and the runtime neither takes it over nor releases it
Extended readdx_foe_read_exBOOLread-onlySame as dx_foe_read, additionally taking ec_foe_options_t* (CRC verification / strict mode / automatic CRC marker)
Extended writedx_foe_write_exBOOLwrite-onlySame as dx_foe_write, additionally taking ec_foe_options_t*
Progressdx_foe_set_progress_hookBOOLwrite-onlySets the progress callback for this master, of type foe_progress_callback_t (slave / packet_number / data_size)
dx_foe_clear_progress_hookBOOLwrite-onlyClears the progress callback for this master

Ownership, failure sentinels and hook scope​

  • Read buffers belong to the runtime: *file_data from dx_foe_read / dx_foe_read_ex is allocated by the runtime with the length given by *file_size, not an arbitrary size; release it with FreeMemory().
  • Write buffers belong to the caller: file_data for dx_foe_write / dx_foe_write_ex is held by the caller; the runtime neither takes it over nor releases it, and the caller may reclaim it as soon as the call returns.
  • On failure *file_size is a sentinel (header convention): mailbox timeout = 0; a real FoE Error from the slave = a negative ERR_TYPE_FOE_*. After a failure, do not look only at the BOOL: a zero versus a non-zero negative *file_size is the boundary between "timeout, no reply" and "protocol error".
  • The progress hook is one global hook per master, not per slave: a master has exactly one, and the slave parameter in the callback tells which slave's transaction it is. To register per slave, use the per-slave wrapper of the upper-layer foe_set_progress_hook, which dispatches through this one global hook.
  • dx_foe_set_progress_hook / dx_foe_clear_progress_hook both return BOOL, indicating whether the hook for this master was set / cleared; the hook is an entry on the transfer path, and once cleared no further callback is made.
  • ec_foe_options_t for the _ex variants is defined with 1-byte alignment and matches the runtime byte for byte (enable_crc / strict_mode / auto_append_crc / expected_crc / CRC progress callback); pass a pointer.

Example​

#include "ethercat.h"
#include <stdio.h>

static void on_progress(uint16_t slave, int packet_number, int data_size)
{
printf("从站 %u 第 %d 包, %d 字节\n", slave, packet_number, data_size); /* Slave %u packet %d, %d bytes */
}

int main(void)
{
uint16_t master = Initialize();
SetNetwork(master, "\\Device\\NPF_{...}", "");
SetStateSequence(master, EC_STATE_BOOT, 5000);

/* Read: *file_data is allocated by the runtime, call FreeMemory when done; on failure look at the *file_size sentinel*/
char* data = NULL;
int size = 0;
if (dx_foe_read(master, 1, "config.bin", 0, &data, &size, 30000)) {
printf("读到 %d 字节\n", size); /* Read %d bytes */
FreeMemory(data);
} else if (size == 0) {
printf("邮箱超时无应答\n"); /* Mailbox timeout, no response */
} else {
printf("从站返回 FoE 错误\n"); /* The slave returned a FoE error */
}

/* Write: file_data is owned by the caller, the runtime does not free it*/
static const char payload[] = "hello";
dx_foe_write(master, 1, "config.bin", 0, payload, sizeof(payload) - 1, 30000);

/* One progress hook per master, clear it when done*/
dx_foe_set_progress_hook(master, on_progress);
dx_foe_clear_progress_hook(master);

Dispose(master);
return 0;
}