FoE (File over EtherCAT)
FoE 协议用于 EtherCAT 从站的文件传输,支持固件更新、配置文件上传下载等场景。
通过 slave.FoE 访问。从站不支持 FoE 时为 null。
属性
| 属性 | 类型 | 访问 | 说明 |
|---|---|---|---|
| DefaultTimeoutMs | int | 读写 | 默认超时时间(毫秒),默认 5000(5秒) |
| DefaultPassword | uint | 读写 | 默认密码,默认 0 |
文件传输
Download(string filename, uint? password = null, int? timeoutMs = null, bool enableCrc = false)
public byte[]? Download(string filename, uint? password = null, int? timeoutMs = null, bool enableCrc = false)
从从站设备下载(读取)文件。
参数:
filename(string) — 要下载的文件名password(uint?) — FoE 密码(不指定则使用DefaultPassword)timeoutMs(int?) — 超时时间(毫秒,不指定则使用DefaultTimeoutMs)enableCrc(bool) — 启用 CRC32 校验(自动验证数据完整性)
返回值:
byte[]?— 文件内容字节数组,失败返回null
示例:
// 基本下载
byte[]? firmware = slave.FoE.Download("firmware.bin");
// 启用 CRC 校验
byte[]? config = slave.FoE.Download("config.xml", enableCrc: true);
Upload(string filename, byte[] fileData, uint? password = null, int? timeoutMs = null, bool enableCrc = false)
public bool Upload(string filename, byte[] fileData, uint? password = null, int? timeoutMs = null, bool enableCrc = false)
上传(写入)文件到从站设备。
参数:
filename(string) — 要上传的文件名fileData(byte[]) — 要写入的文件数据password(uint?) — FoE 密码(不指定则使用DefaultPassword)timeoutMs(int?) — 超时时间(毫秒,不指定则使用DefaultTimeoutMs)enableCrc(bool) — 启用 CRC32 校验(自动附加校验信息)
返回值:
bool— 成功返回true
示例:
// 基本上传
byte[] newFirmware = File.ReadAllBytes("new_firmware.bin");
bool success = slave.FoE.Upload("firmware.bin", newFirmware);
// 启用 CRC 校验
bool ok = slave.FoE.Upload("firmware.bin", newFirmware, enableCrc: true);
进度事件
ProgressChanged
public event EventHandler<FoEProgressEventArgs>? ProgressChanged;
FoE 传输进度事件。订阅后,Download / Upload 操作会自动触发进度报告。
相关结构:
Slave(ushort) — 从站编号PacketNumber(int) — 数据包序号DataSize(int) — 数据大小(字节)ProgressPercent(int) — 估算的进度百分比 (0-100)
示例:
slave.FoE.ProgressChanged += (sender, e) =>
{
Console.Write($"\r传输进度: {e.ProgressPercent}% (包 {e.PacketNumber})");
};
byte[] firmware = File.ReadAllBytes("new_firmware.bin");
bool success = slave.FoE.Upload("firmware.bin", firmware, enableCrc: true);
Console.WriteLine(success ? "\n上传完成!" : "\n上传失败!");
完整示例
固件更新
if (slave.FoE)
{
// 备份当前固件
byte[]? backup = slave.FoE.Download("firmware.bin");
if (backup != null)
File.WriteAllBytes("firmware_backup.bin", backup);
// 上传新固件(带进度和 CRC 校验)
slave.FoE.ProgressChanged += (s, e) =>
Console.Write($"\r更新进度: {e.ProgressPercent}%");
byte[] newFirmware = File.ReadAllBytes("new_firmware.bin");
bool ok = slave.FoE.Upload("firmware.bin", newFirmware, enableCrc: true);
Console.WriteLine(ok ? "\n固件更新成功" : "\n固件更新失败");
}
配置文件传输
if (slave.FoE)
{
slave.FoE.DefaultPassword = 0x12345678;
slave.FoE.DefaultTimeoutMs = 10000; // 10秒
// 读取配置
byte[]? config = slave.FoE.Download("config.xml");
if (config != null)
{
string xmlContent = System.Text.Encoding.UTF8.GetString(config);
Console.WriteLine($"配置内容:\n{xmlContent}");
}
// 写入新配置
string newConfig = "<Config><Param1>100</Param1></Config>";
byte[] configBytes = System.Text.Encoding.UTF8.GetBytes(newConfig);
slave.FoE.Upload("config.xml", configBytes);
}