Skip to main content

C SDK overview

A pure C interface for developing EtherCAT master applications, suited to embedded and resource-constrained devices.

Installation​

The SDK package is darra_ethercat_c-win-x64.zip: get it from the downloads page or use the direct link https://download.darra.xyz/ethercat/c/darra_ethercat_c-win-x64.zip (the SHA256 checksum file darra_ethercat_c-win-x64.zip.sha256 sits in the same directory).

PathContents
bin/DarraEtherCAT.dll plus the runtime libraries shipped with the SDK
include/All header files (umbrella entry point ethercat.h)
lib/darra_ethercat.lib + darra-ethercat-advanced.lib + mxml4.lib
examples/basic.c / highlevel.c / cia402.c
Package rootCMakeLists.txt / build.bat / build.sh (build.bat Release examples builds the examples)

Link the import library darra_ethercat.lib (with MSVC the #pragma comment(lib, ...) in ethercat.h adds it automatically); when you use the advanced layer, also link darra-ethercat-advanced.lib + mxml4.lib. The DarraEtherCAT.dll runtime must be in the same directory as the executable or on PATH; on the first call it loads the runtime libraries that ship with the SDK.

# MSVC (lib\ is the library directory inside the package)
cl /Fe:my_app.exe /I include main.c /link /LIBPATH:lib darra_ethercat.lib darra-ethercat-advanced.lib mxml4.lib

# GCC/MinGW
gcc main.c -I include -o my_app.exe lib/darra_ethercat.lib lib/darra-ethercat-advanced.lib lib/mxml4.lib

The caller needs no DLL handle at all: call the public functions declared in the SDK headers directly, and callbacks are ordinary C function pointers.

#include "ethercat.h"

int main(void) {
uint16_t master = Initialize(); /* call the public function directly, no handle needed */
/* ... */
Dispose(master);
return 0;
}

Requirements​

  • Operating system — Windows 7+ (Windows 10/11 recommended). The Linux edition is planned
  • Compiler — MSVC 2019+, GCC 7+, Clang 10+, C11 or later
  • Privileges — Administrator / root (real-time network access)
  • Real-time network driver — provided with the official installer (download), microsecond-level real time, no dedicated hardware required

Quick start​

Use the Darra configuration tool
  1. Open the Darra configuration tool and scan the EtherCAT network
  2. Configure the slave parameters (PDO mapping, DC settings and so on)
  3. Export the DENI configuration file
  4. Load the DENI file in your code to initialize the master
#include <stdio.h>
#include <stdlib.h>
#include <ethercat.h>

/* read the whole configuration file (DENI is XML text; read it byte by byte and return a NUL-terminated buffer) */
static char* read_text_file(const char* path) {
FILE* f = fopen(path, "rb");
if (!f) return NULL;
if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
long size = ftell(f);
if (size < 0) { fclose(f); return NULL; }
rewind(f);
char* text = (char*)malloc((size_t)size + 1);
if (!text) { fclose(f); return NULL; }
size_t got = fread(text, 1, (size_t)size, f);
fclose(f);
text[got] = '\0';
return text;
}

int main(void) {
/* ★ Recommended: read the whole DENI file and hand it to LoadConfigJson
(a leading '<' in the content -> parsed as DENI XML: NIC selection + live slave scan + the full configuration) */
char* deni = read_text_file("C:\\EtherCAT\\MyProject.deni");
if (!deni) { fprintf(stderr, "DENI 读取失败\n"); return 1; } /* DENI read failed */

uint16_t m = Initialize();
if (m == 0xFFFF) { free(deni); return 1; } /* failure returns 0xFFFF ((uint16_t)-1); indexes start at 1 and 0 is never returned */

int rc = LoadConfigJson(m, deni);
free(deni);
if (rc != 0) {
char why[128];
describe_load_config_error(rc, why, (int)sizeof(why));
fprintf(stderr, "DENI 加载失败: %s\n", why); /* DENI load failed: %s */
Dispose(m);
return 1;
}

/* the DENI already selected a NIC: pass empty strings to use the NIC it resolved (an explicit GUID overrides it) */
uint16_t found = SetNetwork(m, "", "");
if (found == 0 || found == 0xFFFF) { Dispose(m); return 1; }

SetStateSequence(m, EC_STATE_OPERATIONAL, 10000);
Start(m); /* already in OP, so communicate directly here */

uint16_t statusword = 0;
if (sdo_read_u16(m, 1, 0x6041, 0x00, &statusword) == 0) {
printf("Statusword=0x%04X\n", statusword);
}

EcClose(m); /* close in one step: Stop + Dispose */
return 0;
}

Alternative: automatic NIC discovery (without DENI)​

Without DENI, use GetNetworkInfo() to scan all NICs automatically and take the one that has slaves; there is no need to hard-code \Device\NPF_{GUID}:

#include <stdio.h>
#include <ethercat.h>

int main(void) {
/* scan all NICs and probe the slave count (takes ~500 ms-1.5 s) */
int n = GetNetworkInfo(FALSE, TRUE);
ec_network_info_t* nets = (ec_network_info_t*)GetNetworksPointer(); /* internal pointer, do not free */

/* pick the NIC that has slaves */
uint16_t m = Initialize();
int found = 0;
for (int i = 0; i < n; i++) {
if (nets[i].slaveNum > 0) {
printf("找到: %s (从站 %d 台)\n", (const char*)nets[i].desc, nets[i].slaveNum); /* Found: %s (%d slaves) */
SetNetwork(m, (const char*)nets[i].name, "");
found = 1;
break;
}
}
if (!found) { fprintf(stderr, "未发现 EtherCAT 网络\n"); Dispose(m); return 1; } /* No EtherCAT network found */

SetStateSequence(m, EC_STATE_OPERATIONAL, 10000);
Start(m);
/* ... communication ... */
Stop(m);
Dispose(m);
return 0;
}

Use DENI in production (one line loads the complete parameter set); automatic discovery is for demos and tool-type applications.

Load a product DENI / standard ENI with LoadConfigJson: read the whole file first, then pass the contents in. deni_load reads only the legacy offline structure, eni_load reads a standard ENI, and xml_apply_config applies the parsed offline structure.

Core concepts:

  • Master index — a uint16_t that identifies the master instance and is returned by Initialize() (indexes start at 1 and are always > 0 on success; on failure it returns 0xFFFF = (uint16_t)-1, never 0)
  • Handle-free calls — call the public functions declared in the SDK headers directly; no handle and no member syntax
  • Multiple instances — each master instance manages one independent bus on its own NIC, and CPU cores can be assigned independently

Advanced API​

ethercat_advanced.h provides a set of higher-level wrappers that simplify common flows:

CategoryAPI function / headerAccessDescription
One-step initializationEcInit / EcInitFromFile / EcCloseWriteMaster initialization from a JSON configuration in one step
State chain transitionSetStateSequenceWriteRuns a multi-step state transition chain automatically
Startup parameter pipelineAddStartupParameter / ApplyStartupParametersWriteAdd startup parameters in bulk and apply them in one call
CiA 402 drive state machineCiA402_Enable / CiA402_SetModeWriteOne-step enable / fault reset / state parsing
EMCY emergency message bufferEmcyGetCount / EmcyGetHistoryReadRead the slave's emergency message history
PDO direct mapping / whole-frame snapshot and writeGetIO / CopySlaveInputPdo · CopySlaveOutputPdo / WriteSlaveOutputPdoRead / writeGetIO establishes a direct mapping once after entering OP (recommended path); Copy takes a snapshot; WriteSlaveOutputPdo accepts a complete frame from a single owner only
Mailbox gatewaygateway_create / gateway_start / gateway_stop / gateway_get_statisticsRead / writeETG.8200 UDP gateway (master/gateway.h, darra-ethercat-advanced)
ENI/DENILoadConfigJson (pass the whole file contents in) / deni_load · eni_load · xml_apply_config (offline structure read and apply)WriteFor product DENI/ENI use LoadConfigJson: it selects the NIC, scans slaves live and applies the whole configuration; deni_load reads only the legacy offline structure (not product DENI), eni_load reads standard ENI, and xml_apply_config applies a parsed structure (utils/xml.h, included through ethercat.h; SaveXML is not a user API). Saving a configuration is provided by Darra products; the SDK does not expose it
Topology queriesTopologyBuild / TopologyGetRoots / TopologyGetChildrenReadBuild and query the slave network topology tree
OD tree traversalod_load()ReadLoad the complete object dictionary tree
MDP module discoverymdp_discover() / mdp_get_detected_module_list()ReadModular device scan
MDP automatic configurationRuns automatically in the state chainWriteModule configuration completes automatically when the master enters PreOp
Asynchronous mailbox transactionsec_mbx_submit_async / ec_mbx_waitRead / writeNon-blocking mailbox transaction pipeline
FSoE managerfsoe_manager_create()WriteMulti-connection management
EoE pingeoe_ping()WriteICMP ping
PDO change monitorpdo_monitor_create()WriteInput data change detection

Quick example:

/* enable the servo drive in one step (slave=1, max_retries=50) */
CiA402_Enable(master, 1, 50);

/* PDO snapshot and whole-frame write (the recommended path is GetIO, which establishes a direct mapping once; see [PDO input and output](./slave/pdo-io)) */
uint8_t probe = 0;
uint32_t copied = 0, required = 0;
CopySlaveInputPdo(master, 1, &probe, sizeof(probe), &copied, &required); /* probe the length: returns 2 (buffer too small), required holds the authoritative length */
uint8_t* in = (uint8_t*)malloc(required);
if (in && ec_pdo_io_is_ok(CopySlaveInputPdo(master, 1, in, required, &copied, &required))) {
/* in is a complete input frame snapshot; it does not change with the bus */
}
free(in);

uint32_t out_copied = 0, out_required = 0;
CopySlaveOutputPdo(master, 1, &probe, sizeof(probe), &out_copied, &out_required); /* output frame length */
uint8_t* out = (uint8_t*)calloc(1, out_required);
if (out) {
uint32_t written = 0;
WriteSlaveOutputPdo(master, 1, out, out_required, &written, &out_required);
free(out);
}

/* read the emergency message history (the caller supplies an ec_emcy_record_t buffer; returns the number of records written) */
ec_emcy_record_t records[16];
int n = EmcyGetHistory(master, 1, records, 16);

/* topology query */
uint16_t children[64];
int cn = TopologyGetChildren(master, 1, children, 64);

C-specific sugar (C99+)​

internal/sugar/sugar.h (distributed in the internal/ directory of the source package and the installer, not part of the public include surface) provides a set of optional macros and inline wrappers at zero runtime cost that do not affect the standard API. It includes: designated struct initializers ({ .cycle_ns = 1000000 }) / the iteration macro EC_FOREACH_SLAVE(mi, i) / error handling EC_TRY · EC_TRY_LOG · EC_RETURN_IF_FAIL · EC_GOTO_IF_FAIL / inline short-name getters ec_vendor · ec_product / GCC/Clang cleanup EC_AUTO_DISPOSE / cycle presets EC_PRESET_CYCLE_1MS / C11 _Generic type dispatch.

Error code localization​

AL Status descriptions are available in both Chinese and English, English by default; SDO Abort descriptions exist in Chinese only:

const char* en = AL_StatusCode_GetDescription(code);  // AL Status English
const char* zh = DarraEcat_AL_StatusCode_GetDescriptionChinese(code); // AL Status Chinese
const char* sdo = ec_coe_sdo_error_str(abort); // SDO Abort Chinese
  • The English and Chinese AL Status functions are two independent interfaces; neither forwards to the other.
  • ec_coe_sdo_error_str() provides a human-readable Chinese description of an SDO Abort; when nothing matches it returns "UnknownError".
  • Protocol code query families for modes / states / EMCY / SII capability bits are on Protocol codes and diagnostic strings.

SDK readiness check​

The SDK initializes itself the first time a business entry point is called. DarraEcat_ShellReady() returns a value other than 0 when the SDK is ready and may be called repeatedly from any thread; while it is not ready, every business entry point returns its own failure value instead of silently succeeding. Just make sure the matching SDK and runtime are installed.

Utility functions and process-level APIs​

This section collects the entry points that are not part of the master / slave mainline but are used by applications and tools alike: value encoding and decoding, NIC scanning and selection, device and version information, licensing, runtime component guard, bind baseline and compatibility layer, last error code, low-level mailbox gateway configuration, and DC and topology helpers. All are synchronous calls; the return values, ownership and failure semantics follow the corresponding header.

Value encoding and decoding​

The ec_value_* family in utils/base_data.h handles PDO fields with the little-endian bit packing rules of ETG.1000.6: bit i starting at bit_offset is bit (bit_offset + i) % 8 of byte (bit_offset + i) / 8 (LSB-first), and the value is the sum of each bit shifted left by its position, allowing cross-byte spans (up to 9 bytes); signed reads sign-extend the two's complement according to bit_length; writes are a bit-field read-modify-write — only [bit_offset, bit_offset + bit_length) is changed, bits and bytes outside that range keep their original values, and the value is truncated to bit_length. REAL32 / REAL64 are fixed-width types that ignore bit_length and require bit_offset % 8 == 0.

There are only three return codes: EC_VALUE_OK (0), EC_VALUE_ERR_PARAM (-1: null pointer, bit_length outside [1,64], bit_offset < 0, real not 8-bit aligned), EC_VALUE_ERR_RANGE (-2: bit_offset + bit_length > size * 8, same meaning on the read and write sides).

CategoryFunctionReturn typeRead/writeDescription
Bit-field readec_value_extract_u64intread-onlyReads an unsigned value of bit_length bits starting at bit_offset; returns EC_VALUE_OK / EC_VALUE_ERR_PARAM / EC_VALUE_ERR_RANGE
ec_value_extract_i64intread-onlySame, with two's complement sign extension according to bit_length
ec_value_extract_real32intread-onlyFixed-width 32-bit IEEE754; ignores bit_length and requires bit_offset % 8 == 0
ec_value_extract_real64intread-onlyFixed-width 64-bit IEEE754; semantics as real32
Boolean wrapperec_value_try_extract_i64boolread-onlytrue = the return code is EC_VALUE_OK; a null out returns false, and a failure leaves *out unchanged
ec_value_try_extract_real32boolread-onlySame
ec_value_try_extract_real64boolread-onlySame
Bit-field writeec_value_insert_real32intwrite-onlyFixed-width 32-bit write; bit-field read-modify-write, bits outside the field keep their original values; requires bit_offset % 8 == 0
ec_value_insert_real64intwrite-onlyFixed-width 64-bit write; semantics as real32
Type queryec_value_type_nameconst char*read-onlyDataType code → short English name (for example 3 → INT16, 50 → BIT3); returns a static string, borrowed read-only, must not be modified or released; unknown codes return a fallback name

NIC scanning and NIC selection​

Scan results come in two channels: the raw return code is preserved as-is (>= 0 is the slave count, 0 = the scan ran normally and the bus really has no slaves, which is not a failure), while the classified outcome is given by the entry points below. Negative codes other than -1 / -2 / -3 and the named NIC-open failure codes -1201..-1206 have no fixed sentinel; they are carried through at their original value.

CategoryFunctionReturn typeRead/writeDescription
Scan outcomeDarraEcatScanOutcomeFromCodeintread-onlyRaw return code → outcome: >= 0 is always normalised to DARRA_SCAN_SUCCESS (0 = scan completed, an empty bus is also 0); -1 / -2 / -3 are named; other negative codes are carried back at their original value
DarraEcatScanOutcomeIsUnknownintread-onlyA value other than 0 means the outcome is an unclassified raw negative code (outside the named codes); in that case the value is itself the raw error code and should be reported as-is
DarraEcatScanFailureReasondarra_scan_failure_reason_tread-onlyOutcome → failure reason; >= 0 returns DARRA_SCAN_REASON_NONE; named codes map to their reason; -1 and any other unrecognised negative code are classified as UNKNOWN (no invented reason on behalf of the driver)
DarraEcatScanFailureReasonTextconst char*read-onlyFailure reason → Chinese description; static string, no memory allocated
Scan resultsGetScannedSlaveCountintread-onlyNumber of slaves recorded by the most recent scan, used as the upper bound of the GetScannedSlaveInfo index
GetScannedSlaveInfoBOOLread-onlyReads the identity and topology fields of one scanned slave by index (vendor / product / revision / serial, name buffer, configured address, alias address, parent slave and port information); the name buffer is provided by the caller
ReadSlaveInfointread-onlyRuns one scan on the given NIC and records the slave details; returns the raw code (>= 0 slave count, < 0 error code)
QuickFindRedundantPairBatchintread-onlyFinds redundant ring pairs in a batch, returning the primary / secondary NIC indexes and the two WKC counters ring / total in one call; the output is not a slave count (a coupler contributes 0 and a servo contributes 3), and total - ring does not give the branch count either (the difference is the contribution of the other ports); returns the raw ring WKC, 0 = not paired
GetRingSlaveCountintread-onlyNumber of slaves on the ring measured by the most recent on-site topology calibration; 0 = not calibrated; a read-only scan does not update this value (for scan results see the output of QuickFindRedundantPairBatch)
NIC selectionEcNic_IsNonEthercatNameintread-onlyName blacklist verdict: 1 = matches the blacklist / a virtual NIC (not used for EtherCAT), 0 = does not; a purely local check that does not touch the bus
EcNic_PickAutoDetectintread-onlyAutomatically selects the primary / secondary NIC from a name list; 0 = selected, 1 = no slaves, -1 = invalid arguments; out_method gives 0 ring pair / 1 single end / 2 one by one / 3 no slaves
EcNic_DistributeQfbSlavesintread-onlyDistributes the WKC counters into primary and secondary slave counts by ring / total; 0 = distributed, 1 = fell back to raw enumeration, -1 = invalid arguments
EcNic_PickFirstUpintread-onlyTakes the index of the first NIC whose link is up; 1 = selected (writes out_idx), 0 = no NIC up, -1 = invalid arguments

Device and version information​

char* s = GetSerialNumber();   /* Internal static storage, borrowed read-only*/
printf("SN=%s\n", s); /* Do not free(s) / FreeMemory(s)*/
CategoryFunctionReturn typeRead/writeDescription
Device informationGetSerialNumberchar*read-onlyDevice serial number; the return value is internal static storage, borrowed read-only, and must not be passed to free() / FreeMemory() (releasing it crashes immediately)
GetDeviceNamechar*read-onlyDevice name; the return value is an internal cache, borrowed read-only, must not be released
GetDriverListchar*read-onlyDriver list; the return value is an internal cache, borrowed read-only, and releasing it corrupts the heap
Version informationGetDllVersionInfoconst version_info_t*read-onlyReturns a pointer to the internal version structure (major / minor / patch / build + build_date); no release needed

Licensing​

The license runtime fails closed to "not verified" whenever it is unavailable; there is no optimistic default. The verdict is always == LICENSE_VERIFIED; everything else, including unknown status codes, counts as not verified.

CategoryFunctionReturn typeRead/writeDescription
Status querylicense_get_statusdx_license_status_tread-onlyQueries the current license status; the only valid state is LICENSE_VERIFIED; internal status codes not listed collapse to LICENSE_NOT_VERIFIED, and a failed query or an unavailable runtime also returns not verified
Activationlicense_activateintwrite-onlySubmits the activation code, and the license runtime performs online activation and writes the credential; 0 = success, a value other than 0 = failure, -1 = exception; returns 3 when the runtime environment is not ready and writes the reason into err_buf where possible (may be NULL)
Expiry eventSetLicenseExpiredCallbackvoidwrite-onlyRegisters the license expiry callback; the callback arguments are master_index / reason_code / a static message string (the caller does not release it); passing NULL is equivalent to unregistering
UnsetLicenseExpiredCallbackvoidwrite-onlyUnregisters the license expiry callback, symmetric to the registration entry point, so that callbacks of expired objects do not linger in the runtime

Runtime component guard​

Before initializing a master and setting the NIC, use this group of entry points to confirm that the low-level real-time components are available; the probe itself does not throw.

CategoryFunctionReturn typeRead/writeDescription
Availability probedarra_kernel_probedarra_kernel_status_tread-onlyProbes whether the low-level components are available, without throwing; the values include DARRA_KERNEL_OK / NOT_INSTALLED / STOPPED / ACCESS_DENIED / SIGNATURE_FAIL / BLOCKED / DEVICE_MISSING / DISABLED / UNKNOWN_ERROR
Diagnostic informationdarra_kernel_status_messageconst char*read-onlyStatus code → readable Chinese message (UTF-8); static string, the caller does not release it
darra_kernel_installer_urlconst char*read-onlyInstaller download link; defaults to the official driver download page and can be overridden with the DARRA_INSTALLER_URL environment variable
One-line checkdarra_kernel_assert_availableintread-onlyOne-line check: 0 = available, otherwise returns the status code; the caller prints the message itself

Bind baseline and compatibility layer​

Raw entry points that return 0xFFFF have two mutually exclusive causes: a failed read from the runtime, or the shell fallback when the entry point is not bound. The baseline entry points separate the two: take a baseline before the call, then decide afterwards whether this call hit a missing entry point.

CategoryFunctionReturn typeRead/writeDescription
Bind baselineDarraEcat_BindBaselinevoidread-onlyTakes a baseline before calling a raw entry point, recording the cumulative number of runtime entry points missing and the last error code
DarraEcat_BindHitEntryMissingintread-onlyDecides after the call whether this call fell into the missing-entry fallback; a value other than 0 = hit. The test is "the missing count rose above the baseline" or "the error code flipped from something other than ENTRY_UNAVAILABLE to ENTRY_UNAVAILABLE"; only the flip counts, not a lingering value
Compatibility layerdarra_compat_load_dllintwrite-onlyCompatibility with the old load convention: does not load the runtime again, only checks whether the runtime environment is ready; 1 on success, 0 on failure; the path parameter is no longer used (the runtime environment decides the load path)
darra_compat_unload_dllvoidwrite-onlyCompatibility with the old unload convention: clears the handle only, does not unload the runtime (the module belongs to the runtime environment and lives as long as the process)

Last error code​

CategoryFunctionReturn typeRead/writeDescription
Error codeDarra_GetLastErrorintread-onlyReads the Windows error code of the most recent failed SDK call (the library and the caller share the same per-process TLS); always returns 0 on non-Windows platforms. Read it immediately after a failed network setup to distinguish 21 (not ready yet, transient, retry after a wait), 1168 (the NIC is not ready or unavailable and must be reconfigured through the official procedure), 2 (the underlying service does not exist, not installed), 170 (device busy); four driver instance LastError values can be carried with 170: 30 = RT real-time lanes exhausted (run fewer masters at once / let scanning reuse the master lane / reinstall with --rt-masters N), 2 = the instance is still held by another live handle (close the holder or restart the driver), 23 = the NIC is held by another master instance, 22 = the polling thread failed to start/rebuild; in addition, 20 = driver network initialization failed (the underlying NTSTATUS is passed through as-is) and 31 = the PASSIVE real-time admission budget was exhausted, set by the polling thread after StartRT succeeded — neither of these is a 170 reply; any other or unreadable value is reported as unknown together with the raw 170 + LastError number; the value is valid only at the moment of the failure, so do not read it several calls later

Mailbox gateway low-level configuration​

Low-level entry points that ordinary applications do not need to call directly. They write the slave ESC Sync Manager and FMMU registers directly, so the caller must ensure beforehand that the master is initialized and that the slave state allows configuration.

CategoryFunctionReturn typeRead/writeDescription
Sync ManagerConfigureSyncManagerBOOLwrite-onlyWrites the start address, length, control byte and enable bit by SM index
FMMUConfigureFMMUBOOLwrite-onlyWrites the logical address, mapping length, logical / physical start bits, type and enable bit by FMMU index
Output Sync ManagerEnableOutputSyncManagerBOOLwrite-onlyEnables the output Sync Manager with the OpOnly semantics of ETG.1500
DisableOutputSyncManagerBOOLwrite-onlyDisables the output Sync Manager

DC helpers​

Low-level entry points that ordinary applications do not need to call directly. The automatic shift switch affects how the master compensates DC drift; the Raw sync window entry point mirrors registers as they are and does not fold in whether DC SYNC0 is enabled.

CategoryFunctionReturn typeRead/writeDescription
Automatic shiftGetDCAutoShiftEnabledBOOLread-onlyQueries whether the master enables automatic DC drift shifting
SetDCAutoShiftEnabledvoidwrite-onlyEnables / disables automatic DC drift shifting
Sync windowGetSlaveSyncWindowStatusRawBOOLread-onlyRaw mirror: does not fold in whether DC SYNC0 is enabled, so a slave without SYNC0 may still report in_sync = TRUE; suitable only for diagnostics / forensics and register comparison. Do not use it to decide that "this slave is synchronized" — use the folding entry point GetSlaveSyncWindowStatus from the same header

Topology helpers​

Computes a static classification from each slave's port topology (slave index + physical port mask + entry port + parent slave / parent port); the algorithm is implemented once inside the runtime and the SDK does not re-derive it. phys_ap = 0 means that slave has no observable physical link; entry_port / parent_port = 0xFF means unknown or not filled in — do not read 0 as definitely P0.

CategoryFunctionReturn typeRead/writeDescription
Static topology v1TopoComputeRingBranchintread-onlyOutputs the total slave count / ring member count / branch count / closing-point slave index / shape (linear, ring, ring + branches); 0 = success, -1 = parameter error (including the SDK not being ready)
Static topology v2TopoComputeRingBranchExintread-onlyThe input and ring member output are the same as v1, with one extra chain_form at the end of the output (single active port at a linear end / single-port foldback at a chain end); meaningful only when mode is linear

For both generations of entry points, when ring_cap is too small the ring members are truncated to capacity and the difference is added to the branch count; to get the complete ring membership, make ring_cap at least the slave count. mode is the encoding of the static port model, which is not the same value set as runtime topology readings; do not cast or compare it directly.

Example​

Reading a PDO buffer with value encoding and decoding

#include <stdio.h>
#include <ethercat.h>

/* Input frame: bit0..15 = Statusword, bit16..31 = target REAL32; output frame: bit0..31 = actual REAL32*/
static void pdo_codec_demo(const uint8_t* in, int in_size,
uint8_t* out, int out_size) {
uint64_t statusword = 0;
float target = 0.0f;

if (ec_value_extract_u64(in, in_size, 0, 16, &statusword) == 0) {
printf("Statusword = 0x%04llX\n", (unsigned long long)statusword);
}
if (ec_value_try_extract_real32(in, in_size, 16, 32, &target)) {
printf("目标 = %.3f\n", target); /* Target = %.3f */
}

/* A value other than 0 = invalid parameter or out of range (EC_VALUE_ERR_PARAM / EC_VALUE_ERR_RANGE)*/
if (ec_value_insert_real32(out, out_size, 0, 32, target) != 0) {
fprintf(stderr, "输出帧写入失败\n"); /* Output frame write failed */
}
}

Classifying scan outcomes

#include <stdio.h>
#include <ethercat.h>

static void show_scan_result(const char* adapter) {
int native = ReadSlaveInfo(adapter); /* raw code: >= 0 slave count, < 0 error code*/
int outcome = DarraEcatScanOutcomeFromCode(native);

if (outcome >= 0) {
printf("扫描完成, 从站 %d 台\n", GetScannedSlaveCount()); /* Scan complete, %d slaves */
return;
}
if (DarraEcatScanOutcomeIsUnknown(outcome)) {
printf("未归类错误码 %d\n", outcome); /* The outcome value is itself the native error code*/
return;
}
printf("%s (原生码 %d)\n", /* %s (native code %d) */
DarraEcatScanFailureReasonText(DarraEcatScanFailureReason(outcome)), native);
}

Checking runtime component availability

#include <stdio.h>
#include <ethercat.h>

static int ensure_runtime(void) {
int rc = darra_kernel_assert_available(); /* 0 = available, otherwise a status code*/
if (rc != 0) {
fprintf(stderr, "EtherCAT 底层组件不可用 (status=%d): %s\n安装链接: %s\n", /* EtherCAT low-level component unavailable (status=%d): %s, install link: %s */
rc, darra_kernel_status_message(rc), darra_kernel_installer_url());
return 0;
}
return 1;
}

Version compatibility​

The current SDK version is 2.13.16. The SDK runtime, the driver and the GUI are upgraded together under the same version number; a MINOR or MAJOR upgrade requires reinstalling the matching driver.

The version that counts is the one in the official installer; the application layer does not need to query the DLL version.