Skip to main content

Mailbox gateway

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

Provided by the standalone class darra::ethercat::MailboxGatewayService; construct it directly.​

MailboxGatewayService is a standalone class, not a master member

EtherCATMaster has no member method called MailboxGateway. The mailbox gateway is a standalone MailboxGatewayService class (master/mailbox_gateway.hpp); construct it directly:

using darra::ethercat::MailboxGatewayService;

MailboxGatewayService gw(master.MasterNumber()); // Constructor parameter = master number (from 1; master 1 -> 34980, master 2 -> 34981)
// Master OD / slave mailbox are routed centrally by the underlying gateway, no injected handler callback needed
gw.Start();
ETG.8200 standard

The mailbox gateway service conforms to the ETG.8200 specification, uses the standard UDP port 0x88A4 (34980), and its frame structure fully meets the requirements of Table 1.

Service control​

GetPort / SetPort​

uint16_t GetPort() const;
bool SetPort(uint16_t port); // Called before start, returns false at runtime

UDP port number, 0x88A4 (34980) by default. After the service starts, GetPort() returns the port it is actually bound to.

Multiple instances are offset automatically

The port is offset automatically by the master number passed to the constructor (starting at 1), as 34980 + (N - 1), so that several master instances do not collide:

  • Master 1: 34980 (the default construction = master 1, the ETG.8200 standard port)
  • Master N: 34980 + (N - 1)

The constructor argument is the same value as master.MasterNumber(); pass master.MasterNumber() directly (MasterNumber() starts at 1, 0 means initialization failed and behaves like master 1, landing on 34980). To set the port yourself, call SetPort() before Start() to override the automatic value.

caution

The port number must be set before the service starts. The port cannot be changed while the service is running. The gateway uses strict binding: when the expected port is taken, Start() fails outright (and logs an ERROR), with no automatic fallback and no switch to a system-assigned port. To change the port, call SetPort() explicitly and then Start() again.

SetMasterOdHandler / SetSlaveMailboxHandler are kept but never called

Both injection entry points keep their public signatures and types, so caller source code does not have to change; but the gateway routes the master OD (ETG.1510) and the slave mailbox itself, so the injected handlers are never called. You no longer have to implement master OD responses or slave mailbox forwarding yourself.

IsRunning​

bool IsRunning() const;

Whether the service is running.

Start()​

bool Start();

Starts the mailbox gateway service and begins listening for UDP requests. The expected port is bound strictly: if it is taken the start fails, and no alternate port is tried.

Returns:

  • bool — true when the start succeeds; false when the runtime is not ready or the start fails (master not initialized / port taken / the previous instance has not finished stopping)

Example:

MailboxGatewayService gateway(master.MasterNumber());
gateway.Start();
printf("邮箱网关已启动, 端口: %u\n", gateway.GetPort()); // Mailbox gateway started, port: %u

Stop()​

void Stop();

Stops the mailbox gateway service and releases the UDP port. Start() can be called again afterwards.

Example:

gateway.Stop();

Statistics​

GetStatistics()​

MailboxGatewayStats GetStatistics() const;

Returns a snapshot of the mailbox gateway runtime statistics. The snapshot has 10 fields covering packets sent and received, bytes sent and received, and drop counters.

Return fields (MailboxGatewayStats):

  • RxPackets (uint64_t) — total number of UDP datagrams received
  • TxPackets (uint64_t) — total number of UDP responses sent
  • RxBytes (uint64_t) — cumulative inbound bytes
  • TxBytes (uint64_t) — cumulative outbound bytes
  • MasterOdRequests (uint64_t) — number of requests routed to the master object dictionary (ETG.1510, Address = 0x0000)
  • SlaveRequests (uint64_t) — number of requests routed to a slave mailbox (CoE / SoE / FoE / VoE)
  • DropMalformed (uint64_t) — frames dropped for a malformed format
  • DropTimeout (uint64_t) — frames dropped because the slave response timed out (taken from the runtime timeout counter)
  • DropHandlerError (uint64_t) — always 0 (the gateway runs no user callbacks, so there is no "callback threw" path)
  • DropInternalError (uint64_t) — always 0 (same as above, no user callbacks)

Example:

auto stats = gateway.GetStatistics();
printf("Mailbox Gateway 运行 %llu req / %llu resp\n", // Mailbox Gateway running %llu req / %llu resp
(unsigned long long)stats.RxPackets,
(unsigned long long)stats.TxPackets);
printf(" Master OD: %llu, Slave 邮箱: %llu\n", // Master OD: %llu, Slave mailbox: %llu
(unsigned long long)stats.MasterOdRequests,
(unsigned long long)stats.SlaveRequests);
printf(" 丢弃: 格式错=%llu, 超时=%llu\n", // Dropped: bad format=%llu, timeout=%llu
(unsigned long long)stats.DropMalformed,
(unsigned long long)stats.DropTimeout);

Supported protocols​

ProtocolTypeDescription
CoE0x03SDO read and write, for both the master (ETG.1510) and the slave object dictionaries
SoE0x04IDN parameter read and write (ETG.1020 standard)
FoE0x05File transfer (single-packet only at present)
VoE0x0FVendor-specific protocol pass-through
Address routing
  • Address = 0x0000 -> access the master object dictionary (CoE only)
  • Address = slave station address -> pass-through to the corresponding slave (CoE / SoE / FoE / VoE)

Frame structure​

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​

Scenario A — integrate an existing configuration or debugging tool​

Let a third-party configuration tool (or an engineer's tool) access the master and slave object dictionaries over UDP without changing the firmware of the controlled devices.

Scenario B — custom diagnostics or automation scripts​

Collect slave parameters periodically, read objects in bulk or perform remote configuration from a script or service.

Scenario C — remote monitoring and alarm collection​

Use the gateway for remote passive monitoring (periodic reads or subscriptions) and report key data to a central monitoring system.

Starting the gateway yourself​

#include "ethercat.hpp"
using namespace darra::ethercat;

int main() {
EtherCATMaster master(dll);
master.SetENI("config.deni").Build(); // SetENI (uppercase), chained Build
master.SetState(EcState::OP);

MailboxGatewayService gateway(master.MasterNumber());
// gateway.SetPort(12345); // defaults to 34980; change it before Start if needed
// Master OD / slave mailbox are routed centrally by the underlying gateway, no injected handler callback needed
gateway.Start();
printf("邮箱网关已启动, 端口: %u\n", gateway.GetPort()); // Mailbox gateway started, port: %u

getchar();

gateway.Stop();
Close(master); // The Close free function from initialise.hpp
return 0;
}

External code example (C++)​

#include <cstdint>
#include <cstring>
#include <vector>
#include <string>
#include <stdexcept>

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif

class MailboxGatewayClient {
public:
MailboxGatewayClient(const std::string& host = "127.0.0.1", uint16_t port = 0x88A4)
: host_(host), port_(port) {
sock_ = socket(AF_INET, SOCK_DGRAM, 0);
addr_.sin_family = AF_INET;
addr_.sin_port = htons(port);
inet_pton(AF_INET, host.c_str(), &addr_.sin_addr);
}
~MailboxGatewayClient() { if (sock_ >= 0) close(sock_); }

std::vector<uint8_t> SendRequest(uint16_t address, uint8_t mailboxType,
const std::vector<uint8_t>& mailboxData) {
auto frame = BuildFrame(address, mailboxType, mailboxData);
sendto(sock_, reinterpret_cast<const char*>(frame.data()),
(int)frame.size(), 0,
reinterpret_cast<sockaddr*>(&addr_), sizeof(addr_));

std::vector<uint8_t> resp(4096);
sockaddr_in from{}; socklen_t flen = sizeof(from);
int n = recvfrom(sock_, reinterpret_cast<char*>(resp.data()),
(int)resp.size(), 0,
reinterpret_cast<sockaddr*>(&from), &flen);
if (n <= 0) throw std::runtime_error("recvfrom failed");
resp.resize(n);
return resp;
}

// CoE SDO Upload (read from the object dictionary)
std::vector<uint8_t> CoeSdoRead(uint16_t address, uint16_t index, uint8_t subindex) {
std::vector<uint8_t> coData(8, 0);
coData[1] = 0x20; // CoE Type: SDO Request
coData[2] = 0x40; // SDO Upload (Read)
std::memcpy(&coData[3], &index, 2);
coData[5] = subindex;
return SendRequest(address, 0x03, coData);
}

// CoE SDO Download (write to the object dictionary)
std::vector<uint8_t> CoeSdoWrite(uint16_t address, uint16_t index, uint8_t subindex,
const std::vector<uint8_t>& value) {
std::vector<uint8_t> coData(6 + value.size(), 0);
coData[1] = 0x20;
coData[2] = 0x20; // SDO Download (Write)
std::memcpy(&coData[3], &index, 2);
coData[5] = subindex;
std::memcpy(&coData[6], value.data(), value.size());
return SendRequest(address, 0x03, coData);
}

// SoE Read (read IDN parameters)
std::vector<uint8_t> SoeRead(uint16_t address, uint16_t idn,
uint8_t driveNo = 0, uint8_t element = 0x05) {
std::vector<uint8_t> soe(4, 0);
soe[0] = 0x01; // OpCode: Read
soe[1] = static_cast<uint8_t>((driveNo << 3) | (element & 0x07));
std::memcpy(&soe[2], &idn, 2);
return SendRequest(address, 0x04, soe);
}

// FoE Read (download a file from the slave, single packet only)
std::vector<uint8_t> FoeRead(uint16_t address, const std::string& filename) {
std::string name = filename + '\0';
std::vector<uint8_t> foe(5 + name.size(), 0);
foe[0] = 0x01; // OpCode: Read Request
std::memcpy(&foe[5], name.data(), name.size());
return SendRequest(address, 0x05, foe);
}

// VoE send/receive (vendor-specific protocol)
std::vector<uint8_t> VoeSendReceive(uint16_t address, uint32_t vendorId,
uint16_t vendorType,
const std::vector<uint8_t>& data) {
std::vector<uint8_t> voe(6 + data.size(), 0);
std::memcpy(&voe[0], &vendorId, 4);
std::memcpy(&voe[4], &vendorType, 2);
std::memcpy(&voe[6], data.data(), data.size());
return SendRequest(address, 0x0F, voe);
}

private:
std::vector<uint8_t> BuildFrame(uint16_t address, uint8_t mailboxType,
const std::vector<uint8_t>& mailboxData) {
uint16_t mbLen = static_cast<uint16_t>(mailboxData.size());
uint16_t ecatLen = 6 + mbLen;
uint16_t ecatHeader = static_cast<uint16_t>((0x05 << 12) | (ecatLen & 0x07FF));

std::vector<uint8_t> frame(2 + 6 + mbLen, 0);
std::memcpy(&frame[0], &ecatHeader, 2);
std::memcpy(&frame[2], &mbLen, 2);
std::memcpy(&frame[4], &address, 2);
frame[6] = 0x00;
frame[7] = static_cast<uint8_t>(mailboxType << 4);
std::memcpy(&frame[8], mailboxData.data(), mbLen);
return frame;
}

std::string host_;
uint16_t port_;
int sock_ = -1;
sockaddr_in addr_{};
};

// --- Usage example ---
// MailboxGatewayClient client("192.168.1.100");
// auto resp = client.CoeSdoRead(0x0000, 0x1018, 0x01); // master OD
// resp = client.CoeSdoRead(0x03E9, 0x6040, 0x00); // slave OD
// resp = client.SoeRead(0x03E9, 32); // slave IDN
// resp = client.FoeRead(0x03E9, "firmware.bin"); // file

Notes​

Network security

By default the gateway passes traffic straight through, which allows network access to the complete object dictionaries of the master and the slaves. Recommendations:

  • Use it only on a controlled network, or restrict access with an IP allow list or a VPN tunnel
  • Combine it with operating-system firewall rules and allow only trusted source IP addresses
  • 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 very little effect on main-loop performance. A large number of synchronous SDO or mailbox operations can still affect overall latency, so limit concurrency and rate sensibly.

Sending, receiving and forwarding of requests all happen on the gateway's listener thread; slave response timeouts are handled by the gateway against its own budget and counted in DropTimeout, so the C++ class no longer takes a timeout parameter.

Protocol details​

CoE (CAN over EtherCAT)​

Supported operations:

  • SDO Upload (0x40) - read the object dictionary
  • SDO Download (0x20) - write the object dictionary
  • SDO Abort (0x80) - error response

SoE (Servo over EtherCAT)​

Supported operations:

  • IDN Read (0x01) - read an IDN parameter
  • IDN Write (0x02) - write an IDN parameter

Supported elements:

  • Value (0x05) - parameter value
  • Name (0x00) - parameter name
  • Attribute (0x01) - parameter attributes
  • Unit (0x02) - unit
  • Min/Max (0x03/0x04) - minimum/maximum value
  • Default (0x06) - default value
  • Data Type (0x07) - data type

FoE (File over EtherCAT)​

Supported operations:

  • Read Request (0x01) - file download request
  • Write Request (0x02) - file upload preparation
  • Data (0x03) - file data transfer
  • Ack (0x04) - acknowledgement
  • Error (0x05) - error response

Current limits:

  • only single-packet file transfer is supported (small files)
  • a complete segmented transfer requires session state management (a future version)

VoE (Vendor over EtherCAT)​

Frame format:

  • VendorID (4 bytes) - vendor identifier
  • VendorType (2 bytes) - vendor type
  • Data (n bytes) - vendor-specific data

Functions:

  • full pass-through to the slave VoE interface
  • handles requests and responses automatically
  • supports data of any length