<p align="center"><img src="https://download.darra.xyz/ethercat/static/icon.png" alt="Darra EtherCAT Master" width="96" height="96"></p>

# Darra EtherCAT Master · C++ SDK

> **商业 EtherCAT 主站协议栈 · 功能齐全 · 易于集成 · 高可靠**
> *Commercial EtherCAT master · Feature-complete · Easy to integrate · High reliability*

`[ Windows · Linux · MCU ]`  `[ 6 语言 SDK / 6 languages ]`  `[ 全协议 / Full protocols ]`  `[ 高可靠 / Highly reliable ]`  `[ ethercat.darra.xyz ]`

---

## 为什么选 Darra

|  | SOEM 开源 | 专用主站板卡 | **Darra EtherCAT** |
|---|---|---|---|
| 协议覆盖 | 部分 | 视厂商 | **全协议 + 功能安全** |
| 拓扑 | 简单 | 视厂商 | **复杂拓扑 + 热插拔** |
| SDK 语言 | C 一种 | 厂商专用 | **6 语言一致** |
| 安装 | 自行集成 | 硬件 + IDE | **包管理器一行** |
| 配置 | 手工写代码 | 厂商工具 | **图形化一键导出** |
| 实时抖动 | 视 RT 系统 | 硬件保障 | **配 DarraRT ≤ 1 µs** |
| 可靠性 | 用户自实现 | 视厂商 | **冗余 + 故障自愈** |
| 诊断 | 基础 | 视厂商 | **完整在线诊断** |

## Why Darra

|  | SOEM (Open-source) | Dedicated master card | **Darra EtherCAT** |
|---|---|---|---|
| Protocols | Partial | Vendor-dependent | **Full + functional safety** |
| Topology | Simple | Vendor-dependent | **Complex + hot-plug** |
| Languages | C only | Vendor-specific | **6 byte-consistent languages** |
| Install | Build yourself | Hardware + IDE | **One line via package manager** |
| Config | Hand-coded | Vendor tool | **GUI one-click export** |
| RT jitter | Depends on RT stack | Hardware-guaranteed | **≤ 1 µs with DarraRT** |
| Reliability | DIY | Vendor-dependent | **Redundancy + auto-recovery** |
| Diagnostics | Basic | Vendor-dependent | **Full live diagnostics** |

---
## 版本兼容 · Version compatibility

- **同 MAJOR.MINOR 内 PATCH 任意升级互相兼容** (例 X.Y.1 ↔ X.Y.2 ↔ X.Y.3) — SDK 包管理器一行升级即可, **不需重装驱动**
- **MAJOR 或 MINOR 变化 → 必须重装驱动** — 驱动 .sys 内嵌了 Core.dll SHA256 白名单, 主/次版本变 → hash 变 → MS 必须重签 → 客户必须升级驱动
- `master.Build()` 自动比对 Core.dll ↔ 驱动版本, 不匹配 → 日志 Warning

| 升级类型 | 重装驱动? | 客户操作 |
|---|---|---|
| **PATCH** (X.Y.1 → X.Y.2) | ❌ 不需要 | `dotnet add package` / `pip install --upgrade` |
| **MINOR** (X.Y.x → X.(Y+1).0) | ✅ 必须 | 升级 SDK + 重装驱动安装包 (.msi) |
| **MAJOR** (X.Y.Z → (X+1).0.0) | ✅ 必须 | 同上 + 看 CHANGELOG (可能 API 变更) |

*PATCH within same MAJOR.MINOR is mutually compatible (e.g. X.Y.1 ↔ X.Y.2) — package manager upgrade only, no driver reinstall. MINOR or MAJOR change requires driver reinstall (Core.dll hash baked into kernel sys whitelist).*

## 启动性能 · Startup performance

- **DENI 加载比从零扫描快 50%** (实测 7.4s vs 15.2s)
- 推荐生产环境用 DENI 文件 (Darra 配置工具一键导出, 预存 ESI/PDO/DC/启动参数)
- 调试 / 演示场景用自动配 (无 DENI 也能跑, SDK 实时扫从站身份)

*DENI loading is 50% faster than full scan (7.4s vs 15.2s). Use DENI for production, auto-config for debugging.*

---
## 自动健康检查 · Auto health checks

`master.Build()` 时自动跑 (无需客户调用):

- **驱动版本比对 / Driver version match** — Core.dll 直读 `\\.\DarraRT` 拿内核驱动版本, 与 SDK 自身版本比 MAJOR.MINOR. 不匹配 → SDK 日志 Warning, 客户立刻看到 "需要升级驱动" 提示.
- **RT 核隔离配置 / RT core isolation** — 后台异步读 `HKLM\SOFTWARE\Darra\EtherCAT` marker. 缺失 (MSI 安装时未跑 CoreOptimize) → SDK 日志 Warning, 提示用户调 `EnsureRtIsolation(elevated:true)` 自动修复 (仅 C#, 跨语言 SDK 提示重装).

*Auto-runs on `master.Build()`: driver version match (Core.dll vs kernel) and RT core isolation registry check. Mismatches log warnings, no manual API call needed.*

## 错误码本地化 · Error code localization

AL Status Code 描述支持双语, 全部下沉到 Core.dll (VMP 保护):

| 接口 | 语言 | 用途 |
|---|---|---|
| `AL_StatusCode_GetDescription(code)` | English (默认) | 5 SDK 跨语言客户使用 |
| `AL_StatusCode_GetDescriptionChinese(code)` | 中文 | C# / Python 主界面 UI 使用 |
| `AL_StatusCode_GetRecoveryHint(code)` | English | 默认 |
| `AL_StatusCode_GetRecoveryHintChinese(code)` | 中文 | UI 显示 |

*AL Status descriptions are bilingual: English by default for SDKs, dedicated Chinese API for UI applications. All translations are baked into Core.dll with VMP protection.*

---
## 核心能力 · Key capabilities

### 初始化 · Init

- 🟢 **DENI 文件 / DENI file** (★ 推荐 / Recommended) — 配置工具一键导出, 1 行加载. *One-click export, single-line load.*
- 🟡 **ESI 自动配 / Auto-config** — SDK 按从站身份自动套参数. *Auto-applies defaults per slave identity.*
- 🟠 **零配置 / Zero-config** — 无 ESI 用从站 CoE 字典自动配. *Reads slave's own object dictionary.*

### 协议与可靠性 · Protocols & reliability

- **全协议 / Full mailbox protocols** (含功能安全 SIL3 / incl. FSoE SIL3)
- **DC 同步 / Distributed Clocks** ≤ 1 µs (配 DarraRT)
- **冗余 + 故障自愈 / Redundancy + auto-recovery** — 零丢帧切换 / zero-loss failover
- **完整在线诊断 / Full live diagnostics**

### 高级 API · High-level APIs

- **一行初始化 / One-line init** — 5 步合 1. *5 steps in a single call.*
- **状态链 / State chain** — 自动 INIT → OP. *Auto walk to OP with diagnostics.*
- **CiA402 一行使能 / One-line drive enable**.
- **PDO 类型化读写 / Typed PDO I/O** — 自动字节序. *Automatic endianness.*
- **邮箱网关 / Mailbox gateway** — 兼容 TwinCAT 等第三方工具. *Compatible with TwinCAT and 3rd-party tools.*
---

## Install

从 <https://ethercat.darra.xyz/release/> 下载 zip,解压后:

```
darra-ethercat-cpp-<v>-win-x64/
├── include/darra/ethercat.hpp
├── include/darra/slave.hpp
├── include/ethercat.h
├── lib/Darra.Core.lib
├── lib/Darra.Core.protocol.lib
├── lib/darra-ethercat-advanced.lib
├── bin/Darra.Core.dll
├── examples/
└── README.md
```

### CMake

```cmake
find_package(DarraCore CONFIG REQUIRED)
target_link_libraries(my_app PRIVATE Darra::Core)
```

### Manual

```bash
g++ -std=c++17 app.cpp -lDarraCore -o app
```

```cmd
cl /EHsc /std:c++17 /I include app.cpp lib\Darra.Core.lib lib\Darra.Core.protocol.lib lib\darra-ethercat-advanced.lib ws2_32.lib
```

> **要求**: C++17 编译器 (GCC 9+ / MSVC 2019+) · Windows 10/11 x64 · 首次运行需以管理员安装 DarraRT 实时内核驱动.

---

## 快捷使用 · Quick start

最简流程: **DENI 一行加载 → 进 OP → 邮箱基本读写**.

```cpp
#include <cstring>
#include <iostream>
#include <darra/ethercat.hpp>

int main() {
    darra::EtherCATMaster master;
    master.SetENI("C:\\EtherCAT\\MyProject.deni");   // DENI 一行加载
    master.SetState(darra::EcState::OP);             // 自动 INIT → PreOp → SafeOp → OP

    auto& slave = master.GetSlave(0);

    // 邮箱读 — 两种风格任选:

    //  ① 基本: std::vector<uint8_t> + 位运算
    auto data = slave.coe().SDORead(0x6041, 0x00);
    uint16_t statusword = data[0] | (data[1] << 8);

    //  ② 高级: std::memcpy 类型化 (一行, C++20 可用 std::bit_cast)
    uint16_t sw;
    std::memcpy(&sw, slave.coe().SDORead(0x6041, 0x00).data(), sizeof(sw));

    // 邮箱基本写: 字节版
    int32_t target = 100000;
    slave.coe().SDOWrite(0x607A, 0x00,
                         reinterpret_cast<uint8_t*>(&target), sizeof(target));

    return 0;  // RAII 自动析构
}
```

### OP 过程数据交互 (PDO I/O) · Process data in OP

进 OP 后, **过程数据 (PDO) 由内核每个总线周期自动实时收发**, 与 CoE (非周期邮箱) 不同: 不调"读/写", 从站对象上的零拷贝指针拿到的永远是最新一周期, 写出的会被下一周期自动 LRW 发出。

```cpp
auto& slave = master.GetSlave(0);

// 读从站输入 PDO (TxPDO, 从站→主站) — 零拷贝指针:
auto* in = static_cast<uint8_t*>(slave.InputDataPointer());
uint16_t statusword = in ? (in[0] | (in[1] << 8)) : 0;

// 写从站输出 PDO (RxPDO, 主站→从站), 下一周期自动发出:
auto* out = static_cast<uint8_t*>(slave.OutputDataPointer());
if (out) out[0] = 0xFF;
```

---

## 高级使用 · Advanced

**自动搜网卡 + ESI 自动配** · **诊断 / 邮箱网关**.

```cpp
#include <algorithm>
#include <darra/ethercat.hpp>

int main() {
    // ① 自动搜网卡 (取有从站的那张 NIC)
    auto nets = darra::statics::GetNetworkInfo(/*need_slave_count=*/true);
    auto it = std::find_if(nets.begin(), nets.end(),
                           [](const auto& n){ return n.slaveNum > 0; });
    if (it == nets.end()) return -1;

    // ② ESI 目录 + 自动配 (无 DENI 场景)
    darra::EtherCATMaster master;
    master.SetEsiFiles("C:\\Esi");
    master.SetNetwork(it->name);
    master.EnableAutoStartup();
    master.SetState(darra::EcState::OP);

    // ③ 邮箱网关 (TwinCAT / 第三方工具远程透传 SDO, ETG.8200)
    darra::statics::MailboxGateway::Start(/*master_index=*/0, /*port=*/8200);

    return 0;
}
```

> **更多 API · More APIs** — 完整参考: <https://ethercat.darra.xyz/docs/sdk/cpp>

---

## 6 语言 SDK 家族 · 6-language SDK family

字节级一致的 CRC / 枚举 / 错误码,业务代码可平滑跨语言。

| Language | Package | Registry |
|---|---|---|
| **C++** | `darra-ethercat-cpp` | [Releases](https://ethercat.darra.xyz/release/) |
| **C** | `darra-ethercat-c` | [Releases](https://ethercat.darra.xyz/release/) |
| **C#** | `Darra.EtherCAT.Master` | [NuGet](https://www.nuget.org/packages/Darra.EtherCAT.Master/) |
| **Python** | `darra-ethercat-master` | [PyPI](https://pypi.org/project/darra-ethercat-master/) |
| **Java** | `xyz.darra:darra-ethercat-master` | [Maven Central](https://central.sonatype.com/artifact/xyz.darra/darra-ethercat-master) |
| **Rust** | `darra-ethercat-master` | [crates.io](https://crates.io/crates/darra-ethercat-master) |

---

## 文档 · Documentation

- **官网 · Homepage**: <https://ethercat.darra.xyz>
- **C++ SDK 文档**: <https://ethercat.darra.xyz/docs/sdk/cpp>
- **快速开始**: <https://ethercat.darra.xyz/docs/quick-start>
- **协议详解**: <https://ethercat.darra.xyz/docs/ethercat>


> **⚠️ 关于"微秒级"实时性能 · About microsecond real-time**
> 本 SDK **强制配合 DarraRT 实时内核驱动 + 兼容硬件** 使用. 微秒级实时由 SDK + DarraRT 共同提供.
> DarraRT 通过 **CPU 核心隔离 + I/O APIC 中断重定向 + LVT 屏蔽 + 干净抖动统计** 显著降低 SMI 干扰
> (但**不能完全抑制**, SMM 属硬件层中断, 完全抑制需 BIOS/UEFI 配合).
> DarraRT 需另行安装 (非自动安装); SDK 启动时若未检测到, 会提示获取下载链接.
> 我们另提供 **硬实时隔离部署方案**, 满足更严苛的实时与功能安全需求.
> 详见 [DarraRT 驱动说明](https://ethercat.darra.xyz/docs/driver).
>
> *This SDK **requires the DarraRT real-time kernel driver and supported hardware** as runtime companions.
> Microsecond-level performance is delivered by SDK + DarraRT together. DarraRT mitigates SMI via
> **CPU core isolation, I/O APIC redirect, LVT masking, and clean jitter accounting**, though it cannot
> fully suppress SMI (SMM is a hardware-level interrupt; full suppression requires BIOS/UEFI tuning).
> DarraRT must be installed separately (not auto-installed); the SDK prompts a download link on startup if not detected.
> A **hard real-time isolated deployment** is also available for stricter real-time and functional-safety requirements.*

---
