Initialization
The master index is ≥1; 0 is always invalid (0 is not accepted). With multiple masters, every API must be passed a valid index explicitly, and initialization must already be complete before the call.
Initializing from a DENI file exported by the Darra configuration tool is strongly recommended. A DENI file contains the complete network configuration (ports, slaves, PDO mapping, DC settings and so on), which keeps the configuration consistent and correct.
Constructors
EtherCATMaster()
class EtherCATMaster:
def __init__(self, dll_path: Optional[str] = None,
master_index: Optional[int] = None) -> None
Creates an EtherCAT master instance.
Parameters:
dll_path(str, optional) — path to the SDK runtime; searched automatically when Nonemaster_index(int, optional) — master index to use; assigned automatically when None
Example:
from darra_ethercat import EtherCATMaster, EcState
with EtherCATMaster() as master:
# Load the configuration file
master.set_eni(r"C:\EtherCAT\MyProject.deni")
# Set the network and scan for slaves
slave_count = master.set_network(r"\Device\NPF_{GUID}")
print(f"发现 {slave_count} 个从站") # Found {slave_count} slaves
# Transition to OP
master.set_state(EcState.OP)
# Start the PDO cycle
master.start()
Context manager
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 execution leaves the with block
Configuration methods
set_eni()
def set_eni(self, eni_path: str) -> "EtherCATMaster"
Loads an ENI / DENI / JSON configuration file. The file is read as UTF-8 and handed to the SDK runtime: DENI XML is detected and parsed as DENI XML (NIC selection + live scan + full configuration), JSON is parsed as JSON configuration. Returns the same instance, so calls can be chained.
Bus configuration is loaded only through set_eni() / load_config_json(); other configuration entry points are not part of the product API.
load_config_json()
def load_config_json(self, json_str: str) -> int
Loads configuration from a JSON or DENI XML string (loaded by the SDK runtime).
Parameters:
json_str(str) — JSON or DENI XML text
Returns:
int— return code from the SDK runtime
Example:
with open(r"C:\EtherCAT\MyProject.deni", encoding="utf-8") as f:
rc = master.load_config_json(f.read())
set_network()
def set_network(self, adapter: str, redundant_adapter: str = "") -> int
Sets the network adapter and scans for slaves.
Parameters:
adapter(str) — primary NIC name (NIC device name)redundant_adapter(str) — redundant NIC name; an empty string means redundancy is not used
Returns:
int— number of slaves found0— failure (the runtime0xFFFFfailure sentinel is normalized) or success with no slaves on the bus. The two meanings are told apart withmaster.last_error:21= runtime not ready (transient, retryable),1168= NIC binding not ready,5023= data gate closed (license not granted, unrelated to the NIC)
Example:
# Windows
slave_count = master.set_network(r"\Device\NPF_{GUID}")
# Linux
# slave_count = master.set_network("eth0")
# Redundancy mode
slave_count = master.set_network(
r"\Device\NPF_{PRIMARY-GUID}",
r"\Device\NPF_{SECONDARY-GUID}"
)
Asynchronous variant: await master.set_network_async(adapter, redundant_adapter="", progress=None, cancel=None). It returns the same slave count and does not block the calling thread.
set_esi_file()
def set_esi_file(self, file_path: str) -> "EtherCATMaster"
Loads a single ESI file or a directory. The ESI is loaded immediately (a directory is loaded in full); ESI parsing is done by the SDK runtime. After a scan, build() matches and binds the slaves automatically. Returns the same instance, so calls can be chained.
If a DENI file is used, loading the ESI separately is usually unnecessary.
The entry points accept paths in either UTF-8 or the system ANSI code page; on Windows the Python binding encodes them as mbcs (the system ANSI code page) before passing them on, so paths containing Chinese characters open correctly. On Linux, UTF-8 is used.
> 0 = number of devices in the file; 0 = nothing added (already loaded and skipped / no <Device> / XML parse failure); -1 = the file cannot be opened (path does not exist / no permission / the encoding cannot represent it; a WARNING is logged). set_esi_file() returns self and does not surface that return code.
set_esi_files()
def set_esi_files(self, path: str) -> "EtherCATMaster"
Loads an ESI file or a directory. Loading is immediate: a directory is loaded in full, a file is loaded on its own. On Windows the Python binding encodes the path as mbcs (UTF-8 and ANSI are both accepted). Returns the same instance, so calls can be chained. A load that returns -1 means the file cannot be opened; this method does not surface the return code.
enable_auto_startup()
def enable_auto_startup(self) -> "EtherCATMaster"
Marks that the slaves need automatic configuration. Returns the same instance, so calls can be chained.
Automatic configuration (AutoConfigureSM, run at build()) computes and writes the SM2/SM3 physical lengths from the PDO Assignment / Mapping metadata in each slave's startup parameters. Only slaves that have startup parameters are processed; slaves without them are skipped.
With a DENI file, the scan result from the set_network() stage is matched automatically against the slave configuration in the DENI (device and revision matching follows the CheckRevisionNo policy declared by the ESI device). If the network topology does not match the DENI, set_state() returns False, and the slaves that did not reach the target state plus the state step that stalled are written to the log.
Both methods take effect as soon as they are called — build() never touches the port:
set_eni()loads a DENI configuration: it picks the port on the spot, binds the NIC and scans the bus;set_network()binds the NIC you give it on the spot, scans the bus and returns the slave count.
JSON configuration carries no port (the top level holds only slave configuration; a port field is rejected as an unknown key), so with JSON the port is decided solely by set_network().
When both are used, the later call overrides the conflicting configuration from the earlier one:
# set_eni called last -> the port configuration in the DENI file is used
master.set_network(r"\Device\NPF_{GUID}")
master.set_eni(r"C:\config.deni") # <- the port in the DENI overrides set_network
# set_network called last -> the port from set_network overrides the DENI
master.set_eni(r"C:\config.deni")
master.set_network(r"\Device\NPF_{GUID}") # <- overrides the port in the DENI
Switching the port means rebinding the NIC and rescanning the bus (set_network() returns the new slave count) — it is not just flipping one configuration item. The slave configuration, PDO mapping, DC settings and so on from the DENI file are always retained; only the port itself is replaced.
set_cycle_time()
def set_cycle_time(self, time_ns: int) -> None
Sets the PDO cycle time in nanoseconds.
Example:
master.set_cycle_time(1_000_000) # 1ms
build()
def build(self) -> "EtherCATMaster"
Finishes the chained initialization: if an ESI was loaded through set_esi_file() / set_esi_files(), the slaves are matched and bound automatically after the scan; if enable_auto_startup() was set, automatic configuration runs; a runtime compatibility log entry is then recorded. Returns the same instance.
Asynchronous variant: await master.build_async(progress=None, cancel=None). The whole build flow runs on a background thread and returns a build result dictionary without blocking the calling thread.
One-step initialization
EtherCATMaster.from_json()
@classmethod
def from_json(cls, json_config: str, dll_path: Optional[str] = None) -> "EtherCATMaster"
Initializes the master in one step from a JSON configuration string (internally: initialization, NIC setup, configuration loading, automatic SM configuration, state transition to target_state, then PDO start, in that order).
Parameters:
json_config(str) — configuration string in JSON formatdll_path(str, optional) — path to the SDK runtime
Returns:
EtherCATMaster— an initialized master instance
JSON configuration format:
{
"adapter": "\\Device\\NPF_{GUID}",
"adapter_redundant": "",
"target_state": 8,
"slaves": [
{
"index": 1,
"startup_params": [
{
"index": 7186, "sub_index": 0,
"data_hex": "00", "transition": 0, "timing": 1
}
]
}
]
}
Field reference:
adapter(required) primary NIC name;adapter_redundantredundant NIC name, an empty string means no redundancytarget_statenumeric state code, default 8 (EcState.OP); see theEcStateenum for the valuesslaves[].indexslave index (starting at 1);startup_params[]holds that slave's startup parameters- Startup parameters:
index/sub_indexare numeric (0x1C12 is written as 7186);data_hexis a hex byte string;transitionis one ofTRANS_IP=0/TRANS_PS=1/TRANS_SO=2/TRANS_OS=3/TRANS_SP=4/TRANS_PI=5(see the startup parameter constants indarra_ethercat);timingisTIMING_BEFORE=0/TIMING_AFTER=1;priority(lower value wins) andca(Complete Access) are optional - The PDO cycle is not configured in JSON; set it with
set_cycle_time()/config.loop_cycle
Example:
import json
config = json.dumps({
"adapter": r"\Device\NPF_{GUID}",
"target_state": 8 # EcState.OP
})
with EtherCATMaster.from_json(config) as master:
# One-step initialization is complete: the master is in OP and the PDO cycle is running
print(f"从站数: {master.slave_count}") # Slave count: {master.slave_count}
EtherCATMaster.from_json_file()
@classmethod
def from_json_file(cls, json_file_path: str, dll_path: Optional[str] = None) -> "EtherCATMaster"
One-step initialization from a JSON file (same semantics as from_json(); the file is read and the same initialization chain runs).
Example:
with EtherCATMaster.from_json_file("config.json") as master:
# One-step initialization is complete: the master is in OP and the PDO cycle is running
print(f"从站数: {master.slave_count}") # Slave count: {master.slave_count}
Resource release
close()
def close(self) -> bool
Closes and releases the master resources (safe stop → callback deregistration → release of the SDK runtime resources). True means released (repeated calls are idempotent); False means the release did not complete (resources are still in use), and the call may be retried; the reason is in last_close_error.
Asynchronous variants: await master.close_async() / await master.dispose_async() (dispose() is an alias of close(), and so is dispose_async). Both queue on this master's serial gate and do not run concurrently with other asynchronous bus operations; a successful release returns None, and if the synchronous close() did not complete the release (False) they raise RuntimeError (reason in last_close_error), so "not closed" is never silently reported as "closed". This differs from the synchronous close(), which returns bool.
__enter__ / __exit__
Supports automatic resource release with the with statement. If close() did not complete the release and no exception is in flight, __exit__ raises RuntimeError to report this faithfully.
with master: is built into the main SDK; async with master: and the one-line open plus cleanup form with EtherCATMaster.opening(nic, state=OP) as master: come from the darra_ethercat.sugar subpackage, which must be imported first with import darra_ethercat.sugar (see Python-specific sugar).
NICs and scanning
NIC selection → quick scan → full scan → cancel.
Feature overview
| Step | Entry point | Purpose |
|---|---|---|
| NIC selection | get_network_info | Enumerates the physical wired NICs usable as the primary port, optionally with per-port slave counts |
| Quick scan | quick_slave_count | Slave count on a single port without reading EEPROM; used for DENI / drop-down counts |
| Full scan | scan_slaves | Reads EEPROM / topology per slave and returns the selectable slave list |
| Cancel | abort_scan | Interrupts a scan in progress |
The old entry points are no longer provided; new code should migrate to the entries above. Python exposes only the single-port quick scan quick_slave_count() (no batch quick-scan wrapper); loop over adapters for per-port verdicts.
NIC selection
Enumeration covers physical wired ports only: virtual NICs, WiFi and TAP do not appear in the list; USB wired NICs such as ASIX are kept. Each NIC is flagged through bound_protocol as bound to the real-time environment or not (1 = bound, 0 = not bound); an unbound port is not a candidate for the primary port.
get_network_info()
from darra_ethercat import get_network_info
def get_network_info(dll,
is_redundant: bool = False,
need_slaves_num: bool = False) -> List[NetworkInfo]
Retrieves the NIC list (physical wired ports; binding state in bound_protocol). The first parameter is an SDK runtime instance.
Parameters:
dll— SDK runtime instanceis_redundant(bool) — whether to enumerate in redundancy mode; defaultFalseneed_slaves_num(bool) — whether to also probe the slave count on each NIC (slower); defaultFalse
Returns:
List[NetworkInfo]— NIC list; an empty list means there really is no usable physical wired port
Related structures:
@dataclass
class NetworkInfo:
name: str # NIC adapter name
desc: str # adapter description
mac: str # MAC address (format aa:bb:cc:dd:ee:ff)
slave_num: Optional[int] # total slave count (set when need_slaves_num=True); None when not measured / occupied by a local master
redundant_slave_num: Optional[int] # redundancy ring-pair result = ring path WKC, not a slave count; positive = ring path WKC, None = single-port wiring / not measured
bound_protocol: Optional[int] # whether bound to the real-time environment (1 = bound, 0 = not bound; set when need_slaves_num=True)
scan_status: NicScanStatus # classification of this scan result (see the table below)
@property
def occupied_by_master(self) -> bool # whether the scan was skipped because a local master occupies the NIC (a fact, not a failure)
class NicScanStatus(IntEnum):
NOT_MEASURED = 0 # not measured in this run (did not take part in the scan / opening the NIC failed) — not the same as 0 slaves
IDLE_NO_SLAVE = 1 # measured empty port: scanned, and there really are 0 slaves
FOUND = 2 # measured, slaves present
OCCUPIED_BY_MASTER = 3 # a local master occupies this NIC; the scan is skipped by design (a fact, not a failure)
Distinguishing the three kinds of 0:
IDLE_NO_SLAVE— measured empty port: scanned, and there really are 0 slavesOCCUPIED_BY_MASTER— a local master is using this port, so the scan is skipped by design; it does not mean the bus is emptyNOT_MEASURED— not measured in this run (did not take part in the scan / opening the NIC failed)
Once a master has established its link, the NIC it is using cannot be reopened by a scan. The SDK skips that port by design and marks it
NicScanStatus.OCCUPIED_BY_MASTER. Such a port is not rescanned: slave_num being None (not 0) only means
"not measured"; it does not mean the bus is empty. To get its slave count, read the master's own master.slave_count
(a read-only snapshot). With single-port wiring, redundant_slave_num is None as well.
Example:
from darra_ethercat import get_network_info
# dll is the SDK runtime instance
adapters = get_network_info(dll, need_slaves_num=True)
for adapter in adapters:
count = adapter.slave_num
print(f"{adapter.desc}: {count if count is not None else '未量到'} 个从站") # {adapter.desc}: {count if count is not None else 'not measured'} slaves
Quick scan
quick_slave_count()
from darra_ethercat import quick_slave_count
def quick_slave_count(dll, adapter_name: str) -> int
# Can also be called as a static method on EtherCATMaster
EtherCATMaster.quick_slave_count(adapter: str, dll_path: Optional[str] = None) -> int
Fast slave count (no EEPROM read). Used for DENI / drop-down counts; to select slaves, use the full scan scan_slaves(...).
Parameters:
dll— SDK runtime instance (the static method form takesdll_pathinstead; searched automatically whenNone)adapter_name/adapter(str) — primary network adapter name, must not be empty
Returns:
int—>= 0is the slave count (0= measured empty port, a normal result); a negative value is not a slave count but the raw error code, and must not be treated as 0 slaves
Example:
from darra_ethercat import quick_slave_count
count = quick_slave_count(dll, r"\Device\NPF_{GUID}")
if count < 0:
print(f"快扫失败, 错误码 {count}") # Quick scan failed, error code {count}
else:
print(f"快扫从站数: {count}") # Quick scan slave count: {count}
Full scan
scan_slaves()
from darra_ethercat import scan_slaves
def scan_slaves(dll, adapter_name: str,
secondary_adapter: Optional[str] = None) -> List[ScannedSlaveInfo]
Full scan: reads EEPROM / topology and returns the selectable slave list. For a quick DENI count use quick_slave_count(). When the count is valid the list must not be empty (if details are not ready, placeholder entries "slave N" preserve the count).
Parameters:
dll— SDK runtime instanceadapter_name(str) — primary network adapter name, must not be emptysecondary_adapter(str, optional) — redundant network adapter name;None= single-port scan
Returns:
List[ScannedSlaveInfo]— slave list. An empty list means the scan ran to completion and there really are no slaves on the bus (the runtime returns0; this is a normal result, not a failure).
Raises:
ScanError— raised when the scan fails; failures are no longer folded into an empty list.native_codekeeps the raw error code andoutcomegives the outcome classification
Related structures:
@dataclass
class ScannedSlaveInfo:
index: int # slave index (1-based)
name: str # slave name
vendor_id: int # vendor ID
product_code: int # product code
revision_number: int # revision number
serial_number: int # serial number
config_addr: int # physical configuration address
alias_addr: int # alias address
parent_index: int # parent slave index (0 = the master is the parent node)
topology: int # topology type: 0 = no link, 1 = endpoint, 2 = intermediate node, 3 = branch point, 4 = crossing point
active_ports: int # active port bitmap
entry_port: int # entry port
parent_port: int # port number on the parent slave
parent_port_type: int # physical type of the parent port (0=not implemented, 1=not configured, 2=EBUS, 3=MII)
physical_type: int # physical port type register (0x0007)
depth: int # topology depth
from darra_ethercat import ScanOutcome
class ScanOutcome(IntEnum):
SUCCESS = 0 # scan completed, there really are no slaves on the bus
OPEN_FAILED = -1 # opening the NIC failed / invalid parameter (unclassified)
TOPOLOGY_XACT_REFUSED = -2 # topology write transaction refused, this scan is incomplete
SCAN_CLOSING = -3 # the previous scan is still winding down, retry shortly
# named reasons for NIC open failure
OPEN_ACCESS_DENIED = -1201 # the driver safety gate denied access
OPEN_OCCUPIED = -1202 # the port is in use
OPEN_NOT_READY = -1203 # the driver or NIC is not ready
OPEN_NIC_NOT_FOUND = -1204 # this NIC is not in the driver NIC pool
OPEN_LINK_DOWN = -1205 # the port link is down
OPEN_BAD_MEDIA = -1206 # non-wired medium, cannot serve as the EtherCAT primary port
# topology verdict (not a NIC open failure)
OPEN_TOPOLOGY_LOOP = -1208 # zero responses and the linear bus is wired as a ring: break the ring to restore linear wiring
ScanOutcome tells whether the scan completed normally; a failure outcome is treated as "scan not completed" and is never mistaken for an empty bus.
NIC open failures carry named reason codes; handle them by the real cause instead of treating every -1 as the same fault:
| Code | Meaning | Action |
|---|---|---|
-1201 | the driver safety gate denied access | Retry after a restart; if it still fails, reinstall with the official installer and confirm that the runtime and the driver are a matched pair |
-1202 | the port is in use | Close the program using that port (another master instance) and retry |
-1203 | the driver or NIC is not ready | Wait a moment and retry |
-1204 | this NIC is not in the driver NIC pool | Select another port; if it still fails, reinstall the driver |
-1205 | the port link is down | Check the cable and the slave power supply |
-1206 | non-wired medium (wireless / Bluetooth / loopback / tunnel) | Use a wired Ethernet NIC as the primary port |
-1208(ScanOutcome.OPEN_TOPOLOGY_LOOP)is not a NIC open failure: it means zero responses (really 0 slaves) and that the linear bus has been wired as a ring. The remedy = leave the OUT port of the last slave unconnected again, restoring linear wiring; the opposite of the remedy for -1205(cable not connected). classify_scan_failure(-1208) gives ScanFailureReason.TOPOLOGY_LOOP.
To convert an outcome code into a reason enum, use classify_scan_failure():
from darra_ethercat import scan_slaves, ScanError, ScanFailureReason, classify_scan_failure
try:
slaves = scan_slaves(dll, r"\Device\NPF_{GUID}")
except ScanError as e:
reason = classify_scan_failure(e.outcome) # for example ScanFailureReason.ACCESS_DENIED
print(f"扫描失败: 原因 {reason.name}, 原始码 {e.native_code}") # Scan failed: reason {reason.name}, raw code {e.native_code}
The asynchronous scan_async(...) runs the scan on a background thread and also returns a ScannedSlaveInfo list; cancellation uses a scan-specific interrupt channel and does not interfere with master state transitions.
Example:
from darra_ethercat import scan_slaves, ScanError
# dll is the SDK runtime instance
try:
slaves = scan_slaves(dll, r"\Device\NPF_{GUID}")
if not slaves:
print("扫描完成,总线上没有从站") # Scan complete, no slaves on the bus
for s in slaves:
print(f"[{s.index}] {s.name} VID=0x{s.vendor_id:08X}")
except ScanError as e:
print(f"扫描失败: 结局 {e.outcome}, 错误码 {e.native_code}") # Scan failed: outcome {e.outcome}, error code {e.native_code}
Cancel
abort_scan()
from darra_ethercat import abort_scan
def abort_scan(dll) -> None
Aborts the slave scan currently in progress (used when closing a window or cancelling an operation, to interrupt a blocking scan quickly). This is a module-level function; the master instance has no method of the same name.
A cancel interrupts only the current run; the abort flag stays set until it is cleared. Before the next scan, reset it with reset_scan_abort(dll) and then start the quick and full scans as usual:
from darra_ethercat import abort_scan, reset_scan_abort
abort_scan(dll) # cancel the current scan
reset_scan_abort(dll) # reset the abort flag
Example:
import threading
# Scan in a background thread
scan_thread = threading.Thread(target=lambda: scan_slaves(dll, r"\Device\NPF_{GUID}"))
scan_thread.start()
# The user clicks cancel
abort_scan(dll)
scan_thread.join()
abort_network()
def abort_network(self) -> None
Aborts network operations: sets the network-layer abort flag so that blocked calls — state transitions, mailbox round trips and so on — return as early as possible. It can be called from any thread (the cancel button in the UI uses this path).
The abort flag belongs to the whole process: blocked calls on every active master instance return, regardless of which instance raised it. It interrupts blocked calls only and does not stop the PDO data cycle; scanning uses a separate cancel channel (abort_scan), and this method does not abort a scan. The cancel parameter of the asynchronous API cancels by master name and does not affect other masters; prefer cancel when cancelling asynchronous operations.
Example:
import threading
from darra_ethercat import EcState
worker = threading.Thread(target=lambda: master.set_state(EcState.OP))
worker.start()
master.abort_network() # make blocked state transitions return as early as possible
worker.join()
master.reset_abort_network() # reset the flag, later operations proceed normally
reset_abort_network()
def reset_abort_network(self) -> None
Clears the network-layer abort flag and prepares for the next round of operations. Reset it after the aborted call has actually exited; resetting early while the call has not yet returned may let it block again.
Example:
master.abort_network()
# ...waiting for the aborted call to return...
master.reset_abort_network()
Full example
from darra_ethercat import get_network_info, quick_slave_count, scan_slaves, abort_scan
# 1. NIC selection: pick a physical wired port that has slaves
target = next((a for a in get_network_info(dll, need_slaves_num=True)
if (a.slave_num or 0) > 0), None)
if target is None:
raise SystemExit("没有可用网卡") # No NIC available
# 2. Quick scan: count only
count = quick_slave_count(dll, target.name)
# 3. Full scan: per-slave details
slaves = scan_slaves(dll, target.name)
print(f"{target.desc} 快扫 {count} 站,完整扫描 {len(slaves)} 站") # {target.desc} quick scan {count} slaves, full scan {len(slaves)} slaves
# 4. Cancel: used when the scan runs on a background thread
abort_scan(dll)
Scanned slave information
Every item returned by scan_slaves() is a ScannedSlaveInfo. Besides the basic fields (index / name / vendor_id and so on), the class also provides the following read-only properties and methods, so topology and identity can be displayed directly.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Identity | vendor_id_hex | str | read-only | Eight-digit hexadecimal string of the vendor ID |
| product_code_hex | str | read-only | Hexadecimal string of the product code | |
| revision_number_hex | str | read-only | Hexadecimal string of the revision number | |
| Address | alias_addr_hex | str | read-only | Four-digit hexadecimal string of the alias address |
| config_addr_hex | str | read-only | Hexadecimal string of the physical configuration address | |
| Topology | entry_port_type | int | read-only | Physical type of the entry port: 0 = not implemented / 1 = not configured / 2 = EBUS / 3 = MII / -1 = unknown |
| is_coupler | bool | read-only | Whether this is a coupler (conservative test: if the criterion does not hold it returns False, which does not mean it is confirmed not to be a coupler) | |
| parent_key | Optional[int] | read-only | Parent node key; None when the parent node is the master |
The hexadecimal properties only format the value for display (vendor_id_hex is always 8 digits, alias_addr_hex always 4 digits; the others use their actual length). The numeric value itself still comes from the corresponding integer field.
get_port_type(port)
def get_port_type(self, port: int) -> int
Reads the physical type of the specified port (parsed from physical_type, 2 bits per port).
Parameters:
port(int) — port number, valid range 0..3
Returns:
int—0= not implemented,1= not configured,2= EBUS,3= MII;-1= unknown (port number outside 0..3, for example the0xFFsentinel when the parent port is undefined)
Example:
for s in slaves:
if s.get_port_type(0) == 3: # P0 is MII
print(f"[{s.index}] 主口设备") # [{s.index}] primary-port device
ScannedSlaveInfo.get_port_type_string(port_type)
@staticmethod
def get_port_type_string(port_type: int) -> str
Converts a port type value into a short label for logs and table display.
Parameters:
port_type(int) — port type value (the value returned byget_port_type()/entry_port_type)
Returns:
str—0→N/A,1→NC,2→EBUS,3→MII,-1→未知(SDK output, = unknown), other values →?
Example:
from darra_ethercat import ScannedSlaveInfo
text = ScannedSlaveInfo.get_port_type_string(s.entry_port_type)
print(f"[{s.index}] 入口端口: {text}") # [{s.index}] entry port: {text}
Full example
Manual initialization flow
from darra_ethercat import EtherCATMaster, EcState
with EtherCATMaster() as master:
# Set the network adapter
slave_count = master.set_network(r"\Device\NPF_{GUID}")
if slave_count == 0:
print("未发现从站") # No slaves found
exit()
# Set the PDO cycle
master.set_cycle_time(1_000_000)
# State transition
master.set_state(EcState.OP)
# Start the PDO cycle
master.start()
# Access a slave
slave = master[1]
status = slave.coe.sdo_read_value(0x6041, 0, dtype='u16')
print(f"StatusWord = 0x{status:04X}" if status else "读取失败") # Read failed
import time
time.sleep(5)
master.stop()
Using a DENI file (recommended)
from darra_ethercat import EtherCATMaster, EcState
with EtherCATMaster() as master:
master.set_eni(r"C:\EtherCAT\MyProject.deni")
slave_count = master.set_network(r"\Device\NPF_{GUID}")
master.set_state(EcState.OP)
master.start()
Scanning ports dynamically
from darra_ethercat import EtherCATMaster, EcState, get_network_info
# dll is the SDK runtime instance
adapters = get_network_info(dll, need_slaves_num=True)
target = next((a for a in adapters if (a.slave_num or 0) > 0), None)
if target is None:
exit()
with EtherCATMaster() as master:
master.set_esi_files(r"C:\ESI")
master.enable_auto_startup()
slave_count = master.set_network(target.name)
if slave_count > 0:
master.set_state(EcState.OP)
master.start()
Redundancy mode
from darra_ethercat import EtherCATMaster, EcState
with EtherCATMaster() as master:
master.set_redundancy_mode(2)
master.set_eni(r"C:\config.deni")
slave_count = master.set_network(
r"\Device\NPF_{PRIMARY}",
r"\Device\NPF_{SECONDARY}"
)
master.set_state(EcState.OP)
master.start()
Multiple instances (independent buses on multiple NICs)
Each master instance manages one independent EtherCAT bus on a different NIC.
- Each instance must use a different NIC — the same NIC cannot be used by several instances at the same time
- CPU cores are assigned automatically — each instance takes a different CPU core
from darra_ethercat import EtherCATMaster, EcState, get_network_info
# dll is the SDK runtime instance
adapters = [a for a in get_network_info(dll, need_slaves_num=True)
if (a.slave_num or 0) > 0]
master1 = EtherCATMaster()
master1.set_network(adapters[0].name)
master1.set_state(EcState.OP)
master1.start()
master2 = EtherCATMaster()
master2.set_network(adapters[1].name)
master2.set_state(EcState.OP)
master2.start()