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.
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
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Service | Start() | void | Write-only | Starts the gateway; repeated calls on the same master are idempotent |
| Service | Stop() | void | Write-only | Stops the gateway; call again if it has not fully stopped |
| Status | IsRunning | bool | Read-only | Whether the gateway is currently running |
| Service | Port | int | Read/write | UDP port, 34980 by default; must be set before Start |
| Statistics | GetStatistics() | MailboxGatewayStats | Read-only | Snapshot 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);
masterIndexis 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:
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| UDP service | Start(ushort masterIndex, ushort port = 0x88A4) | bool | Write-only | Starts the gateway; fails immediately if the port is in use (strict binding), no automatic port switch |
| Stop(ushort masterIndex) | bool | Write-only | Stops the gateway; if it has not fully stopped within the time limit, call it again | |
| IsRunning(ushort masterIndex) | bool | Read-only | Whether the gateway is running | |
| GetPort(ushort masterIndex) | ushort | Read-only | UDP port actually bound; returns 0 when not started | |
| Statistics | GetStatistics(ushort masterIndex) | MailboxGatewayStats | Read-only | Snapshot of runtime statistics; returns null when unavailable (counters are never fabricated) |
| ResetStatistics(ushort masterIndex) | void | Write-only | Resets the statistics counters (the port and running state are preserved) | |
| TCP channel | StartTcp(ushort masterIndex, ushort port = 0x88A4) | bool | Write-only | Starts 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) | bool | Write-only | Stops the TCP listener and closes all active connections | |
| IsTcpRunning(ushort masterIndex) | bool | Read-only | Whether the TCP channel is running | |
| GetTcpPort(ushort masterIndex) | ushort | Read-only | TCP port actually bound; returns 0 when not started | |
| Discovery | GetSelectedMaster(ushort masterIndex) | ushort | Read-only | Currently selected master index (ServiceID 0x0600); returns 0xFFFF on failure |
| SetSelectedMaster(ushort masterIndex, ushort selected) | bool | Write-only | Sets the selected master index (ServiceID 0x0500, selected must already be initialized) |
Constants: MailboxGateway.DefaultPort / MailboxGateway.DefaultTcpPort (both 0x88A4 = 34980).
Service control
| Category | Member | Type | Read/write | Description |
|---|---|---|---|---|
| Service control | Port | int | Read/write | UDP port number, 0x88A4 (34980) by default; must be set before Start(); while running, it returns the port actually bound |
| IsRunning | bool | Read-only | Whether the service is running (reads the SDK runtime state) | |
| Start() | void | Write | Starts the service (done by the SDK); repeated calls on the same master are idempotent | |
| Stop() | void | Write | Stops 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 | |
| Statistics | GetStatistics() | MailboxGatewayStats | Read-only | Snapshot of runtime statistics |
| ResetStatistics() | void | Write | Resets 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.
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).
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.
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):
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Statistics | RxPackets | ulong | Read-only | Total number of UDP datagrams received |
| TxPackets | ulong | Read-only | Total number of UDP responses sent | |
| RxBytes | ulong | Read-only | Cumulative inbound bytes | |
| TxBytes | ulong | Read-only | Cumulative outbound bytes | |
| MasterOdRequests | ulong | Read-only | Number of requests routed to the master object dictionary (ETG.1510, Address = 0x0000) | |
| MasterRequests | ulong | Read-only | Raw field for the total number of master OD requests (same value as MasterOdRequests) | |
| SlaveRequests | ulong | Read-only | Number of requests routed to slave mailboxes (total forwarded requests minus master OD requests) | |
| DropMalformed | ulong | Read-only | Dropped frames with a malformed frame structure (= InvalidFrame) | |
| DropTimeout | ulong | Read-only | Dropped frames due to processing / forwarding timeout (= TimeoutCount) | |
| ForwardedOk | ulong | Read-only | Number of successful forwards that received a response | |
| ForwardedFailed | ulong | Read-only | Number of failed forwards (mbxsend / mbxreceive errors) | |
| TimeoutCount | ulong | Read-only | Number of slave response timeouts (raw field for DropTimeout) | |
| InvalidFrame | ulong | Read-only | Number of malformed frames (raw field for DropMalformed) | |
| UnknownTarget | ulong | Read-only | Number of times the target slave does not exist | |
| UnsupportedType | ulong | Read-only | Number of unsupported mailbox protocol types | |
| DiscoveryRequests | ulong | Read-only | Number of Discovery (Ping / List / Set / Get) service requests | |
| Status | IsRunning | bool | Read-only | Whether the gateway is running |
| UdpPort | ushort | Read-only | UDP port currently bound | |
| TcpRunning | bool | Read-only | Whether the TCP channel is running | |
| TcpPort | ushort | Read-only | TCP port currently bound (0 = TCP not started) | |
| TcpConnections | ulong | Read-only | Cumulative number of TCP connections accepted | |
| TcpActive | ulong | Read-only | Number of currently active TCP connections | |
| SelectedMaster | byte | Read-only | Master index selected by ServiceID 0x0500 (default = itself) |
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
| Protocol | Type | Description |
|---|---|---|
| CoE | 0x03 | SDO read/write, supporting both the master (ETG.1510) and slave object dictionaries; segmented transfer included |
| FoE | 0x04 | File transfer |
| SoE | 0x05 | IDN parameter read/write (ETG.1020 standard) |
| VoE | 0x0F | Vendor-specific protocol pass-through |
| AoE | 0x01 | ADS over EtherCAT pass-through |
| Discovery | Service-based | ETG.8200 §7.5 / §7.6 (Ping / List / Set / Get Selected Master) |
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 =
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();
}
| Category | Member | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol identification | ProtocolType | byte | Read-only | Protocol type code: AoE=0x01, EoE=0x02, CoE=0x03, FoE=0x04, SoE=0x05, FSoE=0x08, VoE=0x0F |
| ProtocolName | string | Read-only | Protocol name: CoE / FoE / SoE / AoE / EoE / VoE / FSoE | |
| Protocol capability | IsSupported | bool | Read-only | Whether the slave confirms support for this protocol; false when the capability is unknown |
| Transaction status | LastStatus | MailboxStatus | Read-only | Unified status of the most recent mailbox transaction; initially Pending |
| LastErrorCode | uint | Read-only | Protocol-layer error code of the most recent transaction; 0 = no error or not applicable | |
| Statistics | Statistics | MailboxStatistics | Read-only | Snapshot of mailbox transaction statistics; returns an empty snapshot when the statistics interface is unavailable |
| ResetStatistics() | void | Write-only | Resets 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/InvalidArgand 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.
ResponseFrameis filled only onSuccess;ResponseLengthis the actual length of the response frame (including the 6-byte mailbox header), andResponseCounteris 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
MailboxErrorevent 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
ArgumentOutOfRangeExceptiondirectly and are not folded into a status code:RequestFramelength orResponseCapacityabove 65535 bytes, a negativeResponseCapacity, orTimeoutMsoutside 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:
- MailboxStatus — the final status of the same transaction
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
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
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 exist0x06010000- unsupported access0x06010002- write protection0x05040001- command not implemented0x08000000- 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 status0x02- parameter name0x04- parameter attribute0x08- unit0x10/0x20- minimum value / maximum value0x40- data value (most commonly used)0x80- default value
Error codes:
0x1001- IDN does not exist0x1009- invalid access to element 10x3002- attribute transfer too short0x7002- operation data transfer too short0x800B- 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 error0x8001- file not found0x8002- access denied0x8003- disk full0x8008- 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 error0x0002- protocol not supported0x0003- invalid channel0x0004- service not supported (including no response from the slave)0x0005- invalid mailbox header0x0006- length too short0x0007- insufficient memory0x0008- invalid length
Error handling
| Protocol | Error type | Error code | Description |
|---|---|---|---|
| CoE | Object does not exist | 0x06020000 | The requested object or slave does not exist |
| CoE | Unsupported access | 0x06010000 | The protocol type is not supported or the slave has no such function |
| CoE | Write protection | 0x06010002 | Attempt to write a read-only object |
| CoE | Command not implemented | 0x05040001 | The SDO command specifier is not supported |
| CoE | General error | 0x08000000 | Other processing error |
| SoE | IDN does not exist | 0x1001 | The requested IDN parameter does not exist |
| SoE | Operation data transfer too short | 0x7002 | The length of the written data does not meet the requirement |
| FoE | File not found | 0x8001 | The requested file does not exist |
| FoE | Access denied | 0x8002 | The password does not match the slave's requirement or permissions are insufficient |
| VoE | Service not supported | 0x0004 | The 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
Portexplicitly 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
| Symptom | Cause | Handling |
|---|---|---|
| IsRunning is false after Start | The port is in use; the gateway uses strict binding and does not switch ports automatically | Change Port and call Start again; the port can only be set before start-up |
| Start is rejected | The master index is 0, or the master is not initialized | Call Build first to create the master context; master indexes start at 1 |
| Statistics read while not running | No runtime snapshot is available | The 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 Stop | A single stop did not complete within the time limit | Call Stop again to retry |
| Statistics do not grow for a long time | No external tool is sending requests, or the target address / protocol is not supported | Check the UDP port and the target address, and first confirm the peer's request format is correct |