Skip to main content

Mailbox Gateway

The mailbox gateway is the official user SDK (ETG.8200): it exposes a UDP interface per ETG.8200 so external tools can read the object dictionaries of the master and the slaves (CoE / SoE / FoE / VoE / AoE pass-through). It serves external ETG.8200 tools and most applications do not need it; to read the object dictionary from inside an application, use the corresponding CoE / SoE page. The static class MailboxGateway provides the same set of entry points, addressed by master index.

Access through master.MailboxGateway.​

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.

Method overview​

CategoryMethodTypeRead/writeDescription
ServiceStart()voidWrite-onlyStarts the gateway; repeated calls on the same master are idempotent
ServiceStop()voidWrite-onlyStops the gateway; call again if it has not fully stopped
StatusIsRunningboolRead-onlyWhether the gateway is currently running
ServicePortintRead/writeUDP port, 34980 by default; must be set before Start
StatisticsGetStatistics()MailboxGatewayStatsRead-onlySnapshot of runtime statistics; returns an empty snapshot when not running

Static entry point MailboxGateway​

Besides the instance entry point master.MailboxGateway, the SDK also provides the static class MailboxGateway (in the same namespace as DarraEtherCAT) for multi-master processes that operate a specific master by index. The static entry point and the instance entry point share the same SDK implementation (idempotent, and they do not compete for the port).

MailboxGateway.Start(masterIndex: 1);              // master 1, default port 0x88A4
MailboxGateway.Start(masterIndex: 1, port: 34980); // explicit port
var stats = MailboxGateway.GetStatistics(masterIndex: 1);
MailboxGateway.Stop(masterIndex: 1);
Master index and preconditions
  • masterIndex is required and has no default; master indexes start at 1 (≥1), and 0 is always invalid — there is no master context for index 0, so the SDK rejects 0 outright (logs a Warning and returns the failure value documented for each method).
  • The master must already be initialized (Build()) before the call; a call on an uninitialized master is rejected in the same way.

All static entry points require a valid masterIndex to be passed explicitly:

CategoryMethodTypeRead/writeDescription
UDP serviceStart(ushort masterIndex, ushort port = 0x88A4)boolWrite-onlyStarts the gateway; fails immediately if the port is in use (strict binding), no automatic port switch
Stop(ushort masterIndex)boolWrite-onlyStops the gateway; if it has not fully stopped within the time limit, call it again
IsRunning(ushort masterIndex)boolRead-onlyWhether the gateway is running
GetPort(ushort masterIndex)ushortRead-onlyUDP port actually bound; returns 0 when not started
StatisticsGetStatistics(ushort masterIndex)MailboxGatewayStatsRead-onlySnapshot of runtime statistics; returns null when unavailable (counters are never fabricated)
ResetStatistics(ushort masterIndex)voidWrite-onlyResets the statistics counters (the port and running state are preserved)
TCP channelStartTcp(ushort masterIndex, ushort port = 0x88A4)boolWrite-onlyStarts the TCP listener (frame format: 2-byte little-endian length prefix + ETG.8200 frame), suitable for stateful long requests such as FoE
StopTcp(ushort masterIndex)boolWrite-onlyStops the TCP listener and closes all active connections
IsTcpRunning(ushort masterIndex)boolRead-onlyWhether the TCP channel is running
GetTcpPort(ushort masterIndex)ushortRead-onlyTCP port actually bound; returns 0 when not started
DiscoveryGetSelectedMaster(ushort masterIndex)ushortRead-onlyCurrently selected master index (ServiceID 0x0600); returns 0xFFFF on failure
SetSelectedMaster(ushort masterIndex, ushort selected)boolWrite-onlySets the selected master index (ServiceID 0x0500, selected must already be initialized)

Constants: MailboxGateway.DefaultPort / MailboxGateway.DefaultTcpPort (both 0x88A4 = 34980).

Service control​

CategoryMemberTypeRead/writeDescription
Service controlPortintRead/writeUDP port number, 0x88A4 (34980) by default; must be set before Start(); while running, it returns the port actually bound
IsRunningboolRead-onlyWhether the service is running (reads the SDK runtime state)
Start()voidWriteStarts the service (done by the SDK); repeated calls on the same master are idempotent
Stop()voidWriteStops the service (done by the SDK); a single call returns within a bounded time, and if it has not fully stopped you can call Stop() again to retry
StatisticsGetStatistics()MailboxGatewayStatsRead-onlySnapshot of runtime statistics
ResetStatistics()voidWriteResets all statistics counters (the running-state fields are preserved)

Port​

public int Port { get; set; }

UDP port number (read/write), 0x88A4 (34980) by default. While running, reading it returns the port actually bound; when not running it returns the port expected at the next start.

Default port offset for multiple instances

When master.MailboxGateway is constructed, it derives the default expected port from MasterNumber (the master number, starting at 1):

  • Master 1: 34980 (default)
  • Master N: 34980 + (N - 1)

To specify the port manually, set the Port property before Start() to override the default (valid range 0..65535; any other value throws ArgumentOutOfRangeException).

Strict port binding, no automatic port switch

The port must be set before the service starts; assigning it while running throws InvalidOperationException. The SDK uses strict binding: with Port = 0 it binds the default 0x88A4, and if that port is already in use the start fails (logs a Warning and IsRunning stays false) — it no longer tries an alternate port and does not fall back to a system-assigned port. To use a different port, change Port explicitly and call Start() again.

IsRunning​

public bool IsRunning { get; }

Whether the service is running (read-only). It reads the SDK runtime state directly; it is not a locally cached flag.

Start()​

public void Start()

Starts the mailbox gateway service (done by the SDK). Idempotent: if it is already running, another call returns immediately and does not take over the port a second time. If port binding fails, it logs a Warning, IsRunning stays false, and the caller handles the actual state.

Instance service and static interface behave identically

master.MailboxGateway and the static interface behave identically, with the same public method names, parameters and return types. On the same master, the instance service and static MailboxGateway.Start() share one service instance, so repeated starts are idempotent and two services never compete for the port.

Example:

var gateway = master.MailboxGateway;
gateway.Start();
Console.WriteLine($"邮箱网关已启动,端口: {gateway.Port}"); // Mailbox gateway started, port: {gateway.Port}

Stop()​

public void Stop()

Stops the mailbox gateway service (done by the SDK). A single call returns within a bounded time; if it is still not fully stopped when it returns, the SDK logs a Warning and IsRunning remains true, so you can call Stop() again to retry.

Example:

master.MailboxGateway.Stop();
if (master.MailboxGateway.IsRunning)
master.MailboxGateway.Stop(); // retry if it has not fully stopped

Statistics​

public MailboxGatewayStats GetStatistics()

Gets a snapshot of the mailbox gateway runtime statistics. The source of the statistics is the SDK runtime statistics; the instance service and static MailboxGateway.GetStatistics() return the same snapshot, with the full set of fields.

Return value fields (MailboxGatewayStats):

CategoryPropertyTypeRead/writeDescription
StatisticsRxPacketsulongRead-onlyTotal number of UDP datagrams received
TxPacketsulongRead-onlyTotal number of UDP responses sent
RxBytesulongRead-onlyCumulative inbound bytes
TxBytesulongRead-onlyCumulative outbound bytes
MasterOdRequestsulongRead-onlyNumber of requests routed to the master object dictionary (ETG.1510, Address = 0x0000)
MasterRequestsulongRead-onlyRaw field for the total number of master OD requests (same value as MasterOdRequests)
SlaveRequestsulongRead-onlyNumber of requests routed to slave mailboxes (total forwarded requests minus master OD requests)
DropMalformedulongRead-onlyDropped frames with a malformed frame structure (= InvalidFrame)
DropTimeoutulongRead-onlyDropped frames due to processing / forwarding timeout (= TimeoutCount)
ForwardedOkulongRead-onlyNumber of successful forwards that received a response
ForwardedFailedulongRead-onlyNumber of failed forwards (mbxsend / mbxreceive errors)
TimeoutCountulongRead-onlyNumber of slave response timeouts (raw field for DropTimeout)
InvalidFrameulongRead-onlyNumber of malformed frames (raw field for DropMalformed)
UnknownTargetulongRead-onlyNumber of times the target slave does not exist
UnsupportedTypeulongRead-onlyNumber of unsupported mailbox protocol types
DiscoveryRequestsulongRead-onlyNumber of Discovery (Ping / List / Set / Get) service requests
StatusIsRunningboolRead-onlyWhether the gateway is running
UdpPortushortRead-onlyUDP port currently bound
TcpRunningboolRead-onlyWhether the TCP channel is running
TcpPortushortRead-onlyTCP port currently bound (0 = TCP not started)
TcpConnectionsulongRead-onlyCumulative number of TCP connections accepted
TcpActiveulongRead-onlyNumber of currently active TCP connections
SelectedMasterbyteRead-onlyMaster index selected by ServiceID 0x0500 (default = itself)
When the runtime snapshot is unavailable

When the master is not initialized or has been closed, no runtime snapshot is available: the instance GetStatistics() returns a snapshot with IsRunning = false and all counters at 0 (it keeps UdpPort), and counters are never fabricated; the static MailboxGateway.GetStatistics() returns null in this case.

Example:

var stats = master.MailboxGateway.GetStatistics();

Console.WriteLine(
$"Mailbox Gateway 运行 {stats.RxPackets} req / {stats.TxPackets} resp\n" + // Mailbox Gateway running {stats.RxPackets} req / {stats.TxPackets} resp\n
$" ↳ Master OD: {stats.MasterOdRequests}, Slave 邮箱: {stats.SlaveRequests}\n" + // ↳ Master OD: {stats.MasterOdRequests}, slave mailbox: {stats.SlaveRequests}\n
$" ↳ 丢弃: 格式错={stats.DropMalformed}, 超时={stats.DropTimeout}\n" + // ↳ dropped: malformed={stats.DropMalformed}, timeout={stats.DropTimeout}\n
$" ↳ 流量: Rx={stats.RxBytes / 1024.0:F1} KB, Tx={stats.TxBytes / 1024.0:F1} KB"); // ↳ traffic: Rx={stats.RxBytes / 1024.0:F1} KB, Tx={stats.TxBytes / 1024.0:F1} KB

ResetStatistics()​

public void ResetStatistics()

Resets all statistics counters of the mailbox gateway (the running-state fields are preserved). Commonly used to reset the baseline before a new diagnostics round or test case.

Example:

master.MailboxGateway.ResetStatistics();  // reset, then collect again

Supported protocols​

ProtocolTypeDescription
CoE0x03SDO read/write, supporting both the master (ETG.1510) and slave object dictionaries; segmented transfer included
FoE0x04File transfer
SoE0x05IDN parameter read/write (ETG.1020 standard)
VoE0x0FVendor-specific protocol pass-through
AoE0x01ADS over EtherCAT pass-through
DiscoveryService-basedETG.8200 §7.5 / §7.6 (Ping / List / Set / Get Selected Master)
Single implementation

The gateway's protocol capabilities are provided uniformly by the SDK. The instance service master.MailboxGateway and the static entry point have identical capabilities and protocol coverage.

Address routing
  • Address = 0x0000 → access the master object dictionary (CoE only)
  • Address = slave station address → pass through to the corresponding slave

Unified mailbox protocol interface​

DarraEtherCAT_Master.Abstractions.IMailboxProtocol is the unified contract for the seven mailbox protocol instances, obtained through slave.CoE / slave.FoE / slave.SoE / slave.AoE / slave.EoE / slave.VoE / slave.FSoE (implementation classes: CoEInstance / FoEInstance / SoEInstance / AoEInstance / EoEInstance / VoEInstance / FSoEInstance). The gateway routes by mailbox protocol type code to the same set of protocols. The common surface of the protocol instances is as follows:

public interface IMailboxProtocol
{
byte ProtocolType { get; }
string ProtocolName { get; }
bool IsSupported { get; }
MailboxStatus LastStatus { get; }
uint LastErrorCode { get; }
MailboxStatistics Statistics { get; }
void ResetStatistics();
}
CategoryMemberTypeRead/writeDescription
Protocol identificationProtocolTypebyteRead-onlyProtocol type code: AoE=0x01, EoE=0x02, CoE=0x03, FoE=0x04, SoE=0x05, FSoE=0x08, VoE=0x0F
ProtocolNamestringRead-onlyProtocol name: CoE / FoE / SoE / AoE / EoE / VoE / FSoE
Protocol capabilityIsSupportedboolRead-onlyWhether the slave confirms support for this protocol; false when the capability is unknown
Transaction statusLastStatusMailboxStatusRead-onlyUnified status of the most recent mailbox transaction; initially Pending
LastErrorCodeuintRead-onlyProtocol-layer error code of the most recent transaction; 0 = no error or not applicable
StatisticsStatisticsMailboxStatisticsRead-onlySnapshot of mailbox transaction statistics; returns an empty snapshot when the statistics interface is unavailable
ResetStatistics()voidWrite-onlyResets the mailbox statistics counters; on failure it does not reset them and sets LastStatus = MailboxError

Capability tri-state: IsSupported returns true only when support is confirmed; when the capability cannot be read it returns false, which is indistinguishable from "confirmed not supported" as a boolean. To tell them apart, use the tri-state property of each instance (CoESupport / FoESupport / SoESupport / AoESupport / EoESupport / VoESupport / FSoESupport): true = supported, false = confirmed not supported, null = unknown; IsSupportedKnown is equivalent to the tri-state property being != null.

Failure return semantics: LastStatus and LastErrorCode record the most recent transaction; on failure the status becomes Timeout / MailboxError / InvalidArg and so on, and the error code is a protocol-layer error code (CoE = SDO Abort Code, FoE = FoE error code, SoE = SoE error code). When Statistics is unavailable it returns an empty snapshot (all 0s, LastErrorTime is null), which must not be read as "no traffic". For the full definitions of MailboxStatus / MailboxStatistics, see CoE · MailboxStatus enum and CoE · Statistics / ResetStatistics(); all seven mailbox protocols share the same set.

Mailbox transactions​

IMailboxTransaction.Execute()​

MailboxStatus Execute();

Executes one mailbox transaction synchronously and returns the final status of the transaction.

DarraEtherCAT_Master.Abstractions.IMailboxTransaction is the contract for a single mailbox transaction; it exposes only the status, error code and timeout, not the frame buffers; the default implementation MailboxTransaction carries the frame contents in RequestFrame / ResponseFrame. Judge success or failure by the return value, not merely by whether the response frame is empty.

Return value:

  • MailboxStatus — Success = completed with a response received; Timeout / MailboxError / Cancelled / InvalidArg and so on indicate the corresponding termination reason

Example:

using DarraEtherCAT_Master.Abstractions;

IMailboxTransaction txn = new MailboxTransaction
{
MasterIndex = 0,
SlaveIndex = 1,
ProtocolType = 0x03, // CoE
RequestFrame = requestFrame, // Complete mailbox frame (including the 6-byte mailbox header)
TimeoutMs = 2000,
};
MailboxStatus status = txn.Execute();

MailboxTransaction.Execute()​

public virtual MailboxStatus Execute()

Default implementation: completes one request-response using RequestFrame and ResponseCapacity, and writes the result back into the transaction object.

  • ResponseFrame is filled only on Success; ResponseLength is the actual length of the response frame (including the 6-byte mailbox header), and ResponseCounter is the low 3 bits of the mailbox counter.
  • When the terminal state is a failure such as timeout / protocol error / channel closed, the master's MailboxError event fires once; a single execution fires it only once; NotImplemented (the transaction did not actually execute) does not fire it.
  • Out-of-range arguments throw ArgumentOutOfRangeException directly and are not folded into a status code: RequestFrame length or ResponseCapacity above 65535 bytes, a negative ResponseCapacity, or TimeoutMs outside the range 1–4294967 milliseconds.
  • When the SDK runtime libraries are missing or the version does not match, it returns NotImplemented, which means the transaction did not actually execute.

Return value:

Example:

var txn = new MailboxTransaction
{
MasterIndex = 0,
SlaveIndex = 1,
ProtocolType = 0x03,
RequestFrame = requestFrame,
TimeoutMs = 2000,
};

if (txn.Execute() == MailboxStatus.Success)
Console.WriteLine($"响应 {txn.ResponseLength} 字节"); // Response {txn.ResponseLength} bytes

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, 0x01=AoE, 0x0F=VoE
  • Cnt: mailbox counter (cycles 1-7)

Notes​

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 SDK handles the gateway's sending and receiving independently, so the impact on cycle performance is minimal. A large number of synchronous SDO / mailbox operations can still affect overall latency, so limit concurrency and rate sensibly.

The number of failed / timed-out slave forwards is counted faithfully in DropTimeout; successful responses are never fabricated.

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:

  • Read Request (0x01) - read an IDN parameter
  • Read Response (0x02) - read response
  • Write Request (0x03) - write an IDN parameter
  • Write Response (0x04) - write response
  • Notification (0x05) / Emergency (0x06) - asynchronous notification / emergency message

Supported elements (element flags):

  • 0x01 - data status
  • 0x02 - parameter name
  • 0x04 - parameter attribute
  • 0x08 - unit
  • 0x10 / 0x20 - minimum value / maximum value
  • 0x40 - data value (most commonly used)
  • 0x80 - default value

Error codes:

  • 0x1001 - IDN does not exist
  • 0x1009 - invalid access to element 1
  • 0x3002 - attribute transfer too short
  • 0x7002 - operation data transfer too short
  • 0x800B - general error

For the full enum, see SoE · Error handling (SoEError).

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
  • Busy (0x06) - slave busy (reported cyclically while the Flash is being erased or written)

Segmented transfers are handled by the SDK gateway and are not limited to a single packet.

Error codes (ETG.1000.6 Table 92):

  • 0x8000 - undefined error
  • 0x8001 - file not found
  • 0x8002 - access denied
  • 0x8003 - disk full
  • 0x8008 - available in Bootstrap mode only

For the full enum, see FoE · Error handling.

VoE (Vendor over EtherCAT)​

Frame format:

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

Features:

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

Error codes: When a pass-through fails or the slave reports an error, the gateway returns a mailbox error frame (Header Type = 0x00) whose Detail carries the ETG.1000.4 Table 30 error code:

  • 0x0001 - syntax error
  • 0x0002 - protocol not supported
  • 0x0003 - invalid channel
  • 0x0004 - service not supported (including no response from the slave)
  • 0x0005 - invalid mailbox header
  • 0x0006 - length too short
  • 0x0007 - insufficient memory
  • 0x0008 - invalid length

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 exist0x1001The requested IDN parameter does not exist
SoEOperation data transfer too short0x7002The length of the written data does not meet the requirement
FoEFile not found0x8001The requested file does not exist
FoEAccess denied0x8002The password does not match the slave's requirement or permissions are insufficient
VoEService not supported0x0004The slave gives no VoE response or the service is unavailable (Detail is the ETG.1000.4 Table 30 error code)

Limits​

Implemented features​

  • Full CoE pass-through (including segmented transfer)
  • SoE IDN parameter access
  • FoE file transfer
  • VoE vendor protocol pass-through
  • AoE pass-through
  • Discovery (Ping / List / Set / Get Selected Master)
  • Master object dictionary access
  • Slave mailbox pass-through
  • Error handling and error code mapping

Current boundaries​

  • Address mapping table (+0x8000 virtual mapping) is not provided
  • Multicast / broadcast requests are not provided
  • Strict port binding: start fails if the expected port is in use; change Port explicitly and restart (no automatic port switch)
  • Session state management is not provided

Full 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 yourself​

using DarraEtherCAT_Master;

var master = new DarraEtherCAT()
.SetENI(@"C:\config.deni");

var (success, message) = master.Build();
if (!success) { Console.WriteLine(message); return; }

master.SetState(EcState.OP);

// 1. Start: default port 34980; to change the port, set it before Start
var gateway = master.MailboxGateway;
gateway.Port = 34980;
gateway.Start();

if (!gateway.IsRunning)
{
Console.WriteLine("网关未启动:端口被占用,改 Port 后重试"); // Gateway not started: the port is in use, change Port and retry
return;
}

// 2. Query statistics
var stats = gateway.GetStatistics();
Console.WriteLine($"请求 {stats.RxPackets} / 响应 {stats.TxPackets}, 主站 OD {stats.MasterOdRequests}, 从站邮箱 {stats.SlaveRequests}"); // Requests {stats.RxPackets} / responses {stats.TxPackets}, master OD {stats.MasterOdRequests}, slave mailbox {stats.SlaveRequests}

// 3. Stop
gateway.Stop();
Console.WriteLine($"网关运行状态: {gateway.IsRunning}"); // Gateway running state: {gateway.IsRunning}

master.Close();

External client example (C#)​

using System.Net;
using System.Net.Sockets;

/// <summary>
/// ETG.8200 mailbox gateway UDP client
/// Used by external programs to access the master / slave object dictionary
/// </summary>
class MailboxGatewayClient
{
private readonly UdpClient _udp = new();
private readonly IPEndPoint _gateway;

public MailboxGatewayClient(string host = "127.0.0.1", int port = 0x88A4)
{
_gateway = new IPEndPoint(IPAddress.Parse(host), port);
}

/// <summary>
/// Builds an ETG.8200 frame: EtherCAT Header (2) + Mailbox Header (6) + Data
/// </summary>
private byte[] BuildFrame(ushort address, byte mailboxType, byte[] mailboxData)
{
ushort mbLength = (ushort)mailboxData.Length;
ushort ecatLength = (ushort)(6 + mbLength); // Mailbox Header + Data

var frame = new byte[2 + 6 + mbLength];

// EtherCAT Header: Length[10:0] | DataType[15:12]=0x05
ushort ecatHeader = (ushort)((0x05 << 12) | (ecatLength & 0x07FF));
BitConverter.GetBytes(ecatHeader).CopyTo(frame, 0);

// Mailbox Header
BitConverter.GetBytes(mbLength).CopyTo(frame, 2); // Length
BitConverter.GetBytes(address).CopyTo(frame, 4); // Address
frame[6] = 0x00; // Channel + Priority
frame[7] = (byte)(mailboxType << 4); // Type[7:4]

// Mailbox Data
mailboxData.CopyTo(frame, 8);

return frame;
}

/// <summary>
/// Sends a request and receives the response
/// </summary>
public byte[] SendRequest(ushort address, byte mailboxType, byte[] mailboxData)
{
var frame = BuildFrame(address, mailboxType, mailboxData);
_udp.Send(frame, frame.Length, _gateway);

var remoteEP = new IPEndPoint(IPAddress.Any, 0);
return _udp.Receive(ref remoteEP);
}

/// <summary>
/// CoE SDO Upload (read the object dictionary)
/// address: 0x0000=master, otherwise=slave station address
/// </summary>
public byte[] CoE_SDO_Read(ushort address, ushort index, byte subindex)
{
// CoE Header (2) + SDO Request (6)
var coData = new byte[8];
coData[0] = 0x00;
coData[1] = 0x20; // CoE Type: SDO Request
coData[2] = 0x40; // SDO Upload (Read)
BitConverter.GetBytes(index).CopyTo(coData, 3); // Index
coData[5] = subindex; // SubIndex

return SendRequest(address, 0x03, coData); // 0x03 = CoE
}

/// <summary>
/// CoE SDO Download (write the object dictionary)
/// </summary>
public byte[] CoE_SDO_Write(ushort address, ushort index, byte subindex, byte[] value)
{
var coData = new byte[6 + value.Length];
coData[0] = 0x00;
coData[1] = 0x20; // CoE Type: SDO Request
coData[2] = 0x20; // SDO Download (Write)
BitConverter.GetBytes(index).CopyTo(coData, 3);
coData[5] = subindex;
value.CopyTo(coData, 6);

return SendRequest(address, 0x03, coData);
}

/// <summary>
/// SoE Read Request (read an IDN parameter)
/// elementFlags bit flags: 0x01=data status, 0x02=name, 0x04=attribute, 0x08=unit, 0x10=minimum value, 0x20=maximum value, 0x40=data value, 0x80=default value
/// </summary>
public byte[] SoE_Read(ushort address, ushort idn, byte driveNo = 0, byte elementFlags = 0x40)
{
var soeData = new byte[4];
soeData[0] = (byte)(0x01 | ((driveNo & 0x07) << 5)); // OpCode: Read Request (0x01) + DriveNo
soeData[1] = elementFlags; // element flags (bitmask)
BitConverter.GetBytes(idn).CopyTo(soeData, 2); // IDN

return SendRequest(address, 0x05, soeData); // 0x05 = SoE
}

/// <summary>
/// SoE Write Request (write an IDN parameter)
/// </summary>
public byte[] SoE_Write(ushort address, ushort idn, byte[] value, byte driveNo = 0, byte elementFlags = 0x40)
{
var soeData = new byte[4 + value.Length];
soeData[0] = (byte)(0x03 | ((driveNo & 0x07) << 5)); // OpCode: Write Request (0x03) + DriveNo
soeData[1] = elementFlags; // element flags (bitmask)
BitConverter.GetBytes(idn).CopyTo(soeData, 2); // IDN
value.CopyTo(soeData, 4);

return SendRequest(address, 0x05, soeData); // 0x05 = SoE
}

/// <summary>
/// FoE Read (download a file from the slave)
/// </summary>
public byte[] FoE_Read(ushort address, string filename)
{
var nameBytes = Encoding.ASCII.GetBytes(filename + '\0');
var foeData = new byte[5 + nameBytes.Length];
foeData[0] = 0x01; // OpCode: Read Request
nameBytes.CopyTo(foeData, 5);

return SendRequest(address, 0x04, foeData); // 0x04 = FoE
}

/// <summary>
/// VoE send / receive (vendor-specific protocol)
/// </summary>
public byte[] VoE_SendReceive(ushort address, uint vendorId, ushort vendorType, byte[] data)
{
var voeData = new byte[6 + data.Length];
BitConverter.GetBytes(vendorId).CopyTo(voeData, 0); // VendorID
BitConverter.GetBytes(vendorType).CopyTo(voeData, 4); // VendorType
data.CopyTo(voeData, 6);

return SendRequest(address, 0x0F, voeData); // 0x0F = VoE
}
}

// --- Usage example ---
var client = new MailboxGatewayClient("192.168.1.100");

// CoE: read the master object dictionary (address=0x0000)
var resp = client.CoE_SDO_Read(0x0000, 0x1018, 0x01);
Console.WriteLine($"主站 VendorID: {BitConverter.ToString(resp)}"); // Master VendorID: {BitConverter.ToString(resp)}

// CoE: read / write the slave object dictionary
resp = client.CoE_SDO_Read(0x03E9, 0x6040, 0x00);
client.CoE_SDO_Write(0x03E9, 0x6040, 0x00, BitConverter.GetBytes((ushort)0x0006));

// SoE: read a slave IDN parameter value
resp = client.SoE_Read(0x03E9, 32, driveNo: 0, elementFlags: 0x40);

// SoE: write a slave IDN parameter value
client.SoE_Write(0x03E9, 32, BitConverter.GetBytes(1000), driveNo: 0);

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

// VoE: vendor-specific protocol
resp = client.VoE_SendReceive(0x03E9, 0x00001164, 0x0001, new byte[] { 0x01, 0x02 });

Failures and handling​

SymptomCauseHandling
IsRunning is false after StartThe port is in use; the gateway uses strict binding and does not switch ports automaticallyChange Port and call Start again; the port can only be set before start-up
Start is rejectedThe master index is 0, or the master is not initializedCall Build first to create the master context; master indexes start at 1
Statistics read while not runningNo runtime snapshot is availableThe instance entry point returns an empty snapshot with all counters at 0 and does not fabricate counters; the static entry point returns null
IsRunning is still true after StopA single stop did not complete within the time limitCall Stop again to retry
Statistics do not grow for a long timeNo external tool is sending 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