メインコンテンツへスキップ

SoE(Servo over EtherCAT)

SoE プロトコルは、SERCOS サーボ通信プロトコルを EtherCAT メールボックスの中で運ぶ。SERCOS 互換のサーボドライバ向けである。

SoE& 参照は slave.GetSoE() で取得する。​

SoE と CoE

多くの EtherCAT サーボドライバは CoE + CiA 402 のスタックを使う。SoE はSERCOS 互換のドライバ(Bosch Rexroth IndraDrive シリーズなど)専用である。 両者を混在させることはできない。どちらをサポートするかはハードウェア次第である。

位置 ID と診断 ID を混同しない

S-0-0011(IDN 0x000B)と S-0-0012(IDN 0x000C)は Class 1 / Class 2 の診断コード(UINT16)であり、位置値ではない。位置フィードバックには S-0-0051(IDN 0x0033)、位置指令には S-0-0047(IDN 0x002F)を使う。診断コードを 32bit の位置として読むと、物理的な意味を持たない値になる。読み戻した位置は符号付きで、原点とスケールはドライバのスケーリングパラメータで決まる。SDK は変換を行わない。

メソッド概要​

区分メソッド型読み書き説明
パラメータ読み書きReadバイト配列読み取り専用IDN の生パラメータバイトを読む。失敗時は空配列
パラメータ読み書きWritebool書込み専用IDN に生パラメータバイトを書く。失敗時は false
型付き読み取りReadInt16 / ReadInt32 / ReadUInt16 / ReadUInt32 / ReadFloat / ReadDouble / ReadStringstd::optional読み取り専用型指定でデータ値を読む(リトルエンディアンでデコード)。失敗時は空
型付き書き込みWriteInt16 / WriteInt32 / WriteUInt16 / WriteUInt32 / WriteFloat / WriteDouble / WriteStringbool書込み専用型指定でデータ値を書く(リトルエンディアンでエンコード)。失敗時は false
メタデータReadName文字列または空読み取り専用IDN パラメータ名を読む。読めない場合は空
メタデータReadUnit文字列または空読み取り専用IDN パラメータ単位を読む。読めない場合は空
メタデータReadAttributes / WriteAttributeSoEAttributes または空 / bool読み取り専用 / 書込み専用IDN 属性ビットフィールドを読み書きする
メタデータReadMinValue / ReadMaxValue / ReadDefaultValueバイト配列読み取り専用最小値 / 最大値 / 既定値を読む
メタデータReadDataStateoptional uint16読み取り専用データステータスワード(Element 0x01)を読む
パラメータ情報GetAvailableIDNsIDN リスト読み取り専用スレーブがサポートする IDN をすべて列挙する
パラメータ情報GetParameterInfoSoEParameter読み取り専用名称 / 単位 / 属性 / 現在値 / 最小 / 最大 / 既定を一回の呼び出しで取得する
パラメータ情報FormatValueWithAttributes文字列読み取り専用静的ヘルパ。生バイトをデータ型に従って読みやすいテキストに整形する
マッピングGetIDNMappingServoMappingInfo読み取り専用現在のドライブ AT/MDT マッピング構成を読む
マッピングGetAllDriveMappingsマッピング辞書読み取り専用ドライブスロット 8 個を走査してマッピングを集める
プロシジャコマンドExecuteCommandbool読み書きプロシジャコマンドを起動し、完了またはエラーまでポーリングする
通知監視EnableNotificationbool書き込み指定 IDN の値変化監視を有効にする。false の場合はローカルポーリングのみ可能で、その後 PollNotifications で変化を取り出す
通知監視DisableNotification / DisableAllNotificationsbool書込み専用本物の購読解除(ハードウェア側の購読解除を含む)。失敗した項目は再試行のために残す
通知監視NotifyCancelFailureCountuint32_t読み取り専用ハードウェア購読解除失敗の累積カウント(S-0-0127 に 0 を書く)
通知監視PollNotificationsイベントリスト読み取り専用監視中の IDN をポーリングし、今回のポーリングでの変化イベントを返す
通知監視GetMonitoredIDNsIDN リスト読み取り専用現在監視中の IDN
エラー照会GetLastSoEError列挙型または空読み取り専用直近の Read / Write の失敗理由
エラー照会GetLastSoEErrorCodeoptional SoEErrorCode読み取り専用ETG.5003 の拡張エラーコードフィールド
エラー照会SetLastSoEErrorCodevoid書込み専用ETG.5003 の拡張エラーコードフィールドに書く
エラー照会ClearLastSoEErrorCodevoid書込み専用ETG.5003 の拡張エラーコードフィールドを消す

SERCOS の IDN 体系​

SoE はドライブパラメータを**IDN(Identification Number)**でアドレス指定する。各 IDN は 16bit の番号で、一つのパラメータ(位置、速度、制御ワードなど)を表す。

IDN の命名規則:

プレフィックス範囲説明
S-x-xxxx0x0000 – 0x7FFFSERCOS 標準パラメータ(全ベンダ共通)
P-x-xxxx0x8000 – 0xBFFF製品固有パラメータ
P-x-xxxx0xC000 – 0xFFFFベンダ定義パラメータ

主な標準 IDN(サーボ制御関連。その他の IDN の意味はデバイスマニュアルを参照):

IDNSERCOS 名説明データ型
S-0-0001 (0x0001)Cycle Time通信サイクルタイムuint、us、読み取り専用
S-0-0047 (0x002F)Position Command位置指令値int、inc
S-0-0051 (0x0033)Position Feedback 1位置フィードバック値int、inc
S-0-0064 (0x0040)Drive Control Wordドライブ制御ワードushort
S-0-0071 (0x0047)Drive Status Wordドライブステータスワードushort、読み取り専用

要素フラグ — IDN の「層」を読み分ける:

フラグ意味
0x01データ状態
0x02パラメータ名(文字列)
0x04属性(データ型 / 長さ / アクセス権のビットフィールド)
0x08単位(文字列)
0x10最小値
0x20最大値
0x40データ値(既定。最もよく使う)
0x80既定値

SoEElementFlags​

C++ ラッパは、Element Flags のビットマスクを enum class SoEElementFlags : uint8_t で表す。operator| / operator& のオーバーロードと明示的な ToByte() 変換を備え、素の uint8_t の代わりに Read(idn, flags) / Write(idn, ..., flags) へそのまま渡せる。

enum class SoEElementFlags : uint8_t {
None = 0x00,
DataStatus = 0x01, // データステータスワード(valid/invalid/busy)
Name = 0x02, // IDN 名称文字列
Attribute = 0x04, // データ属性(タイプ、長さ、浮動小数点精度など)
Unit = 0x08, // 単位文字列
Min = 0x10, // 最小値
Max = 0x20, // 最大値
Value = 0x40, // 動作データ値(最も一般的。既定)
Default = 0x80 // 既定値
};

inline constexpr SoEElementFlags operator|(SoEElementFlags, SoEElementFlags);
inline constexpr SoEElementFlags operator&(SoEElementFlags, SoEElementFlags);
inline constexpr uint8_t ToByte (SoEElementFlags);

例:

using darra::ethercat::SoEElementFlags;

// Value + Unit を同時に取る
auto flags = SoEElementFlags::Value | SoEElementFlags::Unit;
auto raw = soe.Read(0x0033, ToByte(flags));

SoEIdnTriple / EncodeIdn / DecodeIdn​

ETG.6220 は 16bit の IDN を 3 つのフィールドに分ける。is_standard(S/P)、parameter_set(0..7)、data_block(0..0x0FFF)。SDK はデコード / 組み立て用のヘルパ関数二つとトリプル構造体を提供し、ベンダをまたぐ IDN 文字列の変換を楽にする(例: "S-0-0051" → 0x0033)。

struct SoEIdnTriple {
bool is_standard; // true = S- 標準、false = P- 製品/メーカ
uint8_t parameter_set; // 0..7
uint16_t data_block; // 0..0x0FFF
};

inline uint16_t EncodeIdn(bool is_standard, uint8_t parameter_set, uint16_t data_block);
inline SoEIdnTriple DecodeIdn(uint16_t idn);
  • EncodeIdn(...) — トリプル → 16bit IDN(S-0-0051 → 0x0033)
  • DecodeIdn(idn) — 16bit IDN → トリプル(表示 / 検証用)

SDK は SERCOS IDN 文字列と 16bit 数値の相互変換も提供する。

// "S-0-0040" / "P-1-0123" 文字列 → 16 ビット IDN。形式が不正なら false を返す
inline bool TryParseSercosIdn(const std::string& text, uint16_t& idn_out);
// 16 ビット IDN → "S-x-xxxx" / "P-x-xxxx" 文字列
inline std::string FormatSercosIdn(uint16_t idn);

例:

using darra::ethercat::EncodeIdn;
using darra::ethercat::DecodeIdn;
using darra::ethercat::TryParseSercosIdn;
using darra::ethercat::FormatSercosIdn;

// "S-0-0051" 位置フィードバック値 → 0x0033
uint16_t idn = EncodeIdn(/*is_standard*/ true, /*set*/ 0, /*block*/ 51);

auto t = DecodeIdn(idn);
printf("%s-%u-%04u\n", t.is_standard ? "S" : "P", t.parameter_set, t.data_block);
// 出力:S-0-0051

// 文字列との相互変換
uint16_t parsed = 0;
if (TryParseSercosIdn("S-0-0040", parsed))
printf("%s -> 0x%04X\n", FormatSercosIdn(parsed).c_str(), parsed);

基本的な読み書き​

Read()​

std::vector<uint8_t> Read(uint16_t idn, uint8_t elementFlags = 0x40,
int timeoutMs = 500) const;

IDN パラメータの生バイトを読む。失敗時は空ベクタを返す。既定の elementFlags 0x40 はデータ値を意味する。複数バイト値は ETG ワイヤ順でリトルエンディアンに格納される。空ベクータの場合、「読み取りに失敗した」か「この要素には操作データが無い」かを、GetLastSoEError() でもう一度切り分ける必要がある。

引数:

  • idn(uint16_t)— IDN 番号
  • elementFlags(uint8_t)— 要素フラグ(既定 0x40 = データ値)
  • timeoutMs(int)— タイムアウト(ミリ秒)

戻り値:

  • std::vector<uint8_t> — 読み取ったデータ。失敗時は空ベクタ

例:

// 通信サイクル時間(S-0-0001)を読み取る。戻り値は ETG リトルエンディアン
auto data = soe.Read(0x0001, 0x40);
if (data.size() >= 4) {
uint32_t cycleTime = static_cast<uint32_t>(data[0])
| (static_cast<uint32_t>(data[1]) << 8)
| (static_cast<uint32_t>(data[2]) << 16)
| (static_cast<uint32_t>(data[3]) << 24);
printf("周期时间: %u μs\n", cycleTime); // サイクルタイム: %u µs
}

Write()​

bool Write(uint16_t idn, const void* data, int dataLen,
uint8_t elementFlags = 0x40, int timeoutMs = 500) const;

IDN パラメータに書く。

引数:

  • idn(uint16_t)— IDN 番号
  • data(const void*)— 書き込むデータへのポインタ
  • dataLen(int)— データ長(バイト)
  • elementFlags(uint8_t)— 要素フラグ(既定 0x40 = データ値)
  • timeoutMs(int)— タイムアウト(ミリ秒)

戻り値:

  • bool — 成功時は true

例:

auto& soe = master.GetSlave(1).GetSoE();

// 位置フィードバック(S-0-0051)を読み取る。リトルエンディアンを手動でデコード
auto pos_data = soe.Read(0x0033);
if (pos_data.size() >= 4) {
int32_t pos = static_cast<int32_t>(
static_cast<uint32_t>(pos_data[0])
| (static_cast<uint32_t>(pos_data[1]) << 8)
| (static_cast<uint32_t>(pos_data[2]) << 16)
| (static_cast<uint32_t>(pos_data[3]) << 24));
printf("位置反馈: %d\n", pos); // 位置フィードバック: %d
}

// 制御ワード(S-0-0064)を書き込む
uint16_t cw = 0x0006;
soe.Write(0x0040, &cw, sizeof(cw));

型付き読み取り​

型付き読み取りメソッドはすべて同じシグネチャを持つ。引数は (uint16_t idn, int timeoutMs = 500) で、対応する std::optional<T> を返す。

区分メソッド型読み書き説明
型付き読み取りReadInt16()std::optional<int16_t>読み取り専用16bit 符号付き整数を読む
ReadInt32()std::optional<int32_t>読み取り専用32bit 符号付き整数を読む
ReadUInt16()std::optional<uint16_t>読み取り専用16bit 符号なし整数を読む
ReadUInt32()std::optional<uint32_t>読み取り専用32bit 符号なし整数を読む
ReadFloat()std::optional<float>読み取り専用単精度浮動小数点を読む
ReadDouble()std::optional<double>読み取り専用倍精度浮動小数点を読む
ReadString()std::optional<std::string>読み取り専用文字列を読む

例:

auto& soe = master.GetSlave(1).GetSoE();

// 位置フィードバック(S-0-0051)を読み取る。読み取り失敗は nullopt であり 0 ではない
auto actualPos = soe.ReadInt32(0x0033);
if (actualPos) printf("位置反馈: %d\n", *actualPos); // 位置フィードバック: %d
else printf("位置读取失败\n"); // 位置の読み取りに失敗しました

// ドライバステータスワード(S-0-0071)を読み取る
auto status = soe.ReadUInt16(0x0047);
if (status) printf("状态字: 0x%04X\n", *status); // ステータスワード: 0x%04X

// パラメータ名を読み取る(名称の読み取りには ReadName を使う。ReadString ではない)
auto name = soe.ReadName(0x0033);
if (name) printf("参数名: %s\n", name->c_str()); // パラメータ名: %s

型付き書き込み​

型付き書き込みメソッドはすべて同じシグネチャを持つ。引数は (uint16_t idn, T value, int timeoutMs = 500) で、bool を返す。

区分メソッド型読み書き説明
型付き書き込みWriteInt16()int16_t書込み専用16bit 符号付き整数を書く
WriteInt32()int32_t書込み専用32bit 符号付き整数を書く
WriteUInt16()uint16_t書込み専用16bit 符号なし整数を書く
WriteUInt32()uint32_t書込み専用32bit 符号なし整数を書く
WriteFloat()float書込み専用単精度浮動小数点を書く
WriteDouble()double書込み専用倍精度浮動小数点を書く
WriteString()const std::string&書込み専用文字列を書く

例:

auto& soe = master.GetSlave(1).GetSoE();

// 位置指令(S-0-0047)を設定する
soe.WriteInt32(0x002F, 50000);

// 制御ワード(S-0-0064)を書き込む
soe.WriteUInt16(0x0040, 0x0006);

メタデータの読み取り​

ReadName()​

std::optional<std::string> ReadName(uint16_t idn, int timeoutMs = 500) const;

IDN パラメータ名(Element 0x02)を読む。読めない場合は空を返す。

引数:

  • idn(uint16_t)— IDN 番号
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • std::optional<std::string> — パラメータ名。読めない場合は std::nullopt

ReadUnit()​

std::optional<std::string> ReadUnit(uint16_t idn, int timeoutMs = 500) const;

IDN パラメータ単位(Element 0x08)を読む。読めない場合は空を返す。

引数:

  • idn(uint16_t)— IDN 番号
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • std::optional<std::string> — パラメータ単位。読めない場合は std::nullopt

ReadAttributes()​

std::optional<SoEAttributes> ReadAttributes(uint16_t idn, int timeoutMs = 500) const;

IDN パラメータの属性(データ型、長さ、アクセス権ビットフィールドなど)を読む。

引数:

  • idn(uint16_t)— IDN 番号
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • std::optional<SoEAttributes> — 属性オブジェクト。失敗時は std::nullopt

WriteAttribute()​

bool WriteAttribute(uint16_t idn, uint32_t attrValue, int timeoutMs = 500) const;

IDN の属性ビットフィールド(Element 0x04)に書く。32 ビットは ETG 順でリトルエンディアンに組み立てる。属性ビットフィールドのレイアウトは SoEAttributes のデコード規約を参照。

引数:

  • idn(uint16_t)— IDN 番号
  • attrValue(uint32_t)— 生の 32bit 属性ビットフィールド
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • bool — 成功時は true、失敗時は false

ReadMinValue / ReadMaxValue / ReadDefaultValue​

std::vector<uint8_t> ReadMinValue(uint16_t idn, int timeoutMs = 500) const;
std::vector<uint8_t> ReadMaxValue(uint16_t idn, int timeoutMs = 500) const;
std::vector<uint8_t> ReadDefaultValue(uint16_t idn, int timeoutMs = 500) const;

IDN パラメータの最小値(0x10)、最大値(0x20)、既定値(0x80)を読む。失敗時は空配列を返す。ReadMin() / ReadMax() は最小値 / 最大値の便宜的な別名(同じデータ)であり、ReadIDNList() は GetAvailableIDNs() と等価である。

引数:

  • idn(uint16_t)— IDN 番号
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • std::vector<uint8_t> — 生の要素バイト。失敗時は空配列

例:

auto& soe = master.GetSlave(1).GetSoE();

auto name = soe.ReadName(0x0033);
auto unit = soe.ReadUnit(0x0033);
auto attrs = soe.ReadAttributes(0x0033);
auto minVal = soe.ReadMinValue(0x0033);
auto maxVal = soe.ReadMaxValue(0x0033);

if (name) printf("参数: %s", name->c_str()); // パラメータ: %s
if (unit) printf(" (%s)", unit->c_str());
printf("\n");

if (attrs) {
printf("数据类型: %d, 列表=%s, 命令=%s\n", // データ型: %d、リスト=%s、コマンド=%s
static_cast<int>(attrs->DataType),
attrs->IsList ? "是" : "否",
attrs->IsCommand ? "是" : "否");
}

if (minVal.size() >= 4 && maxVal.size() >= 4) {
auto le32 = [](const std::vector<uint8_t>& d) {
return static_cast<int32_t>(
static_cast<uint32_t>(d[0]) | (static_cast<uint32_t>(d[1]) << 8)
| (static_cast<uint32_t>(d[2]) << 16) | (static_cast<uint32_t>(d[3]) << 24));
};
printf("范围: %d - %d\n", le32(minVal), le32(maxVal)); // 範囲は %d - %d
}

パラメータ情報​

GetAvailableIDNs()​

std::vector<uint16_t> GetAvailableIDNs(int timeoutMs = 5000) const;

スレーブがサポートする IDN の一覧を取得する。

引数:

  • timeoutMs (int) — タイムアウト時間(ミリ秒、デフォルト 5000)

戻り値:

  • std::vector<uint16_t> — IDN 番号の一覧

GetParameterInfo()​

SoEParameter GetParameterInfo(uint16_t idn, int timeoutMs = 5000) const;

IDN パラメータの完全な情報(名称、単位、属性、現在値、最小値 / 最大値など)を取得する。

引数:

  • idn(uint16_t)— IDN 番号
  • timeoutMs (int) — タイムアウト時間(ミリ秒、デフォルト 5000)

戻り値:

  • SoEParameter — 完全なパラメータ情報

関連構造体:

struct SoEParameter {
uint16_t IDN; // IDN 番号
std::string Name; // パラメータ名
std::string Unit; // 単位
SoEAttributes Attributes; // 属性(データタイプ、長さなど)
std::vector<uint8_t> Value; // 現在値
std::vector<uint8_t> DefaultValue; // 既定値
std::vector<uint8_t> MinValue; // 最小値
std::vector<uint8_t> MaxValue; // 最大値

std::string Category() const; // カテゴリ("Standard" / "Product" / "Vendor")
std::string SercosIDN() const; // SERCOS IDN 形式(例:"S-0-0001")
bool IsReadOnly() const; // 読み取り専用かどうか
std::string AccessMode() const; // アクセス権("RO" / "RW" / "RW*")
std::string FormattedValue() const; // フォーマット済みの現在値
std::string FormattedMinValue() const; // フォーマット済みの最小値
std::string FormattedMaxValue() const; // フォーマット済みの最大値
std::string FormattedDefaultValue() const; // フォーマット済みの既定値
};
struct SoEAttributes {
uint16_t EvaluationFactor; // 評価係数
uint8_t Length; // データ長
bool IsList; // リストかどうか
bool IsCommand; // コマンドかどうか
SoEDataType DataType; // データタイプ
uint8_t Decimals; // 小数桁数
bool WriteProtectedPreOp; // PreOp 状態の書き込み保護
bool WriteProtectedSafeOp; // SafeOp 状態の書き込み保護
bool WriteProtectedOp; // Op 状態の書き込み保護

std::string AccessMode() const; // アクセス権文字列("RO", "RW", "RW*")
};
enum class SoEDataType : uint8_t {
Binary = 0, // バイナリ
UInt = 1, // 符号なし整数
Int = 2, // 符号付き整数
Hexadecimal = 3, // 十六進
String = 4, // 文字列
IDN = 5, // IDN 参照
Float = 6, // 浮動小数点数
Parameter = 7 // パラメータ
};

例:

auto& soe = master.GetSlave(1).GetSoE();
auto param = soe.GetParameterInfo(0x0033);
printf("IDN: %s - %s\n", param.SercosIDN().c_str(), param.Name.c_str());
printf("单位: %s, 访问: %s\n", param.Unit.c_str(), param.AccessMode().c_str()); // 単位: %s、アクセス: %s
printf("当前值: %s\n", param.FormattedValue().c_str()); // 現在の値: %s
printf("范围: %s - %s\n", param.FormattedMinValue().c_str(), param.FormattedMaxValue().c_str()); // 範囲は %s - %s

FormatValueWithAttributes()​

static std::string FormatValueWithAttributes(const std::vector<uint8_t>& data,
const SoEAttributes& attr);

静的ヘルパーメソッド。生バイトを attr.DataType に従って読みやすいテキストにデコードする。複数バイトの数値は、ホストのバイト順にかかわらず、常に ETG ワイヤ順でリトルエンディアンにデコードする。

引数:

  • data(const std::vector<uint8_t>&)— 生バイト。通常は SoEParameter の Value / DefaultValue / MinValue / MaxValue
  • attr(const SoEAttributes&)— パラメータ属性。どのデータ型として解釈するかを決める

戻り値:

  • std::string — 整形済みテキスト。data が空の場合は N/A を返す

整形規則:

  • Binary — 空白区切りの大文字十六進バイト列
  • UInt / Int — 1 / 2 / 4 / 8 バイトのリトルエンディアンを十進にデコード。符号付き型は二の補数として解釈する
  • Hexadecimal — データが 4 バイト以下のときは 0x プレフィックス付きの大文字十六進を出力する
  • String — 末尾の NUL を取り除いたテキスト
  • Float — 4 / 8 バイトのリトルエンディアン IEEE754。小数第 6 位まで保持する
  • IDN — IDN 0xXXXX を出力する
  • その他の型、またはデコード失敗 — 十六進バイト列にフォールバックする

例:

auto param = soe.GetParameterInfo(0x0033);
std::string text = SoEParameter::FormatValueWithAttributes(param.Value, param.Attributes);
printf("%s = %s\n", param.SercosIDN().c_str(), text.c_str());

AT/MDT マッピング​

SERCOS は AT(Acknowledge Telegram)と MDT(Master Data Telegram)で周期データを転送する。

  • AT = スレーブからマスタへの周期入力(実位置、実速度、ステータスワード …)
  • MDT = マスタからスレーブへの周期出力(目標位置、目標速度、制御ワード …)

マッピング構成が、周期データフレームにどの IDN パラメータを含めるかを決める。

GetIDNMapping()​

SoE::ServoMappingInfo GetIDNMapping(int timeoutMs = 5000) const;

現在のドライブの AT/MDT マッピング構成を読む。戻り値の型 ServoMappingInfo / ServoMappingEntry は SoE クラスのネスト構造体である。

引数:

  • timeoutMs (int) — タイムアウト時間(ミリ秒、デフォルト 5000)

戻り値:

  • SoE::ServoMappingInfo — マッピング情報オブジェクト

関連構造体(SoE のネスト型):

struct SoE::ServoMappingEntry {
uint16_t IDN; // IDN 番号
std::string Name; // パラメータ名
int BitLength; // データ長(ビット)
int ByteLength() const; // データ長(バイト)
};

struct SoE::ServoMappingInfo {
std::vector<ServoMappingEntry> ATMapping; // AT(入力)マッピングリスト
std::vector<ServoMappingEntry> MDTMapping; // MDT(出力)マッピングリスト
int ATBitSize; // AT の総ビット数
int MDTBitSize; // MDT の総ビット数
bool ATValid; // AT 設定を実際に読み取れたか
bool MDTValid; // MDT 設定を実際に読み取れたか
int ATByteSize() const; // AT の総バイト数
int MDTByteSize() const; // MDT の総バイト数
};

ATValid / MDTValid が false の場合、その方向のマッピング構成が読めていない(読み取りに失敗した、またはスレーブが非対応)ことを意味する。対応するビット数は 0 のままである。ビット数 0 は「0 ビット計測された」という意味ではないので、サイズを信じる前にこの二つのフラグを確認すること。各項目のビット長は属性の Length から導く(0 = 16 ビット、1 = 32 ビット、2 = 64 ビット、3 = 判定不能で 0 として記録)。

GetAllDriveMappings()​

std::map<uint8_t, SoE::ServoMappingInfo> GetAllDriveMappings(int timeoutMs = 5000) const;

すべてのドライブのマッピング情報を取得する(最大 8 ドライブまで走査する)。ドライブが無いスロットや応答が無いスロットは正常なケースであり、スキップして結果には入れない。

引数:

  • timeoutMs(int)— ドライブごとの読み取りタイムアウト(ミリ秒、既定 5000)

戻り値:

  • std::map<uint8_t, SoE::ServoMappingInfo> — ドライブ番号からマッピング情報への辞書

パラメータ変化通知​

SoE の Notification 機能を使うと、SERCOS スレーブの IDN パラメータの変化を監視できる。有効にすると、SDK は S-0-0127(通知要求)を書いてスレーブにハードウェア通知を求める。要求が成功してもしなくても IDN はローカル監視リストに入り、PollNotifications() が現在値をポーリングして前回記録値と比べ、変化があれば変化イベントを返す。

スレッドセーフティ: 監視リストは呼び出し側のスレッドが駆動する(EnableNotification / PollNotifications など)。複数スレッドから同一 SoE インスタンスへ同時に呼ぶ場合は、呼び出し側で直列化する必要がある。

EnableNotification()​

bool EnableNotification(uint16_t idn, int timeoutMs = 500);

指定 IDN のパラメータ変化通知を有効にする。まず S-0-0127 経由でハードウェア通知の有効化を試み、成功しなくても IDN をポーリング監視リストに加える(比較の基準として現在値を使う)。

引数:

  • idn(uint16_t)— 監視対象の IDN 番号
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • bool — true はスレーブがハードウェア通知対応を確認したことを、false はポーリングモードにフォールバックしたことを意味する

DisableNotification()​

bool DisableNotification(uint16_t idn, int timeoutMs = 500);

指定 IDN のパラメータ変化通知を無効にする。true = ローカル監視が削除された(ハードウェア通知を有効にしていた IDN では、S-0-0127 に購読解除も書く)。false = ハードウェアの購読解除に失敗し、その項目は再試行のため監視リストに残る。

ハードウェア購読解除の失敗は NotifyCancelFailureCount() に加算される。ローカル監視表はそのまま残るため、あとで DisableNotification() をもう一度呼べば再試行できる。

DisableAllNotifications()​

bool DisableAllNotifications(int timeoutMs = 500);

有効な通知をすべて、それぞれ本物の購読解除つきで無効にする。true = すべて削除された。false = 少なくとも一つのハードウェア購読解除に失敗し、失敗した項目は再試行のため監視リストに残る。

PollNotifications()​

std::vector<SoENotificationEventArgs> PollNotifications(int timeoutMs = 200);

監視中の全 IDN をポーリングしてパラメータ変化を検出する。順に現在値を読み、前回記録値と比べて、変化があれば変化イベントのリストを返す。タイマやバックグラウンドスレッドからの定期呼び出しに合う。

引数:

  • timeoutMs(int)— IDN ごとの読み取りタイムアウト(ミリ秒、既定 200)

戻り値:

  • std::vector<SoENotificationEventArgs> — 今回のポーリングで検出した変化イベントのリスト

GetMonitoredIDNs()​

std::vector<uint16_t> GetMonitoredIDNs() const;

現在監視中の IDN の一覧を取得する。

SoENotificationEventArgs​

struct SoENotificationEventArgs {
uint16_t SlaveIndex; // スレーブインデックス
uint8_t DriveNumber; // ドライバ番号
uint16_t IDN; // 変化した IDN 番号
std::vector<uint8_t> NewValue; // 新しい値
std::vector<uint8_t> OldValue; // 古い値

std::string SercosIDN() const; // フォーマット済みの SERCOS IDN 名称(例:"S-0-0127")
std::string ToString() const; // フォーマット済みのイベント説明
};

例:

auto& soe = master.GetSlave(1).GetSoE();

// 位置フィードバック(S-0-0051)の監視を有効にする
bool hwSupported = soe.EnableNotification(0x0033);
printf("硬件通知: %s\n", hwSupported ? "支持" : "回退到轮询"); // ハードウェア通知: %s(対応 / ポーリングにフォールバック)

// ドライバステータスワード(S-0-0071)の監視を有効にする
soe.EnableNotification(0x0047);

// ポーリングで変化を検出する
while (running) {
auto changes = soe.PollNotifications();
for (auto& c : changes) {
printf("参数变化: %s (IDN 0x%04X)\n", c.SercosIDN().c_str(), c.IDN); // パラメータ変化: %s(IDN 0x%04X)
printf(" 旧值: %s\n", FormatByteArray(c.OldValue).c_str()); // 旧値は %s
printf(" 新值: %s\n", FormatByteArray(c.NewValue).c_str()); // 新値は %s
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}

// 監視中の IDN を確認する
auto monitored = soe.GetMonitoredIDNs();
printf("正在监控 %zu 个 IDN\n", monitored.size()); // %zu 個の IDN を監視中です

// 監視を停止する
soe.DisableAllNotifications();

プロシジャコマンド​

ExecuteCommand()​

bool ExecuteCommand(uint16_t idn, int timeoutMs = 5000, int pollIntervalMs = 50) const;

SoE プロシジャコマンド(SERCOS Procedure Command)を実行する。DataState 要素(0x01)の bit0 に書き込むことでコマンド実行を起動し、コマンドが完了するまでポーリングする。

引数:

  • idn(uint16_t)— 実行するコマンドの IDN 番号
  • timeoutMs(int)— コマンド完了までの待ち時間(ミリ秒、既定 5000)
  • pollIntervalMs(int)— ポーリング間隔(ミリ秒、既定 50)

戻り値:

  • bool — コマンドが正常に完了したときは true、タイムアウトまたは失敗は false

例:

auto& soe = master.GetSlave(1).GetSoE();

// デバイスマニュアルで定義されたプロセスコマンドを実行する(ホーミング系コマンドなど)
bool success = soe.ExecuteCommand(0x0094);
if (success)
printf("命令完成\n"); // コマンドが完了しました
else
printf("命令超时或失败\n"); // コマンドがタイムアウトしたか失敗しました

// カスタムタイムアウト(長時間コマンド)
bool ok = soe.ExecuteCommand(0x0094, 30000, 100);

ドライブ番号つき ExecuteCommand() オーバーロード​

bool ExecuteCommand(uint16_t idn, uint8_t driveNo, uint8_t elementFlags,
int timeoutMs = 5000, int pollIntervalMs = 50) const;

同じコマンドの流れで、ドライブ番号と要素フラグを追加指定する(状態の読み書きでは elementFlags に 0x01 を合成して使う)。

引数:

  • idn(uint16_t)— 実行するコマンドの IDN 番号
  • driveNo(uint8_t)— ドライブ番号(多軸スレーブ)
  • elementFlags(uint8_t)— 要素フラグ(0x01 のデータ状態と自動で合成される)
  • timeoutMs(int)— コマンド完了までの待ち時間(ミリ秒、既定 5000)
  • pollIntervalMs(int)— ポーリング間隔(ミリ秒、既定 50)

戻り値:

  • bool — コマンドが正常に完了したときは true。状態ビットがエラーを報告した場合やタイムアウトした場合は false

ReadDataState()​

std::optional<uint16_t> ReadDataState(uint16_t idn, int timeoutMs = 500) const;

IDN の Data State 要素(Element 0x01)を読む。bit0 = プロシジャコマンド要求中 / 実行中、bit1 = コマンドエラー。ExecuteCommand() はこの二ビットで完了と失敗を判定する。

引数:

  • idn(uint16_t)— IDN 番号
  • timeoutMs(int)— タイムアウト(ミリ秒、既定 500)

戻り値:

  • std::optional<uint16_t> — Data State の値。失敗時は std::nullopt

例:

auto& soe = master.GetSlave(1).GetSoE();

// IDN の Data State を読み取る
auto state = soe.ReadDataState(0x0094);
if (state) {
bool commandActive = (*state & 0x01) != 0;
bool commandError = (*state & 0x02) != 0;
printf("命令激活: %s, 命令错误: %s\n", // コマンドアクティブ: %s、コマンドエラー: %s
commandActive ? "是" : "否",
commandError ? "是" : "否");
}

標準 IDN 定数​

struct StandardIDN {
static constexpr uint16_t IDNList = 0x0000; // IDN リスト(S-0-0000)
static constexpr uint16_t CycleTime = 0x0001; // 通信サイクル時間(S-0-0001)
static constexpr uint16_t ATConfig = 0x0010; // AT 設定 - 入力マッピング(S-0-0016)
static constexpr uint16_t MDTConfig = 0x0018; // MDT 設定 - 出力マッピング(S-0-0024)
static constexpr uint16_t NotificationRequest = 0x007F; // 通知要求(S-0-0127)
};

SoE::StandardIDN::CycleTime などから参照する。

完全な例​

パラメータスキャン​

#include "ethercat.hpp"
using namespace darra;

auto& soe = master.GetSlave(1).GetSoE();

// サポートされるすべての IDN を取得する
auto idns = soe.GetAvailableIDNs();
printf("从站支持 %zu 个 IDN 参数\n\n", idns.size()); // スレーブは %zu 個の IDN パラメータに対応しています

int limit = std::min<int>(static_cast<int>(idns.size()), 10);
for (int i = 0; i < limit; ++i) {
auto info = soe.GetParameterInfo(idns[i]);
printf("%s: %s = %s %s [%s]\n",
info.SercosIDN().c_str(),
info.Name.c_str(),
info.FormattedValue().c_str(),
info.Unit.c_str(),
info.AccessMode().c_str());
}

サーボドライバ制御​

#include "ethercat.hpp"
using namespace darra;

int main() {
darra::ethercat::dll_t dll;
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
master.SetState(EcState::OP);
master.Start();

auto& soe = master.GetSlave(1).GetSoE();

// 1. ドライバ状態を読み取る
auto statusWord = soe.ReadUInt16(0x0047);
if (statusWord)
printf("状态字: 0x%04X\n", *statusWord); // ステータスワード: 0x%04X

// 2. AT/MDT マッピングを確認する(周期データのレイアウトを把握)
auto mapping = soe.GetIDNMapping();
if (mapping.ATValid) {
printf("\nAT 映射(输入 %d 字节):\n", mapping.ATByteSize()); // AT マッピング(入力 %d バイト):
for (auto& entry : mapping.ATMapping)
printf(" IDN 0x%04X: %s (%dB)\n", entry.IDN, entry.Name.c_str(), entry.ByteLength());
}
if (mapping.MDTValid) {
printf("\nMDT 映射(输出 %d 字节):\n", mapping.MDTByteSize()); // MDT マッピング(出力 %d バイト):
for (auto& entry : mapping.MDTMapping)
printf(" IDN 0x%04X: %s (%dB)\n", entry.IDN, entry.Name.c_str(), entry.ByteLength());
}

// 3. 制御ワードを書き込んでドライバをイネーブルする(S-0-0064)
soe.WriteUInt16(0x0040, 0x0006);

// 4. 位置指令を設定する(S-0-0047)
soe.WriteInt32(0x002F, 50000);

// 5. 位置フィードバックを読み取る(S-0-0051)
auto actualPos = soe.ReadInt32(0x0033);
if (actualPos)
printf("\n位置反馈: %d inc\n", *actualPos); // 位置フィードバック: %d inc

getchar();
return 0;
}

パラメータ変化通知コールバック​

PollNotifications() のポーリング方式に加え、SDK は std::function ベースのコールバック登録機構も提供する。パラメータ変化(IDN Notification)イベントはランタイムのバックグラウンドスレッドが検出し、発火時にコールバックはバックグラウンドスレッドの文脈で動く。コールバックが UI や共有状態に触れる必要がある場合は、自らロックするかメインスレッドに投げる必要がある。

C++ 側に独立した緊急イベントコールバックは無い

C++ SDK は SoEEmergencyEvent / AddEmergencyCallback / RemoveEmergencyCallback / EmergencyCount を提供しない。SERCOS の OpCode=6 online は実際には Slave Info であり(旧資料にあるような Emergency ではない)、ランタイムはそれを通知チャンネルに統合する。こうしたスレーブからの報告を受け取りたい場合は SoENotificationEvent を購読する。他の言語の SDK に緊急イベントが残っているなら、それはその言語側の表面差であり、C++ の能力ではない。

コールバック登録は SoERuntimeEvents シングルトンにあり、SoE のメンバではない

SoE クラスに AddNotificationCallback メンバメソッドは存在しない。 DLL 側の SoE 通知コールバックはグローバルに一つのコールバックであり、複数の SoE インスタンスが同じイベントストリームを共有し、darra::ethercat::SoERuntimeEvents シングルトンが一括で振り分ける。使い方:

auto& evt = SoERuntimeEvents::Instance();
evt.Bind(dll); // DLL 読み込み後、初回サブスクライブ前に一回呼ぶ
size_t h = evt.AddNotificationCallback(cb); // サブスクライブハンドルを返す
// evt.RemoveNotificationCallback(h); evt.Clear();

SoENotificationEvent​

struct SoENotificationEvent {
int slaveIndex; // スレーブインデックス(1 始まり)
uint8_t driveNumber; // ドライバ番号
uint8_t elementFlags; // 要素フラグ(0x40 = データ値)
uint16_t idn; // 変化した IDN
std::vector<uint8_t> newValue; // 新しい値の生バイト
std::chrono::system_clock::time_point timestamp; // イベントタイムスタンプ
};

SoERuntimeEvents::AddNotificationCallback()​

class SoERuntimeEvents {
public:
using NotificationCallback = std::function<void(const SoENotificationEvent&)>;

static SoERuntimeEvents& Instance(); // グローバルシングルトン
void Bind(dll_t& dll); // DLL をバインドする(初回サブスクライブ前に一回呼ぶ)
size_t AddNotificationCallback(NotificationCallback cb); // サブスクライブハンドルを返す
void RemoveNotificationCallback(size_t handle);
void Clear(); // この層の配信リストだけを空にする(DLL 側の登録は維持)
void Unregister(); // 空にする + DLL へのコールバック登録を解除する(プロセス終了/イベントストリーム再構築前)
size_t NotificationCount() const; // 現在の通知サブスクライブ数
};
Clear() と Unregister()
  • Clear() — この層の std::function ディスパッチリストを消すだけ。DLL 側のコールバック登録は残る。
  • Unregister() — ディスパッチリストを消し、さらに DLL からのコールバック登録も削除する。プロセス終了前 / イベントストリームのリセット前に呼んで、登録をきれいに外すこと。

パラメータ変化コールバックを登録する。何度でも呼んで複数登録でき、すべてのコールバックが登録順に発火する。 コールバックはランタイムのバックグラウンド通知スレッドで動く。

例 (C++17 lambda):

using darra::ethercat::SoERuntimeEvents;

auto& evt = SoERuntimeEvents::Instance();
evt.Bind(dll); // DLL 読み込み後、初回サブスクライブ前に一回呼ぶ

// パラメータ変化コールバック
evt.AddNotificationCallback([](const SoENotificationEvent& e) {
std::cout << "[" << std::chrono::duration_cast<std::chrono::milliseconds>(
e.timestamp.time_since_epoch()).count()
<< "ms] IDN 0x" << std::hex << e.idn
<< " 变化 (从站 " << std::dec << e.slaveIndex // 変化(スレーブ
<< " 驱动 " << (int)e.driveNumber << ")\n"; // ドライブ
});

// 監視対象 IDN を有効にする(SoE インスタンスの EnableNotification でハードウェア通知を有効にする)
auto& soe = master.GetSlave(1).GetSoE();
soe.EnableNotification(0x0047); // ドライバステータスワード
soe.EnableNotification(0x0033); // 位置フィードバック
複数コールバックとスレッドセーフティ
  • AddNotificationCallback は購読ハンドルを返す。一件のコールバックを削除するには RemoveNotificationCallback(handle) を、すべて消すには Clear() を使う
  • コールバックはバックグラウンドスレッドで動く。UI やスレッドセーフでないコンテナに触れるときは、std::mutex / PostMessage / Invoke を自分で使う
  • コールバック内でブロックしないこと(ファイル IO や同期 IO など)。通知スレッドが遅くなる
参考

ETG.6220 §7 SoE Notification、SERCOS II 標準 §2.10 診断データ。

エラー照会​

GetLastSoEError()​

std::optional<SoEError> GetLastSoEError() const;

直近の Read() / Write() の失敗理由を読む。エラーコードの値は SoEError 列挙型(SDK ヘッダ data/types.hpp)を参照。

戻り値:

  • std::optional<SoEError> — std::nullopt = 直近の操作は成功。NoOperationData = 読んだ内容が空の操作データ。Unknown = 通信失敗 / 書込み失敗

例:

auto data = soe.Read(0x0033);
if (data.empty()) {
if (auto err = soe.GetLastSoEError())
printf("读取失败: 0x%04X\n", static_cast<uint16_t>(*err)); // 読み取りに失敗しました: 0x%04X
}

同一ファミリのメンバ: GetLastSoEErrorCode() は ETG.5003 の拡張エラーコード(SoEErrorCode 列挙型)を読む。基本の SoEError とは独立したフィールドで、両者が互いに上書きすることはない。SetLastSoEErrorCode(code) がそのフィールドに書き、ClearLastSoEErrorCode() が消す。SDK 自体は拡張エラーコードを埋めないため、値が読めるのは呼び出し側が明示的に設定した場合だけである。

SetLastSoEErrorCode()​

void SetLastSoEErrorCode(SoEErrorCode code);

ETG.5003 の拡張エラーコードフィールドに書く。あとで GetLastSoEErrorCode() がそれを読み戻す。GetLastSoEError() が管理する基本エラーコードには影響しない。

引数:

  • code(SoEErrorCode)— 記録する拡張エラーコード。値は data/types.hpp の SoEErrorCode 列挙型を参照

例:

soe.SetLastSoEErrorCode(SoEErrorCode::NoIDN);
if (auto code = soe.GetLastSoEErrorCode())
printf("高级错误码: 0x%04X\n", static_cast<uint16_t>(*code)); // 拡張エラーコード: 0x%04X

soe.ClearLastSoEErrorCode();

失敗とその対処​

症状原因対処
Read が空配列を返すそのスレーブにその IDN 番号が存在しないデバイスマニュアルに記載の IDN に切り替える。まずそのパラメータが標準セグメントかベンダ定義セグメントかを確認する
Write が false を返すパラメータが書き込み禁止(パスワードまたはアクセスレベル制限)パラメータが書き込み可能か確認する。必要なら書き込み権限のあるアクセスレベルに切り替えて書き直す
Read / Write が失敗し、明らかに時間がかかるメールボックストランザクションのタイムアウト、またはスレーブが応答しないスレーブのメールボックスが利用可能で状態が正常か確認し、再試行するか timeoutMs を延ばす
Write が却下されるそのパラメータは特定のサーボ状態でしか書けないそのパラメータが書ける状態になるのを待ってから書く。状態遷移の窓は避ける