Skip to main content

Mailbox Gateway

The mailbox gateway implements the ETG.8200 standard, allowing external diagnostic tools to access the object dictionaries of the EtherCAT master and slaves over UDP/IP. MailboxGatewayService is a product API, exported by the package __all__, and accessed through master.mailbox_gateway.

Single instance

A master has only one mailbox gateway instance. Start it once through master.mailbox_gateway; do not create a second service object (the ports would conflict).

ETG.8200 standard

The mailbox gateway service complies with the ETG.8200 standard specification, uses the standard UDP port 0x88A4 (34980), and its frame layout fully meets the Table 1 requirements.

Service control​

port​

@property
def port(self) -> int

@port.setter
def port(self, value: int) -> None

UDP port number. Default port = ETG.8200 base port 34980 (0x88A4) + (master index - 1), so master 1 is 34980. While running, reading this property returns the actual listening port; while not running it returns the configured port. Assignment range 0-65535; an out-of-range value raises ValueError.

Port and failure

The port number must be set before the service starts. The port cannot be changed while the service is running (assigning while running raises RuntimeError).

start() tries the available ports; when none is available it raises OSError — there is no fallback to a system-assigned ephemeral port. The ETG.8200 standard port should be used exclusively; do not rely on "any random port will work".

is_running​

@property
def is_running(self) -> bool

Whether the service is running. Returns False when the SDK is unavailable; does not raise.

start()​

def start(self) -> None

Start the mailbox gateway service and begin listening for UDP requests. Idempotent: returns directly if already running; it does not start twice.

Starting from the configured port, it tries preferred + 0 .. +9, 10 candidate ports in total, logging a warning for each fallback; the actual listening port is finally the one read back from port. When all 10 candidates fail to bind it raises OSError (there is no system-assigned port fallback, see the section above). When the SDK does not support this capability it raises RuntimeError and does not pretend to succeed.

Example:

gateway = master.mailbox_gateway
gateway.start()
print(f"邮箱网关已启动,端口: {gateway.port}") # Mailbox gateway started, port: {gateway.port}

stop()​

def stop(self) -> None

Stop the mailbox gateway service. On stop it first stops accepting new requests, waits for in-flight requests to finish, and drains within a single 2-second overall deadline; if the deadline expires before this stop completes, stop() can be called again to retry.

  • the service was not running, or the SDK is unavailable → treated as an idempotent no-op
  • stop failed → only logs a WARNING, does not raise (the caller must re-check is_running itself)
  • after stopping, start() can be called again

Example:

master.mailbox_gateway.stop()
if master.mailbox_gateway.is_running:
print("网关仍在运行(drain 未完成),稍后重试 stop()") # Gateway still running (drain not finished); retry stop() later

Runtime statistics​

get_statistics() / reset_statistics()​

def get_statistics(self) -> MailboxGatewayStats
def reset_statistics(self) -> None

get_statistics() returns a snapshot of the gateway statistics; reset_statistics() zeroes the counters and keeps the port / running-state fields. On a failed read it returns a fallback object with only udp_port / is_running filled in (and logs a WARNING); it does not raise.

The statistics fields are as follows:

CategoryFieldTypeRead/writeDescription
Trafficrx_packets / rx_bytesintread-onlyNumber of UDP datagrams received / bytes received
tx_packets / tx_bytesintread-onlyNumber of UDP responses sent / bytes sent
Forwardingforwarded_okintread-onlySuccessfully forwarded to the slave and a response was received
forwarded_failedintread-onlyForwarding failed (send / receive error)
Dropstimeout_countintread-onlySlave response timeout
invalid_frameintread-onlyInvalid frame format / illegal length
unknown_targetintread-onlyAddress points to a slave that does not exist
unsupported_typeintread-onlyUnsupported mailbox protocol type
Routingmaster_requestsintread-onlyNumber of master OD requests with Address=0
master_od_requestsintread-onlySame source as master_requests (the same counter, identical)
slave_requestsintread-onlyDerived value (forwarded_ok + forwarded_failed) - master_requests (negative values count as 0)
drop_malformedintread-onlyAlias of invalid_frame (identical)
drop_timeoutintread-onlyAlias of timeout_count (identical)
TCPtcp_connections / tcp_activeintread-onlyTotal number of TCP connections accepted / number of currently active connections
tcp_portintread-onlyTCP listening port (0 = not started)
tcp_runningboolread-onlyWhether the TCP listener is running
Discoverydiscovery_requestsintread-onlyTotal number of Ping / List / Set / Get service requests
selected_masterintread-onlyMaster index selected by Discovery
Statusudp_portintread-onlyCurrent UDP port
is_runningboolread-onlyWhether the UDP service is running
Cross-language alignment fields are not independent measurements

master_od_requests / slave_requests / drop_malformed / drop_timeout are all mapped from gateway counters (aliases or derived values), not a second set of independent metrics. Do not add them together with master_requests / forwarded_* / invalid_frame / timeout_count when computing statistics.

Supported protocols​

Protocol routing and frame forwarding are handled uniformly by the gateway; the Python side implements neither frame parsing nor protocol routing (the single-packet / fragmented limits of the old local implementation no longer apply).

ProtocolTypeDescription
CoE0x03SDO read/write, supports the master (ETG.1510) and slave object dictionaries
AoE0x01ADS over EtherCAT pass-through
SoE0x05IDN parameter read/write (ETG.1020 standard)
FoE0x04File transfer frames are forwarded by the gateway
VoE0x0FVendor-specific protocol pass-through
Address routing and EoE
  • Address = 0x0000 → access the master object dictionary (CoE only; other types return a mailbox error frame)
  • Address = slave station address → forward to the corresponding slave (CoE / AoE / SoE / FoE / VoE)
  • EoE (0x02) does not go through the Gateway (ETG.8200 §4.1); returns a "protocol not supported" error frame

Async mailbox transactions​

MailboxTransaction provides single mailbox transaction execution; the SDK handles submission, waiting and result retrieval. It is intended for scenarios that need to submit a whole mailbox frame (including the 6-byte MbxHeader) and wait for the result.

Module location

MailboxTransaction is in the darra_ethercat.abstractions subpackage, not in the top-level darra_ethercat namespace. For regular CoE/SoE/FoE reads and writes prefer the protocol interfaces such as slave.coe / slave.soe; this API is for custom mailbox frame pass-through.

MailboxStatus enum​

from darra_ethercat.abstractions import MailboxStatus

class MailboxStatus(IntEnum):
PENDING = 0 # transaction pending
SUCCESS = 1 # transaction succeeded
TIMEOUT = -1 # timeout
CANCELLED = -2 # cancelled
MAILBOX_ERROR = -3 # mailbox protocol error
PROTO_MISMATCH = -4 # 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)
WKC_FAIL = -6 # WKC check failed
NO_MEMORY = -7 # out of memory
INVALID_ARG = -8 # invalid argument
NOT_IMPLEMENTED = -9 # the SDK does not support the async API
LINK_DOWN = -10 # link down (frames fail immediately, not timing out one by one); check the cable / NIC link status
NOT_SENT = -11 # request never left the host (frame never got on the wire: abort/backoff/pool dry/channel closed/held by the kernel);
# neither a slave timeout nor a slave rejection — no bus evidence at all, must not be used for slave-drop / link-health verdicts, treat as retryable

MailboxTransaction​

from darra_ethercat.abstractions import MailboxTransaction, MailboxStatus

txn = MailboxTransaction(dll, master_index=1, slave_index=1,
protocol_type=0x03, timeout_ms=5000)

Parameters:

  • dll — no default — SDK runtime instance
  • master_index (int) — no default — master index (≥1; 0 is invalid, master indexes start at 1). The master must already be established before the call (complete set_network() / build() and obtain a usable master context), otherwise there is no available bus channel
  • slave_index (int) — no default — slave index (1-based)
  • protocol_type (int) — no default — ECT_MBXT_* protocol type (CoE=3, FoE=4, SoE=5, AoE=1, EoE=2, VoE=0x0F, FSoE=8)
  • timeout_ms (int) — default 5000 — transaction timeout (ms)

Properties:

CategoryPropertyTypeRead/writeDescription
Requestrequest_frameOptional[bytes]read/writeComplete mailbox frame (including the 6-byte MbxHeader)
response_capacityintread/writeResponse buffer capacity (bytes, default 1500)
timeout_msintread/writeTransaction timeout (ms)
Responseresponse_frameOptional[bytes]read-onlyResponse frame filled in after success
response_lengthintread-onlyActual length of the response frame (bytes, including MbxHeader)
response_counterintread-onlyMailbox counter of the response frame (low 3 bits)
StatusstatusMailboxStatusread-onlyCurrent transaction status
error_codeintread-onlyProtocol-layer error code (0 means none)
slave_indexintread-onlySlave index
protocol_typeintread-onlyMailbox protocol type
Timesubmit_timeOptional[float]read-onlySubmission timestamp (time.time())
complete_timeOptional[float]read-onlyCompletion timestamp

Methods:

  • execute() — returns MailboxStatus — executes the transaction synchronously (the SDK handles submission, waiting and result retrieval) and returns the final status
  • cancel(ticket) — returns MailboxStatus — cancels an in-progress async transaction (ticket is the ticket value returned at submission)

Example:

from darra_ethercat.abstractions import MailboxTransaction, MailboxStatus

# Build a CoE mailbox transaction (protocol_type=0x03)
# dll is the SDK runtime instance
txn = MailboxTransaction(dll, master_index=master.master_index,
slave_index=1, protocol_type=0x03)

# Whole-frame mailbox message (including the 6-byte MbxHeader, assembled by you per ETG.1000.6)
txn.request_frame = bytes(...)

status = txn.execute()
if status == MailboxStatus.SUCCESS:
print(f"响应 {txn.response_length} 字节: {txn.response_frame.hex()}") # Response {txn.response_length} bytes: {txn.response_frame.hex()}
else:
print(f"事务失败: {status.name} (error_code=0x{txn.error_code:04X})") # Transaction failed: {status.name} (error_code=0x{txn.error_code:04X})
Degradation when the SDK does not support the async API

If the SDK does not support async transactions, execute() returns MailboxStatus.NOT_IMPLEMENTED and does not raise. The application layer uses this to decide whether the capability is available.

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, otherwise=slave station address
  • Type: 0x03=CoE, 0x04=FoE, 0x05=SoE, 0x0F=VoE
  • Cnt: mailbox counter (cycles 1-7)

Complete example​

Scenario A — Integrate existing configuration / debugging tools​

Let a third-party configuration tool (or engineer tool) access the master / slave object dictionaries over UDP without modifying the firmware of the controlled device.

Scenario B — Custom diagnostics or automation scripts​

Use a script or service to collect slave parameters periodically, read objects in bulk, or perform remote configuration.

Scenario C — Remote monitoring and alarm collection​

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

Starting the gateway​

from darra_ethercat import EtherCATMaster, EcState

with EtherCATMaster() as master:
master.set_eni("config.deni")
master.set_network(r"\Device\NPF_{GUID}")
master.set_state(EcState.OP)
master.start()

# Start the mailbox gateway (optional: custom port)
gateway = master.mailbox_gateway
# gateway.port = 12345 # default 34980 + (master index - 1) (master 1 is 34980); set it before start if you need to change it
gateway.start()
print(f"邮箱网关已启动,端口: {gateway.port}") # Mailbox gateway started, port: {gateway.port}

# PDO runs automatically on a background thread; the gateway provides mailbox service in OP state
input("按回车停止...") # Press Enter to stop...

gateway.stop()

External client​

import socket
import struct

class MailboxGatewayClient:
"""ETG.8200 邮箱网关 UDP 客户端""" # ETG.8200 mailbox gateway UDP client

def __init__(self, host: str = "127.0.0.1", port: int = 0x88A4):
self.addr = (host, port)
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(3.0)

def build_frame(self, address: int, mb_type: int, mb_data: bytes) -> bytes:
"""组装 ETG.8200 邮箱网关 UDP 帧 (示例参考, 可按需重命名)""" # Assemble an ETG.8200 mailbox gateway UDP frame (sample reference, rename as needed)
mb_len = len(mb_data)
ecat_len = 6 + mb_len
ecat_header = (0x05 << 12) | (ecat_len & 0x07FF)

frame = struct.pack('<H', ecat_header) # EtherCAT Header
frame += struct.pack('<H', mb_len) # Mailbox Length
frame += struct.pack('<H', address) # Address
frame += bytes([0x00]) # Channel + Priority
frame += bytes([mb_type << 4]) # Type
frame += mb_data
return frame

def send_request(self, address: int, mb_type: int, mb_data: bytes) -> bytes:
frame = self.build_frame(address, mb_type, mb_data)
self.sock.sendto(frame, self.addr)
resp, _ = self.sock.recvfrom(4096)
return resp

def coe_sdo_read(self, address: int, index: int, subindex: int) -> bytes:
"""CoE SDO Upload(读取对象字典)""" # CoE SDO Upload (read the object dictionary)
co_data = bytearray(8)
co_data[1] = 0x20 # CoE Type: SDO Request
co_data[2] = 0x40 # SDO Upload (Read)
struct.pack_into('<H', co_data, 3, index)
co_data[5] = subindex
return self.send_request(address, 0x03, bytes(co_data))

def coe_sdo_write(self, address: int, index: int, subindex: int, value: bytes) -> bytes:
"""CoE SDO Download(写入对象字典)""" # CoE SDO Download (write the object dictionary)
co_data = bytearray(6 + len(value))
co_data[1] = 0x20 # CoE Type: SDO Request
co_data[2] = 0x20 # SDO Download (Write)
struct.pack_into('<H', co_data, 3, index)
co_data[5] = subindex
co_data[6:6+len(value)] = value
return self.send_request(address, 0x03, bytes(co_data))

def soe_read(self, address: int, idn: int, drive_no: int = 0, element: int = 0x05) -> bytes:
"""SoE Read (read an IDN parameter)
element_flags: 0x00=Name, 0x01=Attribute, 0x02=Unit, 0x03=Min, 0x04=Max, 0x05=Value, 0x06=Default, 0x07=DataType
"""
soe_data = bytearray(4)
soe_data[0] = 0x01 # OpCode: Read
soe_data[1] = (drive_no << 3) | (element & 0x07)
struct.pack_into('<H', soe_data, 2, idn)
return self.send_request(address, 0x05, bytes(soe_data))

def soe_write(self, address: int, idn: int, value: bytes, drive_no: int = 0, element: int = 0x05) -> bytes:
"""SoE Write(写入 IDN 参数)""" # SoE Write (write IDN parameters)
soe_data = bytearray(4 + len(value))
soe_data[0] = 0x02 # OpCode: Write
soe_data[1] = (drive_no << 3) | (element & 0x07)
struct.pack_into('<H', soe_data, 2, idn)
soe_data[4:4+len(value)] = value
return self.send_request(address, 0x05, bytes(soe_data))

def foe_read(self, address: int, filename: str) -> bytes:
"""FoE Read(从从站下载文件,单包 Read Request)""" # FoE Read (download a file from the slave, single-packet Read Request)
name_bytes = filename.encode('ascii') + b'\x00'
foe_data = bytearray(5 + len(name_bytes))
foe_data[0] = 0x01 # OpCode: Read Request
foe_data[5:] = name_bytes
return self.send_request(address, 0x04, bytes(foe_data))

def voe_send(self, address: int, vendor_id: int, vendor_type: int, data: bytes) -> bytes:
"""VoE 发送/接收(厂商特定协议)""" # VoE send/receive (vendor-specific protocol)
voe_data = bytearray(6 + len(data))
struct.pack_into('<I', voe_data, 0, vendor_id) # VendorID
struct.pack_into('<H', voe_data, 4, vendor_type) # VendorType
voe_data[6:6+len(data)] = data
return self.send_request(address, 0x0F, bytes(voe_data))

# --- Usage example ---
client = MailboxGatewayClient("192.168.1.100")

# CoE: read the master object dictionary (address=0x0000)
resp = client.coe_sdo_read(0x0000, 0x1018, 0x01)
print(f"主站 VendorID: {resp.hex()}") # Master VendorID: {resp.hex()}

# CoE: read/write the slave object dictionary
resp = client.coe_sdo_read(0x03E9, 0x6040, 0x00)
client.coe_sdo_write(0x03E9, 0x6040, 0x00, struct.pack('<H', 0x0006))

# SoE: read a slave IDN parameter value
resp = client.soe_read(0x03E9, idn=32, drive_no=0, element=0x05)

# SoE: write a slave IDN parameter value
client.soe_write(0x03E9, idn=32, value=struct.pack('<I', 1000))

# FoE: download a file from the slave
resp = client.foe_read(0x03E9, "firmware.bin")

# VoE: vendor-specific protocol
resp = client.voe_send(0x03E9, vendor_id=0x00001164, vendor_type=0x0001, data=b'\x01\x02')

Cautions​

Network security

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

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

The gateway runs UDP send/receive and forwarding on a background thread, so the impact on the main loop is minimal. However, a large number of synchronous SDO / mailbox operations can still affect overall latency — limit concurrency and rate appropriately.

The effective budget for slave mailbox transactions is decided by the SDK (requested values are raised to the lower bound; the actual value is in the "gateway budget request / effective" line in the log).

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

Error codes:

  • 0x06020000 - object does not exist
  • 0x06010000 - unsupported access
  • 0x06010002 - write protection
  • 0x05040001 - command not implemented
  • 0x08000000 - general error

SoE (Servo over EtherCAT)​

Supported operations:

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

Elements in the frame (interpreted by the slave side; the gateway forwards them as-is):

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

Error codes:

  • 0x8001 - service not available
  • 0x1001 - invalid command
  • 0x1009 - IDN does not exist
  • 0x3002 - invalid data size
  • 0x7002 - write failed
  • 0x8000 - general error

FoE (File over EtherCAT)​

Forwarding semantics:

  • Read Request (0x01) / Write Request (0x02) / Data (0x03) / Ack (0x04) are all forwarded to the slave by the gateway as ETG.1000.6 frames
  • Error (0x05) - the slave's error response is returned along the original path
Old limitations no longer apply

The local FoE session implementation on the Python side has been removed; the limitation in old documentation ("only single-packet Read supported, WRQ returns 0x00008001") belonged to the removed implementation and no longer represents current gateway behavior.

Error codes (slave side):

  • 0x00008001 - invalid opcode
  • 0x00008002 - file not found
  • 0x00008003 - illegal file name
  • 0x00008000 - general error

VoE (Vendor over EtherCAT)​

Frame layout:

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

Purpose:

  • Full pass-through to the slave VoE interface
  • Request/response handled automatically
  • Supports data of any length

Error codes:

  • 0x0001 - service not available
  • 0x0002 - invalid frame
  • 0x0003 - no response
  • 0x0000 - general error

Error handling​

ProtocolError typeError codeDescription
CoEObject does not exist0x06020000The requested object or slave does not exist
CoEUnsupported access0x06010000The protocol type is not supported or the slave has no such function
CoEWrite protection0x06010002Attempt to write a read-only object
CoECommand not implemented0x05040001The SDO command specifier is not supported
CoEGeneral error0x08000000Other processing error
SoEIDN does not exist0x1009The requested IDN parameter does not exist
SoEWrite failed0x7002Writing the IDN parameter failed
FoEFile not found0x00008002The requested file does not exist
FoEIllegal file name0x00008003The file name format is invalid
VoENo response0x0003The slave gives no VoE response

Failures and handling​

SymptomCauseHandling
start throws OSErrorBinding fails for the preferred port and all 9 candidate ports after itRelease the processes occupying these ports and retry; before start use port to specify the preferred port, after start read gateway.port to confirm the actual port
start throws RuntimeErrormaster has no usable runtime context, or the runtime does not support the capabilityAccess the gateway through a normally constructed master; if it still fails, check the runtime version
Statistics read while not runningThe gateway has no running snapshotReturns an empty snapshot with only the port and running state filled in; counters are not fabricated
is_running is still True after stopThe underlying stop did not completeCall stop again to retry
Statistics do not grow for a long timeNo external tool sends requests, or the target address / protocol is not supportedCheck the UDP port and the target address, and first confirm the peer's request format is correct

Boundaries​

  • The gateway's UDP/TCP service, frame parsing and response construction are provided by the SDK; the application layer only starts/stops through master.mailbox_gateway and reads statistics.
  • The UDP port is tried as preferred + 0..+9; when all fail it raises OSError; there is no system ephemeral port fallback.
  • Stop drains within a single 2-second overall deadline; if it does not complete, stop() can be retried.
  • EoE (0x02) does not go through the Gateway (ETG.8200 §4.1).
  • Only one gateway instance is started per master; capabilities such as the TCP channel / Discovery master selection are provided uniformly by the gateway, and the statistics fields are in the table above.