Skip to main content

Mailbox Gateway

The mailbox gateway implements the ETG.8200 standard and lets external diagnostic tools access the object dictionary of the EtherCAT master and slaves over UDP/IP.

The C SDK product API lives in master/gateway.h and consists of gateway_create / gateway_start / gateway_stop / gateway_get_statistics. The header can be pulled in through the ethercat.h umbrella header (ethercat.h already does #include "master/gateway.h"), or included directly as master/gateway.h; the gateway_* symbols come from the advanced static library rather than the public export surface. UDP listening, frame parsing, master OD / slave mailbox routing, Discovery and statistics are all handled by the gateway service, and the SDK does not start a server of its own; starting the same master again is idempotent.

Not mailbox_gateway.h

master/mailbox_gateway.h is the register / SM / FMMU / watchdog entry point, not the ETG.8200 UDP gateway.

ETG.8200 standard

The mailbox gateway service conforms to the ETG.8200 standard and uses the standard UDP port 0x88A4 (34980); the frame structure follows Table 1 exactly.

Service control​

DarraGateway* gateway_create(uint16_t masterNumber);
void gateway_destroy(DarraGateway* gw);
int gateway_set_port(DarraGateway* gw, uint16_t port);
uint16_t gateway_get_port(const DarraGateway* gw);
int gateway_start(DarraGateway* gw);
void gateway_stop(DarraGateway* gw);
bool gateway_is_running(const DarraGateway* gw);
  • gateway_create() creates a gateway instance; masterNumber is the master number (starting at 1, the same value Initialize() returns) and the default port is 0x88A4 + (N - 1); returns a handle (NULL = allocation failed)
  • gateway_set_port() must be called before starting; returns 0 on success and -1 if the gateway is already running
  • gateway_start() starts UDP listening (the background thread is managed by the gateway service); returns 0 on success, -1 when the start fails (master not initialized / port already taken / the previous instance has not finished stopping), and -2 when it is already running
  • gateway_destroy() destroys the instance (if the service is still running it is stopped automatically)
Multiple instance ports

Ports are offset automatically by master number (starting at 1): master N = 34980 + (N - 1) (master 1 = 34980; passing 0 means an uninitialized master and behaves like master 1). The gateway service uses strict binding: if the port is taken the start fails, with no automatic port switch and no fallback to a system-assigned port.

Port policy​

Default port 0x88A4 (34980), master 1 → 34980
Master N: 34980 + (N - 1)

When the port is taken, gateway_start() fails honestly instead of silently switching ports. While running, gateway_get_port() returns the port the gateway service is actually bound to; when it is not running it returns the port expected on the next start.

Protocol callbacks​

typedef int (*DarraGatewayMasterOdCallback)(uint8_t mbxType,
const uint8_t* request, int requestLen,
uint8_t* responseBuf, int responseBufSize, void* user);

typedef int (*DarraGatewaySlaveCallback)(uint16_t slaveAddr, uint8_t mbxType,
const uint8_t* request, int requestLen,
uint8_t* responseBuf, int responseBufSize, void* user);

void gateway_set_master_od_callback(DarraGateway* gw,
DarraGatewayMasterOdCallback cb, void* user);
void gateway_set_slave_callback(DarraGateway* gw,
DarraGatewaySlaveCallback cb, void* user);
Both callback entry points are kept but never invoked again

The public signatures and types of gateway_set_master_od_callback() / gateway_set_slave_callback() are kept, but the gateway now routes master OD (ETG.1510) and slave mailboxes uniformly, so the SDK no longer dispatches callbacks. A registered callback is never invoked (gateway_start() writes a log entry saying so); there is no need to implement master OD responses or slave mailbox forwarding yourself. Whether a request succeeded, and why it was dropped, is visible through the statistics interface.

  • Master object dictionary requests: routed directly to the master OD when Address == 0x0000, without going through a callback
  • Slave mailbox requests: forwarded directly to the target slave when Address != 0x0000, without going through a callback

Statistics​

typedef struct {
uint64_t rxPackets; /* number of UDP packets received */
uint64_t txPackets; /* number of response packets sent */
uint64_t rxBytes; /* number of bytes received */
uint64_t txBytes; /* number of bytes sent */
uint64_t masterOdRequests; /* number of requests routed to the master OD */
uint64_t slaveRequests; /* number of requests routed to a slave mailbox */
uint64_t dropMalformed; /* dropped because of a malformed frame */
uint64_t dropTimeout; /* dropped because processing timed out */
} DarraGatewayStats;

void gateway_get_statistics(const DarraGateway* gw, DarraGatewayStats* outStats);
void gateway_reset_statistics(DarraGateway* gw);

get_statistics takes a single atomic copy; reset_statistics clears all counters without affecting the running state.

Diagnostics-friendly

The statistic field names and semantics are fixed, so diagnostic scripts can parse them by field name directly.

Supported protocols​

ProtocolType byteDescription
CoE0x03SDO read/write, for both the master (ETG.1510) and slave object dictionaries
SoE0x04IDN parameter read/write (ETG.1020 standard)
FoE0x05File transfer (single packet only at present)
VoE0x0FVendor-specific protocol pass-through

Address routing rules:

  • Address 0x0000 → master object dictionary (CoE only)
  • Address = slave station address → pass-through to that slave (CoE / SoE / FoE / VoE)

Frame structure​

EtherCAT Header (2B): Length(11bit) + Type=0x05
Mailbox Header (6B): Length(2) + Address(2) + channel+priority(1) + type+counter(1)
Data (NB): protocol payload

EtherCAT Header:

  • Length: total length of Mailbox Header + Data
  • Data Type: fixed at 0x05 (Mailbox communication)

Mailbox Header:

  • Length: length of the mailbox data part
  • Address: 0x0000 = master, anything else = slave station address
  • Type: 0x03=CoE, 0x04=SoE, 0x05=FoE, 0x0F=VoE
  • Cnt: mailbox counter (cycles 1-7)

Full example​

Starting the gateway yourself​

#include "master/gateway.h"

int main(void) {
DarraGateway* gw = gateway_create(1);
gateway_set_port(gw, 0x88A4);

/* master OD / slave mailboxes are routed by the gateway service; no callbacks need to be injected. */

if (gateway_start(gw) != 0) {
fprintf(stderr, "网关启动失败\n"); /* Gateway start failed */
gateway_destroy(gw);
return 1;
}

/* ... main loop ... */

DarraGatewayStats s;
gateway_get_statistics(gw, &s);
printf("rx=%llu tx=%llu master_od=%llu drop=%llu\n",
(unsigned long long)s.rxPackets, (unsigned long long)s.txPackets,
(unsigned long long)s.masterOdRequests,
(unsigned long long)(s.dropMalformed + s.dropTimeout));

gateway_stop(gw);
gateway_destroy(gw);
return 0;
}

External code example (C client)​

#include <winsock2.h>

/* ETG.8200 frame: EtherCAT Header (2) + Mailbox Header (6) + Data */
static int build_frame(uint8_t* frame, uint16_t address, uint8_t mbx_type,
const uint8_t* mbx_data, uint16_t mbx_len)
{
uint16_t ecat_len = 6 + mbx_len;
/* EtherCAT Header: Length[10:0] | DataType[15:12]=0x05 */
*(uint16_t*)(frame + 0) = (uint16_t)((0x05 << 12) | (ecat_len & 0x07FF));
*(uint16_t*)(frame + 2) = mbx_len;
*(uint16_t*)(frame + 4) = address;
frame[6] = 0x00; /* Channel + Priority */
frame[7] = (uint8_t)(mbx_type << 4); /* Type[7:4] */
memcpy(frame + 8, mbx_data, mbx_len);
return 8 + mbx_len;
}

/* CoE SDO Upload: address=0x0000 = master OD, anything else = slave */
int coe_sdo_read(SOCKET sock, uint16_t address, uint16_t index, uint8_t subindex,
uint8_t* resp, int resp_cap)
{
uint8_t co_data[8] = {0};
co_data[1] = 0x20; /* CoE Type: SDO Request */
co_data[2] = 0x40; /* SDO Upload (Read) */
*(uint16_t*)(co_data + 3) = index;
co_data[5] = subindex;

uint8_t frame[64];
int n = build_frame(frame, address, 0x03 /* CoE */, co_data, sizeof(co_data));
/* sendto + recvfrom omitted */
return n;
}

Error handling​

ProtocolError typeError code
CoEObject does not exist0x06020000
CoEUnsupported access0x06010000
CoEWrite protection0x06010002
CoECommand not implemented0x05040001
SoEIDN does not exist0x1009
SoEWrite failed0x7002
FoEFile not found0x00008001
FoEInvalid file name0x00008003
VoENo response0x0003

Notes​

Network security

By default the gateway is a full pass-through and allows network access to the complete object dictionary of the master and the slaves. Recommendations:

  • Always use it in a controlled network, or restrict access with IP filtering / a VPN tunnel
  • Combine it with operating system firewall rules and allow only trusted source IPs
  • Enable it with care in production and do not expose it to the public internet
Performance impact

The mailbox gateway runs on its own thread and has minimal impact on main loop performance. Large numbers of synchronous SDO or mailbox operations can still affect overall latency, so limit concurrency and rate sensibly.

Limits​

Implemented:

  • Full CoE pass-through / SoE IDN parameter access / FoE single-packet file transfer / VoE vendor protocol pass-through
  • Master object dictionary access + slave mailbox pass-through
  • Error handling and error code mapping

Not implemented yet:

  • FoE segmented transfer (large file support)
  • Address mapping table (+0x8000 virtual mapping)
  • Multicast/broadcast requests
  • Session state management

Asynchronous mailbox transactions (slave/mbx_registry.h)​

slave/mbx_registry.h provides a set of non-blocking mailbox transaction APIs: the caller submits a mailbox transaction (any CoE/SoE/FoE/AoE/VoE/FSoE protocol frame) and immediately gets a ticket, then waits for, cancels or collects the result asynchronously. This suits scenarios that need to submit several mailbox operations concurrently or that must not block the current thread.

Difference from the mailbox gateway

The mailbox gateway (above) is an ETG.8200 UDP routing service aimed at external diagnostic tools. Asynchronous mailbox transactions serve mailbox communication initiated by the application itself; the two are unrelated.

Transaction status enum​

typedef enum {
EC_MBX_STATUS_PENDING = 0, /* pending / not yet submitted */
EC_MBX_STATUS_SUCCESS = 1, /* success */
EC_MBX_STATUS_TIMEOUT = -1, /* timeout */
EC_MBX_STATUS_CANCELLED = -2, /* cancelled */
EC_MBX_STATUS_MBX_ERROR = -3, /* peer returned a mailbox Error frame */
EC_MBX_STATUS_PROTO_MISMATCH = -4, /* response protocol type mismatch */
/* -5 reserved slot: this status never occurs (the mailbox Rx counter
* is an independent slave-send counter and has no pairing with the request Tx counter) */
EC_MBX_STATUS_WKC_FAIL = -6, /* underlying wkc <= 0 */
EC_MBX_STATUS_NO_MEMORY = -7, /* buffer allocation failed */
EC_MBX_STATUS_INVALID_ARG = -8, /* invalid argument */
EC_MBX_STATUS_NOT_IMPL = -9, /* not implemented */
EC_MBX_STATUS_LINK_DOWN = -10, /* link down: frames fail immediately instead of timing out one by one; check the cable / NIC link status */
EC_MBX_STATUS_NOT_SENT = -11 /* request never left locally (frame never reached the wire: aborted / backed off / pool empty / channel closed / held by the kernel);
* not a slave timeout and not a slave rejection — no bus evidence at all,
* never use it for slave-drop / link-health verdicts; treat it as retryable by the caller */
} ec_mbx_status_t;

Transaction structure​

/* natural alignment (x64), 72 bytes total — never #pragma pack(1) */
typedef struct {
/* ---- input fields (filled by the caller) ---- */
uint16_t slave; /* slave index (1-based) */
uint8_t protocol_type; /* MBXPROT_* (AOE=0x01/EOE=0x02/COE=0x03/FOE=0x04/SOE=0x05/VOE=0x0F/FSOE=0x10/PDO=0x11) */
uint8_t reserved0;
uint32_t timeout_us; /* total timeout (microseconds); 0 = default */
volatile int cancel_flag; /* set to 1 by the caller to request cancellation */
void* request_frame; /* request frame buffer (including the 6-byte MbxHeader) */
uint16_t request_len; /* valid request length */
uint16_t reserved1;
void* response_frame; /* response frame buffer (allocated by the caller) */
uint16_t response_cap; /* writable response capacity */
uint16_t response_len; /* output: actual response length */
/* ---- output fields ---- */
ec_mbx_status_t status; /* final status */
uint32_t error_code; /* protocol-specific error code */
uint8_t response_counter; /* counter of the response actually received */
uint8_t reserved2[3];
uint64_t submit_time_us; /* submission time */
uint64_t complete_time_us; /* completion time */
} ec_mbx_transaction_t;

Statistics structure​

/* natural alignment (x64), 72 bytes total — never #pragma pack(1) */
typedef struct {
uint64_t total_sent; /* total transactions sent */
uint64_t total_received; /* total responses received successfully */
uint64_t total_timeout; /* total timeouts */
uint64_t total_mbx_error; /* total mailbox error frames */
uint64_t total_proto_error; /* total protocol mismatches */
uint64_t total_cancelled; /* total cancellations */
uint32_t last_error_code; /* last protocol error code */
uint64_t last_error_time_us; /* time of the last error (microseconds) */
uint64_t total_latency_us; /* accumulated latency; average = total_latency_us / total_received */
} ec_mbx_stats_t;

API​

/* query per-slave / per-protocol mailbox statistics (protocol_type=0 aggregates all protocols) */
int ec_mbx_get_stats(uint16_t master_index, uint16_t slave,
uint8_t protocol_type, ec_mbx_stats_t* out_stats);

/* reset mailbox statistics (protocol_type=0 clears all protocols) */
void ec_mbx_reset_stats(uint16_t master_index, uint16_t slave,
uint8_t protocol_type);

/* submit a mailbox transaction asynchronously, returning a ticket */
int ec_mbx_submit_async(uint16_t master_index, ec_mbx_transaction_t* txn,
uint32_t* out_ticket);

/* wait for an asynchronous mailbox transaction to complete */
int ec_mbx_wait(uint16_t master_index, uint32_t ticket, int timeout_ms);

/* cancel an asynchronous mailbox transaction */
int ec_mbx_cancel(uint16_t master_index, uint32_t ticket);

/* fetch a snapshot of the complete result of an asynchronous mailbox transaction */
int ec_mbx_get_result(uint16_t master_index, uint32_t ticket,
ec_mbx_transaction_t* out_txn);

All functions take the master index directly (no handle, no function-pointer table). When the SDK provides no entry point for a call, it safely returns EC_MBX_STATUS_NOT_IMPL instead of crashing.

Structure packing

ec_mbx_transaction_t / ec_mbx_stats_t must use x64 natural alignment (72 bytes each) and must never be wrapped in #pragma pack(1). The SDK headers already declare them correctly, so just #include "slave/mbx_registry.h" and do not redefine them.

Example:

#include "slave/mbx_registry.h"

uint8_t req[64], resp[256];
/* ... build a 6-byte MbxHeader + CoE SDO request in req ... */

ec_mbx_transaction_t txn = {0};
txn.slave = 1;
txn.protocol_type = MBXPROT_COE; /* 0x03 */
txn.timeout_us = 1000000; /* 1s */
txn.request_frame = req;
txn.request_len = 14;
txn.response_frame = resp;
txn.response_cap = sizeof(resp);

uint32_t ticket = 0;
if (ec_mbx_submit_async(master, &txn, &ticket) == EC_MBX_STATUS_SUCCESS) {
if (ec_mbx_wait(master, ticket, 2000) == EC_MBX_STATUS_SUCCESS) {
ec_mbx_transaction_t result = {0};
ec_mbx_get_result(master, ticket, &result);
printf("响应 %u 字节, status=%d\n", result.response_len, result.status); /* Response %u bytes, status=%d */
}
}

/* query mailbox statistics */
ec_mbx_stats_t st = {0};
if (ec_mbx_get_stats(master, 1, 0, &st) == 0) {
printf("发送=%llu 接收=%llu 超时=%llu\n", /* sent=%llu received=%llu timeouts=%llu */
(unsigned long long)st.total_sent,
(unsigned long long)st.total_received,
(unsigned long long)st.total_timeout);
}