Skip to main content

Python SDK overview

The Python package for EtherCAT master development, targeting 64-bit Windows (CPython 3.12) and providing real-time communication between the master and its slaves.

Installation​

pip install darra-ethercat-master
Installing the released wheel directly

You can also install the release package darra_ethercat_master-2.13.16-cp312-cp312-win_amd64.whl directly (it is the same package as pip install):

pip install darra_ethercat_master-2.13.16-cp312-cp312-win_amd64.whl

Download: https://download.darra.xyz/ethercat/python/darra_ethercat_master-cp312-cp312-win_amd64.whl

Distribution name and import name

The PyPI distribution name is darra-ethercat-master (the name to pass to pip install); the import name inside Python code is darra_ethercat (import darra_ethercat). The two are separate concepts (PEP 427) — do not mix them up.

Specifying the library path manually

When the runtime libraries provided with the SDK are not on the system search path, pass the dll_path argument when creating the master (the SDK selects the library for the current operating system automatically).

Requirements​

ItemRequirement
Operating systemWindows 10/11 (64-bit)
PythonPython 3.12 (64-bit Windows; wheel tag cp312-cp312-win_amd64, CPython 3.12 only, other major versions are not supported)
PrivilegesAdministrator
Real-time driverThe real-time runtime component must be installed (provided with the installer)

Runtime environment gating​

When the real-time runtime is not installed, is stopped, or access is denied, link setup and initialization fail. The module-level functions below probe ahead of time and hand a readable reason and an installation entry point to the application layer.

probe()​

from darra_ethercat.kernel_guard import probe

def probe() -> DarraKernelStatus

Probes the current state of the real-time runtime. It does not raise.

Returns:

  • DarraKernelStatus — status code (values are listed in get_status_message()); a missing runtime library, an older version that does not provide this entry point, or a code outside the enum are all reported as UnknownError

Example:

from darra_ethercat import DarraKernelStatus
from darra_ethercat.kernel_guard import probe

status = probe()
print("运行时可用" if status == DarraKernelStatus.Ok else f"状态: {status.name}") # Runtime available / state: {status.name}

assert_available()​

from darra_ethercat.kernel_guard import assert_available

def assert_available() -> None

Probes whether the real-time runtime is available: it returns normally when available and raises DarraKernelNotAvailableError when it is not. Call it before link setup entry points such as set_network() and from_json() so that a readable hint can be shown early; the SDK also probes once more at key entry points as a safety net.

Exceptions:

  • DarraKernelNotAvailableError — the runtime is not available. The exception object carries three fields: status (the DarraKernelStatus status code), message (a readable description in Chinese), installer_url (the installer download link)

Example:

from darra_ethercat import DarraKernelNotAvailableError
from darra_ethercat.kernel_guard import assert_available, open_installer_website

try:
assert_available()
except DarraKernelNotAvailableError as e:
print(e.message)
open_installer_website()

get_status_message(status)​

from darra_ethercat.kernel_guard import get_status_message

def get_status_message(status: DarraKernelStatus) -> str

Converts a status code into a readable Chinese message. When the text cannot be obtained it returns a generic fallback string and does not raise.

Parameters:

  • status (DarraKernelStatus) — status code

Returns:

  • str — a Chinese description; when the runtime libraries are unavailable or do not provide this entry point, generic fallback text is returned

Related structures:

from darra_ethercat import DarraKernelStatus

class DarraKernelStatus(IntEnum):
Ok = 0 # available
NotInstalled = 1 # not installed
Stopped = 2 # stopped
AccessDenied = 3 # access denied
SignatureFail = 4 # signature mismatch
Blocked = 5 # blocked
DeviceMissing = 6 # device missing
Disabled = 7 # disabled
UnknownError = 99 # cannot be determined

Example:

from darra_ethercat import DarraKernelStatus
from darra_ethercat.kernel_guard import get_status_message

print(get_status_message(DarraKernelStatus.NotInstalled))

get_installer_url()​

from darra_ethercat.kernel_guard import get_installer_url

def get_installer_url() -> str

Returns the installer download link, https://www.darrart.com/downloads/drivers by default; the deployment side can override it with the DARRA_INSTALLER_URL environment variable. When it cannot be obtained it falls back to the default link.

Returns:

  • str — the download link; never returns None

Example:

from darra_ethercat.kernel_guard import get_installer_url

print(f"下载安装包: {get_installer_url()}") # Download installer: {get_installer_url()}

open_installer_website()​

from darra_ethercat.kernel_guard import open_installer_website

def open_installer_website() -> bool

Opens the installer download link in the default browser. Call it after catching the runtime-unavailable condition to guide the user through completing the installation.

Returns:

  • bool — True means the browser was launched successfully; False means the link was empty or launching failed (environment problems such as a missing browser); a failure does not raise

Example:

from darra_ethercat.kernel_guard import open_installer_website

if not open_installer_website():
print("请手动打开下载页") # Please open the download page manually

Quick start​

Use the Darra configuration tool to scan the network, configure the slaves and export a DENI file; load it in code and communication is ready:

from darra_ethercat import EtherCATMaster, EcState

with EtherCATMaster() as master: # close() runs automatically when the with block exits
master.set_eni(r"C:\EtherCAT\MyProject.deni").build()
master.set_state(EcState.OP)
# Start communicating...

Alternative: specifying the NIC directly (no DENI)​

Without DENI, initialize the master by specifying the NIC name directly; to enumerate NICs use get_network_info() (see NICs and scanning) and take the one that has slaves:

from darra_ethercat import EtherCATMaster, EcState

# The NIC name is visible in the NIC list of the Darra configuration tool
master = EtherCATMaster()
count = master.set_network(r"\Device\NPF_{GUID}")
if count > 0:
master.build()
master.set_state(EcState.OP)

set_network() returns the number of slaves found (0 = empty bus: the NIC opened successfully but there are no slaves on the wire); a failure to open or bind the NIC raises RuntimeError and is never reported as 0 slaves.

Which one to use
  • DENI — production; loads the full set of ESI/PDO/DC parameters in one line, recommended.
  • Automatic search — demos / tooling applications / scenarios that do not need preconfigured startup parameters.
from darra_ethercat import EtherCATMaster, EcState

with EtherCATMaster() as master:
master.set_eni("config.deni")
count = master.set_network(r"\Device\NPF_{GUID}")
if count > 0:
master.set_state(EcState.OP)
master.start()
# close() is called automatically when master exits the with block

One-step initialization (JSON configuration)​

from darra_ethercat import EtherCATMaster

# target_state is numeric: 8 = EcState.OP
config = '{"adapter": "\\\\Device\\\\NPF_{GUID}", "target_state": 8}'
with EtherCATMaster.from_json(config) as master:
# Initialization is complete: the target state is reached and the PDO cycle is running
print(master.slave_count)
# ...

JSON configuration fields: adapter is the main NIC name (the same NIC name used by set_network()), target_state is the numeric state code, defaulting to 8 (EcState.OP), with values from the EcState enum; from_json_file("config.json") has the same semantics. For the full field list see Initialization.

Feature overview​

CapabilityDescription
One-step initializationfrom_json / from_json_file initialize from a JSON configuration in one step
State switchingset_state chains across levels INIT → PRE_OP → SAFE_OP → OP, running the startup parameters at each step automatically
Startup parameter pipelineslave.add_startup_param adds startup parameters in bulk; master.auto_startup applies them automatically
CiA 402 drive state machineslave.cia402 enable / fault reset / state parsing
PDO process datainputs_mapping / outputs_mapping map once and read the process image directly; inputs / outputs are whole-frame snapshots, input_array / output_array are byte-offset views of the process image (writes go through versioned transactions)
CoE SDOslave.coe.sdo_read / sdo_write and the typed sdo_read_value / sdo_write_value
Topology queryBuild and query the slave network topology tree
Mailbox gatewaymaster.mailbox_gateway provides an ETG.8200 UDP gateway so external tools can access the master / slave object dictionary. Product API
Real-time driverMinimum 31 µs PDO cycle; direct process-image reads or whole-frame copies

Complete example​

from darra_ethercat import EtherCATMaster, EcState

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

slave = master[1] # 1-based index

# CoE SDO read/write (a failed read returns None)
status = slave.coe.sdo_read_value(0x6041, 0, dtype='u16')
if status is not None:
print(f"状态字 = 0x{status:04X}") # Status word = 0x{status:04X}
slave.coe.sdo_write_value(0x6040, 0, 0x0006, dtype='u16')

# Topology query
for node in master.topology:
print(f"从站 {node['slave_index']}: 父={node['parent_index']}") # Slave {node['slave_index']}: parent={node['parent_index']}

Optional extensions​

import darra_ethercat.sugar activates the optional Pythonic extensions (the standard API is unaffected): chained queries such as slave in master / reversed(master) / master.at and master.where / master.first / master.group_by, an async for diagnostic stream, slave.summary() debug output, SlaveIdentityKey (a frozen dataclass usable as a set / dict key and unpackable), match-friendly state helpers such as classify_state, and the MasterLike / SlaveLike / CoELike Protocol static types. with master:, for slave in master, master[1] and len(master) are provided by the main SDK itself and need no sugar import.

Error code localisation​

Chinese descriptions for AL Status / SDO Abort come from the enum's own describe():

from darra_ethercat import EcALState, SDOError

al = EcALState(0x001A).describe() # AL Status description in Chinese
sdo = SDOError(0x06010000).describe() # SDO Abort description in Chinese

describe() prefers the Chinese text supplied by the library underneath. For EcALState, codes ≥ 0x8000 fall back to 厂商自定义错误码 (0x....) (SDK output, = vendor-defined error code) and other codes outside the table fall back to 未知(0x....) (SDK output, = unknown); for SDOError, codes outside the table fall back to 未知(0x........) (SDK output, = unknown). EcALState(值) can now also carry codes outside the table: it returns an instance that keeps the original value (int(...) yields the original code, and the name looks like AL_CODE_0x0038), and it no longer raises ValueError; as a result slave.al_status_code / master.error_code preserve the original value of unrecognised codes, and EcALState.UNKNOWN (0xFFFF) means only "not read / not sampled". Likewise, composite states such as EcState(0x14) / EcState(0x18) can be constructed directly (the name looks like STATE_0x1A), resolved with has_error / base_state / format(). English descriptions are not provided at present.

describe_native_result()​

from darra_ethercat import describe_native_result

def describe_native_result(code: int) -> str

Translates an operation result code into a Chinese description, for showing the result of APIs that return an int result code (such as load_config_json(), validate_config()) directly to the user.

Parameters:

  • code (int) — operation result code

Returns:

  • str — for a known code, a Chinese description; for an unknown code, 未识别的结果码 (SDK output, = unrecognized result code) followed by the raw number, together with a prompt to report the raw code — it does not guess the meaning and does not fold the result into 失败 (SDK output, = failure)
Scope

This function recognises 0 and negative result codes (-1 invalid master index, -4 invalid parameter, -24 state transition timeout, and so on). master.last_error records system error codes (for example the NIC-related 21 / 1168 / 5023), which belong to a separate numbering scheme — do not translate them with this function.

Example:

from darra_ethercat import describe_native_result

rc = master.load_config_json(deni_text)
if rc < 0:
print(f"配置加载失败: {describe_native_result(rc)}") # Configuration load failed: {describe_native_result(rc)}

Version compatibility​

Current SDK version 2.13.16. The runtime libraries, real-time runtime and GUI share one version number; a MINOR/MAJOR upgrade requires reinstalling the matching runtime.

Key changes in 2.5.x​

CategoryContent
AddedMDP modular device orchestration (modular devices such as GCAN-8200 are configured automatically when entering OP)
AddedAsync mailbox transaction API MailboxTransaction (real async worker)
AddedPer-group expected WKC accessor master.get_group_expected_wkc(group)
AddedSoE IDN encoding/decoding and runtime bit-level alignment (encode_idn / decode_idn)
Fixedhas_esi_dc_sync follows the real ESI DC OpMode declaration; the DC capability gate follows the real ESI declaration
FixedSlave PDO byte properties (ibytes / obytes and so on) renamed to match the runtime
RemovedDead / ghost APIs: the PDO cycle statistics family, QuickSlaveCountRedundant, ScanSlaveCount*, SetStateCacheUpdateInterval and others