Skip to main content

FoE (File over EtherCAT)

FoE transfers files over the EtherCAT mailbox and is used for firmware updates and configuration file reads and writes. The direction follows the API naming: download fetches a file from the slave, upload writes to the slave; the chunking of upload is handled by the SDK, so the caller only supplies the file name and the data. A single download reads at most 64 KiB (65536 bytes); for larger files you must use the chunked read tool provided by the slave vendor.

The parameter order of the two file transfer methods is fixed:

  • download(filename, password=None, timeout_ms=None, enable_crc=False) — returns bytes or None
  • upload(filename, file_data, password=None, timeout_ms=None, enable_crc=False) — returns bool

When password is omitted, slave.foe.default_password is used (default 0); when timeout_ms is omitted, the instance default timeout is used (default 30000 ms). An empty file name or empty upload data throws ValueError directly — it is not a link failure.

Accessed through slave.foe (created lazily, always returns an object). Whether a slave supports FoE is queried with slave.foe.is_supported.​

Honest boundaries​

  • Read buffer / file size: read / download return a byte string copied according to the file size reported by the device, not a user buffer of arbitrary size; download additionally has a 64 KiB per-call read limit

Method overview​

CategoryMethodTypeRead/writeDescription
File transferdownloadbytes or Noneread-onlyReads file contents from the slave; returns None on failure. At most 64 KiB per call
uploadboolwrite-onlyWrites file contents to the slave; returns True on success
read / writebytes or None / boolread/writeRaw read and write; the password and timeout must be given explicitly
read_ex / write_exbytes or None / boolread/writeExtended versions that specify CRC and strict mode directly
Asyncdownload_async / upload_asyncbytes or None / boolread/writeasyncio versions of download / upload
read_async / write_asyncbytes or None / boolread/writeasyncio versions of read / write
Transfer progressset_progress_callbackboolwrite-onlyRegisters a per-packet progress callback callback(slave, packet_number, data_size, percent); pass None to clear it
enable_progress_hookboolwrite-onlyEnables the progress hook with an estimated total packet count (used to compute the percentage)
disable_progress_hookboolwrite-onlyDisables the progress hook
estimate_packet_countintread-onlyStatic method; estimates how many data packets the file needs
Cancel / BUSYcancel / clear_cancelboolwrite-onlyRequests that the current transfer be aborted / clears the cancel flag
set_busy_hookboolwrite-onlyReceives BUSY event callbacks while the slave is writing flash

Properties​

CategoryPropertyTypeRead/writeDescription
Configurationdefault_timeout_msintread/writeDefault timeout (milliseconds), default 30000 (30 seconds)
default_timeout_usintread/writeDefault timeout (microseconds); coupled with default_timeout_ms
default_passwordintread/writeDefault password, default 0
Capabilityis_supportedOptional[bool]read-onlyWhether the slave declares FoE: True supported / False confirmed not declared by an actual read of SII General / None the read failed or the evidence is insufficient (not folded into "unsupported")

File transfer​

read()​

def read(self, filename: str, password: int = 0) -> Optional[bytes]

Reads a file from the slave device. The underlying library allocates a buffer and copies according to file_size; it is not a user buffer of arbitrary size.

Parameters:

  • filename (str) — file name to read
  • password (int) — FoE password, default 0

Returns:

  • bytes | None — byte array of the file contents; returns None on failure

Example:

firmware = slave.foe.read("firmware.bin")
config = slave.foe.read("config.xml", password=0x1234)

write()​

def write(self, filename: str, data: bytes, password: int = 0) -> bool

Writes a file to the slave device.

Example:

with open("new_firmware.bin", "rb") as f:
new_firmware = f.read()
success = slave.foe.write("firmware.bin", new_firmware)

download() / upload()​

def download(self, filename: str, password: Optional[int] = None,
timeout_ms: Optional[int] = None,
enable_crc: bool = False) -> Optional[bytes]

def upload(self, filename: str, file_data: bytes,
password: Optional[int] = None,
timeout_ms: Optional[int] = None,
enable_crc: bool = False) -> bool

download reads a file from the slave and upload writes a file to the slave. They correspond to read / write, but the password and timeout fall back to default_password / default_timeout_ms, and CRC is supported:

  • password (int, optional) — FoE password
  • timeout_ms (int, optional) — timeout (milliseconds)
  • enable_crc (bool) — enables CRC checking, handled by the underlying library through the extended read/write flow (upload also enables strict checking and appends the CRC automatically)

An empty file name throws ValueError, and upload additionally rejects empty data. download returns None on failure and upload returns bool.

There are also read_ex / write_ex (which specify the CRC option directly) and download_async / upload_async / read_async / write_async (asyncio versions; the timeout is controlled by the underlying library and no additional asyncio cutoff is applied).

Transfer progress​

set_progress_callback()​

def set_progress_callback(
self, callback: Optional[Callable[[int, int, int, int], None]]) -> bool

Sets the FoE transfer progress callback. Passing None clears it. This is the only progress callback entry point; enable_progress_hook / disable_progress_hook are its low-level switches, and in normal use this method alone is enough.

Callback parameters (4, all supplied at once):

  • slave_index (int) — slave index
  • packet_number (int) — data packet number
  • data_size (int) — number of bytes transferred
  • percent (int) — progress percentage 0..100; -1 when there is no estimated total packet count (unknown, not 0%)

Example:

def on_progress(slave_index, packet_number, data_size, percent):
print(f"\r传输进度: {percent}% (包 {packet_number}, {data_size} 字节)", end="") # \rTransfer progress: {percent}% (packet {packet_number}, {data_size} bytes)

slave.foe.set_progress_callback(on_progress)

enable_progress_hook()​

def enable_progress_hook(self, estimated_total_packets: int = 0) -> bool

Enables the FoE progress hook and passes the estimated total packet count to the callback so it can compute percent (0 = no estimate, and the callback receives percent for -1). It does not need to be called manually once a callback is registered with set_progress_callback(): download / upload take over automatically, and upload also estimates the packet count with estimate_packet_count().

Parameters:

  • estimated_total_packets (int) — estimated total number of data packets (used to compute the progress percentage; 0 = no estimate)

disable_progress_hook()​

def disable_progress_hook(self) -> bool

Disables the FoE progress hook.

estimate_packet_count()​

@staticmethod
def estimate_packet_count(file_size: int, mailbox_size: int = 512) -> int

Estimates the number of data packets required to transfer a file.

Parameters:

  • file_size (int) — file size (bytes)
  • mailbox_size (int) — mailbox size (bytes, default 512)

Example:

from darra_ethercat.slave.foe import FoE

# use a progress callback with percentages
def on_progress(slave_index, packet_number, data_size, percent):
print(f"\r传输进度: {percent}% (包 {packet_number})", end="") # \rTransfer progress: {percent}% (packet {packet_number})

slave.foe.set_progress_callback(on_progress)

with open("new_firmware.bin", "rb") as f:
firmware = f.read()

packets = FoE.estimate_packet_count(len(firmware))
slave.foe.enable_progress_hook(packets)

ok = slave.foe.upload("firmware.bin", firmware)
slave.foe.disable_progress_hook()
print("\n上传完成" if ok else "\n上传失败") # \nUpload complete / \nUpload failed

Error handling​

FoEErrorCode enum​

Error codes defined by the FoE protocol, used to diagnose the cause of transfer failures.

class FoEErrorCode(IntEnum):
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

get_error_description()​

@staticmethod
def get_error_description(error_code: FoEErrorCode) -> str

Gets the Chinese description text of a FoE error code.

last_error_code property​

@property
def last_error_code(self) -> FoEErrorCode

Error code of the most recent FoE operation. On success it is NotDefined (the sentinel value); a failed read / download may report a concrete error code (such as NotFound), while a failed write / upload is always NotDefined, and a timeout is likewise NotDefined.

Example:

from darra_ethercat.data.types import FoEErrorCode
from darra_ethercat.slave.foe import FoE

data = slave.foe.download("firmware.bin")
if data is None:
error = slave.foe.last_error_code
desc = FoE.get_error_description(error)
print(f"下载失败: {desc}") # Download failed: {desc}

Full example​

Firmware update​

if slave.foe.is_supported is not False:   # try for both True / None (unknown); skip only when SII confirms it is not declared
# back up the current firmware
backup = slave.foe.read("firmware.bin")
if backup is not None:
with open("firmware_backup.bin", "wb") as f:
f.write(backup)

# upload the new firmware (with a progress callback)
def on_progress(s, pkt, sz, pct):
print(f"\r更新进度: {pct}% (包 {pkt}, {sz} 字节)", end="") # \rUpdate progress: {pct}% (packet {pkt}, {sz} bytes)
slave.foe.set_progress_callback(on_progress)

with open("new_firmware.bin", "rb") as f:
new_firmware = f.read()
ok = slave.foe.write("firmware.bin", new_firmware)
print("\n固件更新成功" if ok else "\n固件更新失败") # \nFirmware update succeeded / \nFirmware update failed

Configuration file transfer​

if slave.foe.is_supported is not False:
slave.foe.default_password = 0x12345678
slave.foe.default_timeout_ms = 10000 # 10 seconds

# read the configuration
config = slave.foe.read("config.xml")
if config is not None:
xml_content = config.decode("utf-8")
print(f"配置内容:\n{xml_content}") # Configuration content:\n{xml_content}

# write the new configuration
new_config = '<Config><Param1>100</Param1></Config>'
config_bytes = new_config.encode("utf-8")
slave.foe.write("config.xml", config_bytes)

Cancel / BUSY hooks​

Firmware upgrades often take minutes, so the SDK provides two complementary API groups for long transfers:

  • cancel / clear_cancel — actively aborts a FoE transfer in progress
  • set_busy_hook — while the slave is in the flash write phase, receives BUSY frames periodically and invokes the callback (Done/Entire/text)
Difference from set_progress_callback
  • set_progress_callback — fires for every data packet and reflects transfer progress
  • set_busy_hook — fires during the slave flash write phase and reflects device-side processing progress (ETG.1000.6 Table 93 BUSY frames)

FoEBusyEvent​

@dataclass
class FoEBusyEvent:
slave_index: int = 0 # slave index
done: int = 0 # amount completed
entire: int = 0 # total amount
text: str = "" # optional descriptive text returned by the slave
retry_index: int = 0 # BUSY frame retry index

@property
def percent(self) -> float
"""完成百分比 (0..100). entire=0 时返回 0.""" # Completion percentage (0..100). Returns 0 when entire=0.

cancel()​

def cancel(self) -> bool

Requests cancellation of a FoE transfer in progress. It sets the low-level cancel flag and aborts the transfer actively after the mailbox frame currently being awaited completes (on the next loop iteration). Returns False when the underlying library does not support cancellation.

Returns:

  • bool — whether the call succeeded

clear_cancel()​

def clear_cancel(self) -> bool

Clears the FoE cancel flag (used for exceptional resets). Returns False when the underlying library does not support cancellation.

Normally no manual call is needed

The read / write / download / upload entry points clear the cancel flag automatically; use this only in exception / forced-reset scenarios.

set_busy_hook()​

def set_busy_hook(self,
callback: Optional[Callable[[FoEBusyEvent], None]]
) -> bool

Sets the FoE BUSY callback, which receives progress events during download/upload.

Parameters:

  • callback — callback function fn(FoEBusyEvent); pass None to clear the hook

Returns:

  • bool — whether the call succeeded
The callback is triggered synchronously on the underlying mailbox thread

It should return quickly to avoid blocking the processing of subsequent BUSY frames.

Example — synchronous cancellation:

def on_busy(e: FoEBusyEvent):
print(f"\r{e.percent:.1f}% {e.text} (retry={e.retry_index})", end="")

slave.foe.set_busy_hook(on_busy)

# start the upload (on a new thread so it can be cancelled)
import threading
result = [None]
def worker():
result[0] = slave.foe.write("firmware.bin", firmware_bytes)
t = threading.Thread(target=worker, daemon=True)
t.start()

# the user decides to cancel
import time
time.sleep(5)
slave.foe.cancel() # takes effect from the next loop iteration
t.join()
print("\n取消成功" if not result[0] else "\n传输完成") # \nCancel succeeded / \nTransfer complete

Example — asyncio timeout cancellation:

import asyncio

def on_busy(e: FoEBusyEvent):
print(f"{e.percent:.1f}% {e.text}")

slave.foe.set_busy_hook(on_busy)

async def upload_firmware():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(
None, slave.foe.write, "firmware.bin", firmware_bytes
)

task = asyncio.create_task(upload_firmware())
try:
ok = await asyncio.wait_for(task, timeout=60.0)
except asyncio.TimeoutError:
slave.foe.cancel()
ok = False
print("FoE 上传超时, 已请求取消") # FoE upload timed out, cancel requested

Example — clearing the hook:

# clearing after completion is recommended so later transfers do not keep firing the callback
slave.foe.set_busy_hook(None)

Failures and handling​

SymptomCauseHandling
The transfer stalls and BUSY keeps arrivingThe slave is erasing or writing flashKeep waiting and do not resend; resending during BUSY interrupts the write
download returns None after waiting until the timeoutThe mailbox does not respond, or the operation takes longer than timeout_msRaise timeout_ms and retry once; if the file exceeds 64 KiB, raising the timeout has no effect
download returns None and the log reports that the per-call read limit is exceededThe file exceeds the fixed 64 KiB read bufferUse the slave vendor's chunked / large-file read tool; download cannot read it
download returns None and finishes quicklyThe file name does not exist on the slaveCheck the slave file list and the case of the file name
upload returns False and the slave rejects itThe password does not match the slave setting, or the file is write-protectedRetry with the FoE password configured on the slave: slave.foe.upload(..., password=password), or set slave.foe.default_password first, and confirm the file may be written
The call throws ValueError directlyThe file name is empty, or the upload data is emptyPass a non-empty file name and data; this is a parameter error, not a mailbox or link failure

shutdown_foe_async_executor()​

from darra_ethercat.slave.foe import shutdown_foe_async_executor

def shutdown_foe_async_executor(wait: bool = True) -> None

Shuts down the FoE async thread pool. download_async / upload_async / read_async / write_async share this pool (it is separate from the CoE / SoE pools); it is created lazily on the first asynchronous method call, and calling this function before the program exits releases it.

Parameters:

  • wait (bool) — True (the default) waits for the transfers already submitted to finish before shutting down; False returns immediately and unfinished transfers are not guaranteed to complete
Do not wrap up with wait=False during a firmware upgrade

A FoE transfer often takes minutes, so wait=True waits for the current transfer to finish before returning and exiting becomes slower; but passing False and exiting the process interrupts the firmware being written, and the file on the slave may be left in an incomplete state. To exit as soon as possible, call cancel() first to request an abort, wait for the transfer to return, and then shut down.

Pool reclamation only

Idempotent; repeated calls have no side effects; calling an asynchronous method after shutdown lazily recreates the pool. It does not clear the progress callbacks / BUSY callbacks and does not change last_error_code.

Example:

import asyncio
from darra_ethercat.slave.foe import shutdown_foe_async_executor

async def main():
data = await slave.foe.download_async("config.xml")
print(len(data) if data is not None else "读取失败") # Read failed

try:
asyncio.run(main())
finally:
shutdown_foe_async_executor()