SoE (Servo over EtherCAT)
SoE 는 SERCOS 서보 파라미터를 EtherCAT 메일박스에 나른다: 파라미터는 16 비트 IDN 으로 색인되며 원시 바이트로 읽거나 쓸 수 있고, 이름과 단위는 따로 조회할 수 있다.
대부분의 서보 장치는 CoE + CiA 402 를 쓴다. SoE 는 SERCOS 호환 서보 장치 (Bosch Rexroth IndraDrive 계열 등) 에만 적용되며, 한 슬레이브가 두 프로토콜을 섞어 쓸 수는 없다.
slave.SoE 로 접근한다. 슬레이브가 SoE 를 지원하지 않으면 null 이다.
메서드 개요
| 분류 | 메서드 | 타입 | 읽기·쓰기 | 설명 |
|---|---|---|---|---|
| 프로토콜 지원 여부 | IsSupported | bool | 읽기 전용 | SoESupport == true 의 bool 뷰. 지원이 확인되었을 때만 true |
| 프로토콜 지원 여부 | SoESupport | bool? | 읽기 전용 | 능력 삼태: true = 지원, false = 선언되지 않은 것이 확인됨, null = 불명 |
| 프로토콜 지원 여부 | IsSupportedKnown | bool | 읽기 전용 | 지원 판정이 알려졌는지. false = 불명 (미지원과는 다르다) |
| 파라미터 읽기·쓰기 | Read | byte[]? | 읽기 전용 | IDN 으로 원시 파라미터 바이트를 읽는다. 실패하면 null |
| 파라미터 읽기·쓰기 | Write | bool | 쓰기 전용 | IDN 으로 원시 파라미터 바이트를 쓴다. 실패하면 false |
| 파라미터 읽기·쓰기 | ReadInt16 / ReadInt32 / ReadUInt16 / ReadUInt32 / ReadFloat / ReadDouble / ReadString | short? / int? / ushort? / uint? / float? / double? / string? | 읽기 전용 | 타입 지정 읽기. 실패하면 null |
| 파라미터 읽기·쓰기 | WriteInt16 / WriteInt32 / WriteUInt16 / WriteUInt32 | bool | 쓰기 전용 | 타입 지정 쓰기. 실패하면 false |
| 메타데이터 | ReadName | string? | 읽기 전용 | IDN 파라미터 이름을 읽는다 |
| 메타데이터 | ReadUnit | string? | 읽기 전용 | IDN 파라미터 단위를 읽는다 |
| 메타데이터 | ReadMinValue / ReadMaxValue / ReadDefaultValue | byte[]? | 읽기 전용 | 파라미터 최소 / 최대 / 기본값을 읽는다 |
| 파라미터 정보 | GetAvailableIDNs | List<ushort> | 읽기 전용 | 슬레이브가 지원하는 모든 IDN 을 나열한다. 조회에 실패하면 SoEException 을 던진다 |
| 파라미터 정보 | GetParameterInfo | SoEParameter | 읽기 전용 | IDN 의 전체 파라미터 정보를 읽는다. 조회에 실패하면 SoEException 을 던진다 |
| 매핑 | GetIDNMapping | ServoMappingInfo | 읽기 전용 | 현재 드라이버 AT/MDT 매핑 구성을 읽는다 |
| 매핑 | GetAllDriveMappings | Dictionary<byte, ServoMappingInfo> | 읽기 전용 | 모든 드라이버 (최대 8 개) 의 매핑 정보를 읽는다 |
| 절차 명령 | ExecuteCommand | bool | 쓰기 전용 | SERCOS 절차 명령을 실행하고 완료를 기다린다 |
| 절차 명령 | ReadDataState | ushort? | 읽기 전용 | IDN 의 Data State 요소를 읽는다 |
| 절차 명령 | WaitForProcedureDone | bool | 읽기 전용 | 절차 명령이 끝날 때까지 폴링한다 |
| 알림 | NotificationReceived | Action<SoENotificationEventArgs> | 읽기 전용 | 감시 중인 IDN 의 값이 바뀔 때 발동한다. 콜백은 IDN 과 이전·새 값을 담는다 |
| 알림 | EnableNotification | bool | 쓰기 전용 | IDN 의 변화 알림을 켠다. true = 하드웨어 알림 활성화 |
| 알림 | DisableNotification / DisableAllNotifications | void | 쓰기 전용 | 하나 또는 전체 파라미터 변화 알림을 끈다 |
| 알림 | PollNotifications | int | 읽기 전용 | 파라미터 변화를 폴링해 이벤트를 올린다. 변화 수를 반환한다 |
| 알림 | GetMonitoredIDNs | List<ushort> | 읽기 전용 | 지금 알림이 켜져 있는 IDN 들의 스냅샷 |
| 알림 | EmergencyReceived | Action<SoEEmergencyEventArgs> | 읽기 전용 | Sercos Emergency (OpCode=6) 를 수신할 때 발동한다 |
| 비동기 | ReadAsync / WriteAsync / 타입 지정 읽기·쓰기의 *Async 변형 / GetAvailableIDNsAsync / GetParameterInfoAsync / EnableNotificationAsync / PollNotificationsAsync | Task<...> | 읽기·쓰기 | 동기 API 의 비동기 래퍼. 취소는 호출자에게만 영향을 준다. 비동기 메서드 참조 |
| 오류 코드 | LastSoEError / LastStatus / LastErrorCode | SoEError? / MailboxStatus / uint | 읽기 전용 | 가장 최근 작업의 오류 코드와 메일박스 트랜잭션 상태 |
| 인코딩 헬퍼 | SoEInstance.EncodeIdn / DecodeIdn / TryParseSercosIdn | ushort / tuple / bool | 읽기 전용 | IDN 번호와 세 요소 / SERCOS 문자열을 서로 변환한다. 순수 비트 연산 |
프로토콜 지원 여부
| 분류 | 속성 | 타입 | 읽기·쓰기 | 설명 |
|---|---|---|---|---|
| 프로토콜 지원 여부 | IsSupported | bool | 읽기 전용 | SoESupport == true 의 bool 뷰: 지원이 확인되었을 때만 true, 판정이 불명이면 false |
| SoESupport | bool? | 읽기 전용 | SoE 능력 삼태: true = 지원, false = mbx_proto 를 실제로 읽어 비트가 꺼짐, null = 불명 (읽기 실패) | |
| IsSupportedKnown | bool | 읽기 전용 | 지원 판정이 알려졌는지. false = 불명 (미지원과는 다르다) |
SoESupport 는 bool? 를 반환한다: true = 지원, false = SII mbx_proto 워드를 실제로 읽었고 비트가 꺼짐, null = 이번 호출에서 읽을 수 없음 (호출 실패). 읽기 실패를 더 이상 false 로 뭉치지 않는다. "확인된 미지원"과 "불명"을 가르려면 SoESupport / IsSupportedKnown 을 본다.
SERCOS IDN 체계
SoE 는 IDN (Identification Number) 으로 드라이버 파라미터를 색인한다. 각 IDN 은 하나의 파라미터 (위치, 속도, 제어 워드 등) 를 뜻하는 16 비트 숫자다.
IDN 명명 규칙:
| 접두사 | 범위 | 설명 |
|---|---|---|
| S-x-xxxx | 0x0000 – 0x7FFF | SERCOS 표준 파라미터 (모든 벤더 공통) |
| P-x-xxxx | 0x8000 – 0xBFFF | 제품별 파라미터 |
| — | 0xC000 – 0xFFFF | 벤더 정의 파라미터 |
흔히 쓰는 표준 IDN (서보 제어):
| IDN | SERCOS 이름 | 설명 | 데이터 타입 |
|---|---|---|---|
| S-0-0001 (0x0001) | Cycle Time | 통신 사이클 시간 | uint, µs |
| S-0-0011 (0x000B) | Position Feedback 1 | 실제 위치 | int, inc |
| S-0-0012 (0x000C) | Position Command | 목표 위치 | int, inc |
| S-0-0013 (0x000D) | Velocity Feedback | 실제 속도 | int, rpm |
| S-0-0014 (0x000E) | Velocity Command | 목표 속도 | int, rpm |
| S-0-0016 (0x0010) | AT Config | 입력 매핑 구성 목록 | list |
| S-0-0019 (0x0013) | Drive Status | 드라이버 상태 워드 | ushort |
| S-0-0024 (0x0018) | MDT Config | 출력 매핑 구성 목록 | list |
| S-0-0036 (0x0024) | Max Velocity | 최대 속도 한계 | uint, rpm |
| S-0-0040 (0x0028) | Homing Velocity | 호밍 속도 | uint, rpm |
| 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 열거형을 받는 Read / Write 오버로드는 같은 이름의 멤버에 대응한다: DataStatus = 0x01, Name = 0x02, Attribute = 0x04, Unit = 0x08, Min = 0x10, Max = 0x20, Value = 0x40. 비트 연산 OR 로 결합하면 여러 요소를 한 번에 읽거나 쓴다. 기본값 0x80 은 byte 오버로드나 ReadDefaultValue 로 접근한다.
기본 읽기와 쓰기
Read(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500)
public byte[]? Read(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500)
public byte[]? Read(ushort idn, SoEElementFlags elementFlags, int timeoutMs = 500)
IDN 파라미터의 원시 바이트를 읽는다. 슬레이브가 PreOp / SafeOp / OP (메일박스를 쓸 수 있는 상태) 가 아니면 SDK 가 먼저 PreOp 로 전환한 뒤 읽는다. 전환에 실패하면 null 을 반환한다. 두 번째 오버로드는 맨 byte 대신 SoEElementFlags 열거형 ([Flags], OR 로 결합 가능) 을 받으며 elementFlags 에 기본값이 없다.
매개변수:
idn(ushort) — IDN 번호elementFlags(byte) — 요소 플래그 (기본값 0x40 = 데이터 값)timeoutMs(int) — 밀리초 타임아웃 (기본값 500)
반환값:
byte[]?— 읽은 데이터. 실패하면null
예제:
// 통신 사이클 시간 읽기 (S-0-0001)
byte[]? data = slave.SoE.Read(0x0001, 0x40);
if (data != null)
{
uint cycleTime = BitConverter.ToUInt32(data, 0);
Console.WriteLine($"周期时间: {cycleTime} μs"); // 사이클 시간: {cycleTime} µs
}
Write(ushort idn, byte[] data, byte elementFlags = 0x40, int timeoutMs = 500)
public bool Write(ushort idn, byte[] data, byte elementFlags = 0x40, int timeoutMs = 500)
public bool Write(ushort idn, byte[] data, SoEElementFlags elementFlags, int timeoutMs = 500)
IDN 파라미터를 쓴다. 슬레이브가 PreOp / SafeOp / OP 가 아니면 SDK 가 먼저 PreOp 로 전환한 뒤 쓴다. 전환에 실패하면 false 를 반환한다. 두 번째 오버로드는 맨 byte 대신 SoEElementFlags 열거형을 받으며 elementFlags 에 기본값이 없다.
매개변수:
idn(ushort) — IDN 번호data(byte[]) — 기록할 데이터elementFlags(byte) — 요소 플래그 (기본값 0x40 = 데이터 값)timeoutMs(int) — 밀리초 타임아웃 (기본값 500)
반환값:
bool— 성공하면true
예제:
// 목표 위치 설정 (S-0-0012)
byte[] position = BitConverter.GetBytes(100000);
bool success = slave.SoE.Write(0x000C, position);
타입 지정 읽기
모든 메서드가 같은 시그니처를 쓴다: ReadXxx(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500)
| 분류 | 메서드 | 타입 | 읽기·쓰기 | 설명 |
|---|---|---|---|---|
| 타입 지정 읽기 | ReadInt16 | short? | 읽기 전용 | 16 비트 부호 있는 정수를 읽는다 |
| ReadInt32 | int? | 읽기 전용 | 32 비트 부호 있는 정수를 읽는다 | |
| ReadUInt16 | ushort? | 읽기 전용 | 16 비트 부호 없는 정수를 읽는다 | |
| ReadUInt32 | uint? | 읽기 전용 | 32 비트 부호 없는 정수를 읽는다 | |
| ReadFloat | float? | 읽기 전용 | 단정밀도 부동소수점을 읽는다 | |
| ReadDouble | double? | 읽기 전용 | 배정밀도 부동소수점을 읽는다 | |
| ReadString | string? | 읽기 전용 | 문자열을 읽는다 |
예제:
// 실제 위치 읽기 (S-0-0011)
int? actualPos = slave.SoE.ReadInt32(0x000B);
// 드라이버 상태 워드 읽기 (S-0-0071)
ushort? status = slave.SoE.ReadUInt16(0x0047);
// 매개변수 이름 읽기
string? name = slave.SoE.ReadString(0x000B, elementFlags: 0x02);
타입 지정 쓰기
모든 메서드가 같은 시그니처를 쓴다: WriteXxx(ushort idn, T value, byte elementFlags = 0x40, int timeoutMs = 500). 반환 타입은 bool 다.
| 분류 | 메서드 | 타입 | 읽기·쓰기 | 설명 |
|---|---|---|---|---|
| 타입 지정 쓰기 | WriteInt16 | short | 쓰기 전용 | 16 비트 부호 있는 정수를 쓴다 |
| WriteInt32 | int | 쓰기 전용 | 32 비트 부호 있는 정수를 쓴다 | |
| WriteUInt16 | ushort | 쓰기 전용 | 16 비트 부호 없는 정수를 쓴다 | |
| WriteUInt32 | uint | 쓰기 전용 | 32 비트 부호 없는 정수를 쓴다 |
예제:
// 목표 위치 설정 (S-0-0012)
slave.SoE.WriteInt32(0x000C, 50000);
// 제어 워드 기록 (S-0-0064)
slave.SoE.WriteUInt16(0x0040, 0x0006);
메타데이터 읽기
ReadName(ushort idn, int timeoutMs = 500)
public string? ReadName(ushort idn, int timeoutMs = 500)
IDN 파라미터 이름을 읽는다 (ElementFlag 0x02 사용).
ReadUnit(ushort idn, int timeoutMs = 500)
public string? ReadUnit(ushort idn, int timeoutMs = 500)
IDN 파라미터 단위를 읽는다 (ElementFlag 0x08 사용).
ReadMinValue / ReadMaxValue / ReadDefaultValue
public byte[]? ReadMinValue(ushort idn, int timeoutMs = 500)
public byte[]? ReadMaxValue(ushort idn, int timeoutMs = 500)
public byte[]? ReadDefaultValue(ushort idn, int timeoutMs = 500)
IDN 파라미터의 최소 (0x10), 최대 (0x20), 기본 (0x80) 값을 읽는다.
예제:
string? name = slave.SoE.ReadName(0x000B);
string? unit = slave.SoE.ReadUnit(0x000B);
byte[]? min = slave.SoE.ReadMinValue(0x000B);
byte[]? max = slave.SoE.ReadMaxValue(0x000B);
Console.WriteLine($"参数: {name} ({unit})"); // 매개변수: {name} ({unit})
if (min != null && max != null)
Console.WriteLine($"范围: {BitConverter.ToInt32(min, 0)} - {BitConverter.ToInt32(max, 0)}"); // 범위: {BitConverter.ToInt32(min, 0)} - {BitConverter.ToInt32(max, 0)}
파라미터 정보
GetAvailableIDNs(int timeoutMs = 5000)
public List<ushort> GetAvailableIDNs(int timeoutMs = 5000)
슬레이브가 지원하는 모든 IDN 목록을 얻는다. 읽기에 실패하면 SoEException 을 던지며, 성공한 척하는 빈 목록을 반환하지 않는다. 빈 목록은 슬레이브가 IDN 0 개를 보고했다는 뜻만이다.
반환값:
List<ushort>— IDN 번호 목록
GetParameterInfo(ushort idn, int timeoutMs = 5000)
public SoEParameter GetParameterInfo(ushort idn, int timeoutMs = 5000)
IDN 파라미터의 전체 정보 (이름, 단위, 속성, 현재 값, 최소 / 최대 값 등) 를 얻는다. 모든 요소 읽기에 실패하면 SoEException 을 던지며 빈 껍데기 객체를 반환하지 않는다.
반환값:
SoEParameter— 전체 파라미터 정보를 담는다
관련 구조체:
public class SoEParameter
{
public ushort IDN { get; set; } // IDN 번호
public string Name { get; set; } // 매개변수 이름
public string Unit { get; set; } // 단위
public SoEAttributes Attributes { get; set; } // 속성 (데이터 유형, 길이 등)
public byte[] Value { get; set; } // 현재 값
public byte[] DefaultValue { get; set; } // 기본값
public byte[] MinValue { get; set; } // 최솟값
public byte[] MaxValue { get; set; } // 최댓값
public string SercosIDN { get; } // SERCOS IDN 형식 (예: "S-0-0001", 읽기 전용 파생)
public string Category { get; } // 카테고리 ("Standard" / "Product" / "Vendor", 읽기 전용 파생)
public bool IsReadOnly { get; } // 읽기 전용인지 여부 (읽기 전용 파생)
public string AccessMode { get; } // 접근 권한 ("RO" / "RW" / "RW*", 읽기 전용 파생)
public string FormattedValue { get; } // 서식화된 현재 값 (읽기 전용 파생)
public string FormattedDefaultValue { get; } // 서식화된 기본값 (읽기 전용 파생)
public string FormattedMinValue { get; } // 서식화된 최솟값 (읽기 전용 파생)
public string FormattedMaxValue { get; } // 서식화된 최댓값 (읽기 전용 파생)
}
public struct SoEAttributes
{
public ushort EvaluationFactor; // 평가 인자
public byte Length; // 데이터 길이
public bool IsList; // 목록인지
public bool IsCommand; // 명령인지
public SoEDataType DataType; // 데이터 유형
public byte Decimals; // 소수점 자릿수
public bool WriteProtectedPreOp; // PreOp 상태 쓰기 보호
public bool WriteProtectedSafeOp; // SafeOp 상태 쓰기 보호
public bool WriteProtectedOp; // Op 상태 쓰기 보호
}
public enum SoEDataType : byte
{
Binary = 0, // 바이너리
UInt = 1, // 부호 없는 정수
Int = 2, // 부호 있는 정수
Hexadecimal = 3, // 십육진수
String = 4, // 문자열
IDN = 5, // IDN 참조
Float = 6, // 부동소수점 수
Parameter = 7 // 매개변수
}
예제:
var param = slave.SoE.GetParameterInfo(0x000B);
Console.WriteLine($"IDN: {param.SercosIDN} - {param.Name}");
Console.WriteLine($"单位: {param.Unit}, 访问: {param.AccessMode}"); // 단위: {param.Unit}, 접근: {param.AccessMode}
Console.WriteLine($"当前值: {param.FormattedValue}"); // 현재 값: {param.FormattedValue}
Console.WriteLine($"范围: {param.FormattedMinValue} - {param.FormattedMaxValue}"); // 범위: {param.FormattedMinValue} - {param.FormattedMaxValue}
AT/MDT 매핑
SERCOS 는 AT (Acknowledge Telegram) 와 MDT (Master Data Telegram) 로 주기 데이터를 전달한다:
- AT = 슬레이브에서 마스터로 가는 주기 입력 (실제 위치, 실제 속도, 상태 워드, ...)
- MDT = 마스터에서 슬레이브로 가는 주기 출력 (목표 위치, 목표 속도, 제어 워드, ...)
매핑 구성은 주기 데이터 프레임에 어떤 IDN 파라미터가 실리는지 정한다.
GetIDNMapping(int timeoutMs = 5000)
public ServoMappingInfo GetIDNMapping(int timeoutMs = 5000)
드라이버의 현재 AT/MDT 매핑 구성을 읽는다. 조회에 실패하면 SoEException 을 던진다.
반환값:
ServoMappingInfo— 매핑 정보 객체
관련 구조체:
public class ServoMappingInfo
{
public List<ServoMappingEntry> ATMapping { get; set; } // AT(입력) 매핑 목록
public List<ServoMappingEntry> MDTMapping { get; set; } // MDT(출력) 매핑 목록
public int ATBitSize { get; set; } // AT 총 비트 수
public int MDTBitSize { get; set; } // MDT 총 비트 수
public int ATByteSize { get; } // AT 총 바이트 수 (읽기 전용 파생)
public int MDTByteSize { get; } // MDT 총 바이트 수 (읽기 전용 파생)
}
public class ServoMappingEntry
{
public ushort IDN { get; set; } // IDN 번호
public string Name { get; set; } // 매개변수 이름
public int BitLength { get; set; } // 데이터 길이 (비트)
public int ByteLength { get; } // 데이터 길이 (바이트, 읽기 전용 파생)
}
GetAllDriveMappings(int timeoutMs = 5000)
public Dictionary<byte, ServoMappingInfo> GetAllDriveMappings(int timeoutMs = 5000)
모든 드라이버의 매핑 정보를 얻는다 (드라이버 최대 8 개를 스캔한다).
반환값:
Dictionary<byte, ServoMappingInfo>— 드라이버 번호를 매핑 정보로 매핑한 사전
절차 명령
ExecuteCommand(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
public bool ExecuteCommand(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
SoE 절차 명령 (SERCOS Procedure Command) 을 실행한다. DataState 요소 (0x01) 의 bit0 을 쓰면 명령이 트리거되고, 그 뒤 메서드는 완료될 때까지 폴링한다. IsCommand=true 인 IDN 에만 유효하다.
매개변수:
idn(ushort) — 실행할 명령의 IDN 번호timeoutMs(int) — 명령 완료를 기다릴 시간 (밀리초, 기본값 5000)pollIntervalMs(int) — 폴링 간격 (밀리초, 기본값 50)
반환값:
bool— 명령이 성공적으로 끝나면true, 타임아웃이나 실패면false
예제:
// 호밍 명령 실행 (S-0-0148)
bool success = slave.SoE.ExecuteCommand(0x0094);
if (success)
Console.WriteLine("回零完成"); // 호밍 완료
else
Console.WriteLine("回零超时或失败"); // 호밍 타임아웃 또는 실패
// 사용자 지정 타임아웃 (오래 걸리는 명령)
bool ok = slave.SoE.ExecuteCommand(0x0094, timeoutMs: 30000, pollIntervalMs: 100);
ReadDataState(ushort idn, int timeoutMs = 500)
public ushort? ReadDataState(ushort idn, int timeoutMs = 500)
IDN 의 Data State 요소 (ElementFlag 0x01) 를 읽는다. Data State 는 명령 상태, 데이터 유효성 같은 정보를 담는다.
매개변수:
idn(ushort) — IDN 번호timeoutMs(int) — 밀리초 타임아웃 (기본값 500)
반환값:
ushort?— 16 비트 Data State 값. 실패하면null
예제:
// IDN의 Data State 읽기
ushort? state = slave.SoE.ReadDataState(0x0094);
if (state != null)
{
bool commandActive = (state.Value & 0x01) != 0;
bool commandError = (state.Value & 0x02) != 0;
Console.WriteLine($"命令激活: {commandActive}, 命令错误: {commandError}"); // 명령 활성화: {commandActive}, 명령 오류: {commandError}
}
WaitForProcedureDone(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
public bool WaitForProcedureDone(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
절차 명령이 끝날 때까지 Data State 를 폴링한다 (IEC 61800-7-204): bit0 = 진행 중 (1 = 아직 실행 중, 0 = 완료), bit1 = 오류 (설정되면 즉시 false 반환), bit3 = 중단 (설정되면 false 반환). 명령을 트리거한 뒤 ExecuteCommand 도 같은 완료 조건을 기다린다. 이 메서드는 이미 돌고 있는 명령에 대해서도 단독으로 쓸 수 있다.
비동기 메서드
동기 API 에 대한 비동기 래퍼다. 각 메서드는 같은 이름의 동기 메서드 (Read / Write / ReadInt16 ...) 와 대응하며 반환값과 실패 의미가 정확히 같다. 비동기라는 것은 호출이 현재 스레드를 점유하지 않는다는 뜻뿐이고, 취소는 CancellationToken 으로 지원된다.
public Task<byte[]?> ReadAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteAsync(ushort idn, byte[] data, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> ExecuteCommandAsync(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50, CancellationToken cancellationToken = default)
public Task<short?> ReadInt16Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<int?> ReadInt32Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<ushort?> ReadUInt16Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<uint?> ReadUInt32Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteInt16Async(ushort idn, short value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteInt32Async(ushort idn, int value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteUInt16Async(ushort idn, ushort value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteUInt32Async(ushort idn, uint value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<ushort?> ReadDataStateAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<List<ushort>> GetAvailableIDNsAsync(int timeoutMs = 5000, CancellationToken cancellationToken = default)
public Task<SoEParameter> GetParameterInfoAsync(ushort idn, int timeoutMs = 5000, CancellationToken cancellationToken = default)
public Task<byte[]?> ReadDefaultValueAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<string?> ReadNameAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<string?> ReadUnitAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<byte[]?> ReadMinValueAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<byte[]?> ReadMaxValueAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<string?> ReadStringAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<float?> ReadFloatAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<double?> ReadDoubleAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> EnableNotificationAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<int> PollNotificationsAsync(int timeoutMs = 200, CancellationToken cancellationToken = default)
- 취소는 호출자에게만 영향을 준다:
Task는OperationCanceledException으로 끝나고, 밑의 동기 호출은 백그라운드에서 끝까지 실행되며 그 결과는 버려지고 기록된다 - 읽기 실패는
null, 쓰기 실패는false를 반환하며 동기 API 와 같다.GetAvailableIDNsAsync/GetParameterInfoAsync의 조회 실패는Task에서 던져지는SoEException으로 드러난다 (동기 버전과 같다) timeoutMs/pollIntervalMs는 해당 동기 메서드로 그대로 전달되며 같은 의미다
예제:
var soe = slave.SoE;
byte[]? status = await soe.ReadAsync(0x0047);
if (status != null && status.Length >= 2)
Console.WriteLine($"状态字: 0x{BitConverter.ToUInt16(status, 0):X4}"); // 상태 워드: 0x{BitConverter.ToUInt16(status, 0):X4}
bool ok = await soe.WriteInt32Async(0x002F, 50000);
int changed = await soe.PollNotificationsAsync();
파라미터 변화 알림
SoE Notification 는 SERCOS 슬레이브의 IDN 파라미터 변화를 감시하고 값이 바뀌면 NotificationReceived 이벤트로 애플리케이션에 알린다. 알림은 애플리케이션 계층에 투명하게, 같은 이벤트 구조로 두 가지 방식 중 하나로 전달된다:
- 하드웨어 알림: SDK 가 먼저 슬레이브 쪽에서 하드웨어 알림을 켜려 시도하고 (알림 요청 S-0-0127, OpCode=5 기록), 슬레이브가 변화를 스스로 밀어온다
- 폴링: 슬레이브가 하드웨어 알림을 지원하지 않으면 SDK 가 자동으로 대체 경로로 넘어간다. 감시 중인 각 IDN 을 읽어 마지막에 기록된 값과 비교하고, 변화를 발견하면 이벤트를 올린다. 이 모드는 애플리케이션 계층이
PollNotifications()을 주기적으로 호출해야 한다. 변화의 지연은 호출 빈도에 달려 있다
NotificationReceived
public event Action<SoENotificationEventArgs>? NotificationReceived;
감시 중인 IDN 파라미터의 값이 바뀔 때 발동한다. 첫 알림에서는 OldValue 가 null 일 수 있다 (기준선이 막 잡혔고 이전 값이 아직 없기 때문이다).
관련 구조체:
public class SoENotificationEventArgs : EventArgs
{
public ushort SlaveIndex { get; set; } // 슬레이브 번호 (1부터 시작)
public byte DriveNumber { get; set; } // 드라이버 번호 (다축 드라이버용)
public ushort IDN { get; set; } // 변경된 IDN 번호
public SoEElementFlags ElementFlags { get; set; } // 알림을 발생시킨 Element 비트 마스크
public byte[]? NewValue { get; set; } // 변경 후 값 (null이면 읽기 실패일 수 있음)
public byte[]? OldValue { get; set; } // 변경 전 값 (첫 알림에서는 null)
public string SercosIDN { get; } // SERCOS 형식, 예: "S-0-0036" (읽기 전용 파생)
}
예제:
if (slave.SoE != null)
{
// 알림 이벤트 등록
slave.SoE.NotificationReceived += (args) =>
{
Console.WriteLine($"参数变化: {args.SercosIDN} (IDN 0x{args.IDN:X4})"); // 매개변수 변경: {args.SercosIDN} (IDN 0x{args.IDN:X4})
Console.WriteLine($" 旧值: {(args.OldValue != null ? BitConverter.ToString(args.OldValue) : "(首次)")}"); // 이전 값: {(args.OldValue != null ? BitConverter.ToString(args.OldValue) : "(첫 번째)")}
Console.WriteLine($" 新值: {(args.NewValue != null ? BitConverter.ToString(args.NewValue) : "N/A")}"); // 새 값: {(args.NewValue != null ? BitConverter.ToString(args.NewValue) : "N/A")}
};
// 실제 위치 감시 켜기 (S-0-0011)
bool hwSupported = slave.SoE.EnableNotification(0x000B);
Console.WriteLine($"硬件通知: {(hwSupported ? "支持" : "回退到轮询")}"); // 하드웨어 알림: {(hwSupported ? "지원" : "폴링으로 폴백")}
// 드라이버 상태 워드 감시 켜기 (S-0-0071)
slave.SoE.EnableNotification(0x0047);
// 타이머에서 주기적으로 폴링한다
while (running)
{
int changed = slave.SoE.PollNotifications();
if (changed > 0)
Console.WriteLine($"检测到 {changed} 个参数变化"); // {changed}개의 매개변수 변경 감지
Thread.Sleep(100);
}
// 감시 중지
slave.SoE.DisableAllNotifications();
}
EnableNotification(ushort idn, int timeoutMs = 500)
public bool EnableNotification(ushort idn, int timeoutMs = 500)
주어진 IDN 의 변화 알림을 켠다. 먼저 S-0-0127 을 통해 하드웨어 알림을 켜려 시도하고, 성공 여부와 무관하게 그 IDN 을 폴링 목록에 넣는다.
매개변수:
idn(ushort) — 감시할 IDN 번호timeoutMs(int) — 밀리초 타임아웃 (기본값 500)
반환값:
bool—true는 슬레이브가 하드웨어 알림을 확인했다는 뜻.false는 폴링 모드로 넘어갔다는 뜻
DisableNotification(ushort idn)
public void DisableNotification(ushort idn)
주어진 IDN 의 변화 알림을 끄고 감시 목록에서 제거한다.
DisableAllNotifications()
public void DisableAllNotifications()
켜져 있는 모든 알림을 끄고 감시 목록을 비운다.
GetMonitoredIDNs()
public List<ushort> GetMonitoredIDNs()
지금 감시 중인 IDN 들의 스냅샷을 반환한다 (EnableNotification 은 넣고, DisableNotification / DisableAllNotifications 은 뺀다). 반환값은 목록의 새 사본이므로 호출자가 자유롭게 순회할 수 있다. 다만 감시 목록 자체는 알림이 켜지고 꺼지면서 계속 바뀐다.
반환값:
List<ushort>— 알림이 켜진 IDN 번호
PollNotifications(int timeoutMs = 200)
public int PollNotifications(int timeoutMs = 200)
감시 중인 모든 IDN 에 대해 파라미터 변화를 폴링한다. 각 현재 값을 읽어 마지막에 기록된 값과 비교하고, 변화를 발견하면 NotificationReceived 이벤트를 올린다. 타이머나 백그레운드 스레드에서 주기적으로 호출하기에 적합하다.
매개변수:
timeoutMs(int) — IDN 읽기 한 번의 타임아웃 (밀리초, 기본값 200)
반환값:
int— 이번 폴링에서 값이 바뀐 IDN 수
런타임 비동기 알림 (Notification / Emergency)
동기 Read/Write API 외에, SoE 는 슬레이브가 비동기로 밀어오는 두 종류의 알림을 지원하며 SDK 는 이를 두 이벤트로 드러낸다:
| 이벤트 | SERCOS OpCode | 용도 |
|---|---|---|
| NotificationReceived | 5 | IDN 파라미터 값 변화 알림 (실시간 모니터링) |
| EmergencyReceived | 6 | 드라이버 Sercos Emergency (긴급 정지 / 오류) |
흔한 용도:
- 서보 파라미터 실시간 모니터링 — HMI 가 S-0-0036 Max Velocity 를 고치면 다른 모니터링 지점이 Notification 을 통해 새 값을 실시간으로 받는다
- 긴급 정지 모니터링 — 드라이버가 하드웨어 수준의 Emergency (과전류 / 과열 / 엔코더 손실) 를 밀어오면 애플리케이션은 즉시 자기 안전 분기로 넘어간다
- 여러 튜닝 지점 간 일관성 — 여러 엔지니어가 다른 호스트 애플리케이션에서 파라미터를 튜닝할 때, 파라미터 변화를 듣고 있는 모든 지점에 브로드캐스트할 수 있다
이벤트를 구독하는 데 슬레이브가 OP 에 있을 필요는 없다. PreOp / SafeOp 에서 메일박스를 쓸 수 있으면 이벤트를 받는다 (메일박스 가용성과 일치한다). 전체 이벤트 목록은 슬레이브 이벤트 참조.
EmergencyReceived
public event Action<SoEEmergencyEventArgs>? EmergencyReceived;
드라이버가 Sercos Emergency (OpCode=6) 를 밀어올 때 발동한다. CoE EMCY 메시지와 달리 Sercos Emergency 는 서보 드라이버 전용이며 오류 코드도 SERCOS 정의를 따른다 (CiA 301 이 아니다). 콜백 안에서 막히는 SDO/SoE 읽기·쓰기를 호출하지 않는다 — 오류 상황에서는 요청이 쉽게 쌓인다.
관련 구조체:
public class SoEEmergencyEventArgs : EventArgs
{
public ushort SlaveIndex { get; set; } // 출처 슬레이브 번호 (1부터 시작)
public byte DriveNumber { get; set; } // 드라이버 번호 (SoEHeader driveNo 비트 필드, 3 bit)
public ushort ErrorCode { get; set; } // Sercos Emergency Error Code (2바이트)
public DateTime Timestamp { get; set; } // 수신 타임스탬프 (UTC)
}
스레드 계약
NotificationReceived / EmergencyReceived 는 SDK 콜백 스레드 에서 발동하며 UI 스레드가 ** 아니다**. WinForms / WPF UI 의 컨트롤을 갱신하려면 Invoke / Dispatcher.Invoke 로 UI 스레드로 돌아와야 한다:
// WinForms
slave.SoE.EmergencyReceived += (args) =>
{
if (mainForm.InvokeRequired)
mainForm.BeginInvoke(new Action(() => HandleEmergency(args)));
else
HandleEmergency(args);
};
콜백 안에서 오래 막히지 않는다 (몇 밀리초를 넘으면 안 된다). SoE 메일박스 처리가 느려지기 때문이다. 오래 걸리는 작업은 Task.Run 으로 옮긴다.
예제:
if (slave.SoE == null) return;
// 1. Notification 구독 (파라미터 실시간 변경)
Action<SoENotificationEventArgs> onNotification = args =>
{
string newStr = args.NewValue != null ? BitConverter.ToString(args.NewValue) : "N/A";
string oldStr = args.OldValue != null ? BitConverter.ToString(args.OldValue) : "(首次)"; // (첫 번째)
Console.WriteLine(
$"[SoE Notify] 从站={args.SlaveIndex} 驱动器={args.DriveNumber} " + // [SoE Notify] 슬레이브={args.SlaveIndex} 드라이버={args.DriveNumber}
$"{args.SercosIDN} (0x{args.IDN:X4}) Elements=0x{(byte)args.ElementFlags:X2} " +
$"旧=[{oldStr}] → 新=[{newStr}]"); // 이전=[{oldStr}] → 새 값=[{newStr}]
};
// 2. Emergency 구독 (치명적 고장)
Action<SoEEmergencyEventArgs> onEmergency = args =>
{
Console.WriteLine(
$"[SoE EMCY] 从站={args.SlaveIndex} 驱动器={args.DriveNumber} " + // [SoE EMCY] 슬레이브={args.SlaveIndex} 드라이버={args.DriveNumber}
$"ErrorCode=0x{args.ErrorCode:X4} @ {args.Timestamp:HH:mm:ss.fff}");
// 일반적인 대응: UI를 고장 분기로 전환하고 모션 축을 정지한다
if (mainForm.InvokeRequired)
mainForm.BeginInvoke(new Action(() => mainForm.ShowEmergencyBanner(args.ErrorCode)));
};
slave.SoE.NotificationReceived += onNotification;
slave.SoE.EmergencyReceived += onEmergency;
// 3. 감시할 IDN 켜기 (여러 개 지원)
slave.SoE.EnableNotification(0x0024); // Max Velocity
slave.SoE.EnableNotification(0x0047); // Drive Status Word
// 4. 애플리케이션 종료 시 구독을 해제해 참조가 남지 않게 한다
try
{
// ... 애플리케이션 실행 ...
}
finally
{
slave.SoE.DisableAllNotifications();
slave.SoE.NotificationReceived -= onNotification;
slave.SoE.EmergencyReceived -= onEmergency;
}
FSoE 안전 슬레이브 인터페이스 (slave.FSoE)
아래 멤버들은 slave.FSoE (FSoEInstance) 에 있으며 같은 안전 프레임과 메일박스 채널을 쓰므로 진입점을 여기에 나열한다. 안전 프로토콜 상태 기계, 연결 파라미터, 안전 PDO 의미는 FSoE 참조.
| 분류 | 속성 | 타입 | 읽기·쓰기 | 설명 |
|---|---|---|---|---|
| 안전 IO | SafeInputFaulted | bool | 읽기 전용 | 가장 최근 PDO 사이클에서 안전 입력 갱신이 실패했는지. true = 읽기가 실패하거나 예외를 던짐. 인스턴스는 이전 사이클의 낡은 데이터를 아직 들고 있으므로 새 안전 입력으로 취급하면 안 된다 |
| 안전 IO | SafeOutputFaulted | bool | 읽기 전용 | 가장 최근 PDO 사이클에서 안전 출력 커밋이 실패했는지. true = 안전 출력이 슬레이브에 기록되지 않았으므로 상위 계층이 발행된 것으로 취급하면 안 된다 |
| 안전 IO | SafeIoFaulted | bool | 읽기 전용 | 안전 IO 가 오류 상태인지 (입력 갱신 실패 또는 출력 커밋 실패). 안전 애플리케이션은 이번 사이클에 자기 페일세이프 로직을 적용해야 한다 |
세 플래그 모두 사이클 전처리와 후처리가 관리하며 갱신이 성공하면 자동으로 리셋된다. 수동으로 지울 필요가 없다.
GetDeviceAddress(out ushort safetyAddress)
public bool GetDeviceAddress(out ushort safetyAddress)
SDO 로 0xF980:01 을 읽어 호출 시점의 슬레이브 안전 주소를 얻는다. 호출할 때마다 실제로 메일박스 명령을 보내므로 속성이 아니라 메서드인 것이다.
매개변수:
safetyAddress(out ushort) — 안전 주소. 실패하면 0
반환값:
bool— true = 읽기 성공. false = 읽기 실패 또는 예외 (원인은 기록된다)
GetModuleCommParam(ushort moduleNumber)
public byte[]? GetModuleCommParam(ushort moduleNumber)
SDO 로 0x9nn1 을 읽어 MDP 모듈의 통신 파라미터를 얻는다 (nn 은 모듈 번호). 값은 호출 시점에 읽으며 캐시하지 않는다.
매개변수:
moduleNumber(ushort) — 모듈 번호
반환값:
byte[]?— 통신 파라미터 바이트. 읽기가 실패하거나 길이가 잘못되면null(빈 배열이 아니다)
GetModuleDiagnosis(ushort moduleNumber, out ushort connectionState, out ushort connectionDiagnosis)
public bool GetModuleDiagnosis(ushort moduleNumber, out ushort connectionState, out ushort connectionDiagnosis)
SDO 로 0xAnn0 을 읽어 MDP 모듈의 연결 상태와 연결 진단을 얻는다.
매개변수:
moduleNumber(ushort) — 모듈 번호connectionState(out ushort) — 연결 상태. 실패하면 0connectionDiagnosis(out ushort) — 연결 진단. 실패하면 0
반환값:
bool— true = 읽기 성공. false = 읽기 실패 또는 예외
FSoEPdoLayout.Create(int safeDataLength)
public static FSoEPdoLayout Create(int safeDataLength)
안전 데이터 길이로 안전 프레임 레이아웃을 만든다: 명령 바이트 오프셋, 안전 데이터 오프셋과 길이, 각 체크섬 조각의 오프셋, Connection ID 오프셋, 끝 패딩.
매개변수:
safeDataLength(int) — 안전 데이터 길이 (바이트)
반환값:
FSoEPdoLayout— 프레임 레이아웃 인스턴스.CrcSegmentCount는 체크섬 조각 수,TotalLength는 프레임 전체 길이
관련 구조체:
public sealed class FSoEPdoLayout
{
public int CommandOffset { get; set; } // 명령 바이트 오프셋
public int SafeDataOffset { get; set; } // 안전 데이터 시작 오프셋
public int SafeDataLength { get; set; } // 안전 데이터 총 길이 (바이트)
public int PaddingBytes { get; set; } // 마지막 데이터 세그먼트의 패딩 바이트 수
public int[] CrcOffsets { get; set; } // 각 검증 세그먼트의 프레임 내 오프셋
public int ConnIdOffset { get; set; } // Connection ID 오프셋
public int CrcSegmentCount { get; } // 검증 세그먼트 수
public int TotalLength { get; } // 프레임 전체 길이
}
오류 처리
public SoEError? LastSoEError { get; } // 가장 최근 SoE 작업 오류 코드: 성공 시 null, 실패 시 해당 오류 코드
public MailboxStatus LastStatus { get; } // 가장 최근 메일박스 트랜잭션의 통합 상태 (Success / MailboxError 등)
public uint LastErrorCode { get; } // LastSoEError와 같은 원천이고 uint로 표시한다
모든 Read / Write (타입 지정 읽기·쓰기 포함) 이후 자동으로 갱신된다. 실패한 Read 는 null, 실패한 Write 는 false 를 반환하며 그때 LastSoEError 가 구체적 원인을 알려준다 (예: NoIDN = IDN 이 없다).
GetAvailableIDNs / GetParameterInfo / GetIDNMapping 같은 조회는 실패하면 SoEException 을 던진다. 성공한 척하는 빈 목록 / 빈 껍데기 객체를 반환하지 않는다:
public class SoEException : Exception { }
관련 구조체:
SoE 작업 오류 코드 (SERCOS / ETG.1000.6 §5.11):
public enum SoEError : ushort
{
NoError = 0x0000,
NoIDN = 0x1001, // IDN이 존재하지 않음
InvalidAccessToElement1 = 0x1009,
NoName = 0x2001,
NameTransmissionTooShort = 0x2002,
NameTransmissionTooLong = 0x2003,
NameCannotBeChanged = 0x2004,
NameWriteProtected = 0x2005,
AttributeTransmissionTooShort = 0x3002,
AttributeTransmissionTooLong = 0x3003,
AttributeCannotBeChanged = 0x3004,
AttributeWriteProtected = 0x3005,
NoUnits = 0x4001,
UnitTransmissionTooShort = 0x4002,
UnitTransmissionTooLong = 0x4003,
UnitCannotBeChanged = 0x4004,
UnitWriteProtected = 0x4005,
NoMinimumInputValue = 0x5001,
MinimumInputValueTransmissionTooShort = 0x5002,
MinimumInputValueTransmissionTooLong = 0x5003,
MinimumInputValueCannotBeChanged = 0x5004,
MinimumInputValueWriteProtected = 0x5005,
NoMaximumInputValue = 0x6001,
MaximumInputValueTransmissionTooShort = 0x6002,
MaximumInputValueTransmissionTooLong = 0x6003,
MaximumInputValueCannotBeChanged = 0x6004,
MaximumInputValueWriteProtected = 0x6005,
NoOperationData = 0x7001,
OperationDataTransmissionTooShort = 0x7002,
OperationDataTransmissionTooLong = 0x7003,
OperationDataCannotBeChanged = 0x7004,
OperationDataWriteProtectedByState = 0x7005,
OperationDataSmallerThanMinimum = 0x7006,
OperationDataGreaterThanMaximum = 0x7007,
InvalidOperationDataConfiguredIDNNotSupported = 0x7008,
OperationDataWriteProtectedByPassword = 0x7009,
OperationDataCyclicallyWriteProtected = 0x700A,
InvalidIndirectAddressing = 0x700B,
OperationDataWriteProtectedBySettings = 0x700C,
Reserved_700D = 0x700D,
ProcedureCommandAlreadyActive = 0x7010,
ProcedureCommandNotInterruptible = 0x7011,
ProcedureCommandNotExecutableState = 0x7012,
ProcedureCommandNotExecutableInvalidParameters = 0x7013,
NoDataState = 0x7014,
NoDefaultValue = 0x8001,
DefaultValueTransmissionTooLong = 0x8002,
DefaultValueTransmissionTooShort = 0x8003,
DefaultValueCannotBeChanged = 0x8004,
DefaultValueWriteProtected = 0x8005,
InvalidDriveNumber = 0x800A,
GeneralError = 0x800B,
NoElementAddressed = 0x800C,
Unknown = 0xFFFF
}
예제:
byte[]? data = slave.SoE.Read(0x000B);
if (data == null)
{
if (slave.SoE.LastSoEError == SoEError.NoIDN)
Console.WriteLine("IDN 不存在"); // IDN이 존재하지 않습니다
else
Console.WriteLine($"SoE 读取失败: {slave.SoE.LastSoEError}"); // SoE 읽기 실패: {slave.SoE.LastSoEError}
}
IDN 인코딩 헬퍼
SDK 는 16 비트 IDN 번호와 (标准/厂商, 参数集, 数据块) 세 요소, 또는 SERCOS 문자열을 서로 변환하는 정적 헬퍼 메서드 묶음을 제공한다. 비트 배치: bit15 = 0 표준 (S) / 1 벤더 (P), bit14..12 = 파라미터 세트 Set (0-7), bit11..0 = 데이터 블록 Block (0-4095).
| 분류 | 메서드 | 반환 타입 | 읽기·쓰기 | 설명 |
|---|---|---|---|---|
| 인코딩 | EncodeIdn(bool isStandard, byte parameterSet, ushort dataBlock) | ushort | 읽기 전용 | 세 요소를 16 비트 IDN 으로 인코딩한다 |
| 디코딩 | DecodeIdn(ushort idn) | (bool IsStandard, byte ParameterSet, ushort DataBlock) | 읽기 전용 | 16 비트 IDN 을 세 요소로 디코딩한다 |
| 파싱 | TryParseSercosIdn(string text, out ushort idn) | bool | 읽기 전용 | SERCOS 문자열 ("S-0-0040" / "P-1-0123" 등) 을 IDN 으로 파싱한다 |
public static ushort EncodeIdn(bool isStandard, byte parameterSet, ushort dataBlock)
public static (bool IsStandard, byte ParameterSet, ushort DataBlock) DecodeIdn(ushort idn)
public static bool TryParseSercosIdn(string text, out ushort idn)
예제:
// 인코딩: 표준 IDN S-0-0040 (호밍 속도)
ushort idn = DarraEtherCAT.Slave.SoEInstance.EncodeIdn(isStandard: true, parameterSet: 0, dataBlock: 40);
// 디코딩
var (isStd, set, block) = DarraEtherCAT.Slave.SoEInstance.DecodeIdn(idn);
Console.WriteLine($"标准={isStd}, 参数集={set}, 数据块={block}"); // 표준={isStd}, 매개변수 집합={set}, 데이터 블록={block}
// 문자열에서 파싱
if (DarraEtherCAT.Slave.SoEInstance.TryParseSercosIdn("S-0-0040", out ushort parsed))
{
byte[]? data = slave.SoE.Read(parsed);
}
이 메서드들은 순수 비트 연산이라 슬레이브에 접근하지 않으므로, 슬레이브가 온라인이 아니어도 호출할 수 있다.
표준 IDN 상수
public static class StandardIDN
{
public const ushort IDNList = 0x0000; // IDN 목록 (S-0-0000)
public const ushort CycleTime = 0x0001; // 통신 사이클 시간 (S-0-0001)
public const ushort SyncTime = 0x0002; // 동기화 타임스탬프 T_scyc (S-0-0002)
public const ushort MdtToAtDelay = 0x0003; // MDT에서 AT까지 간격 T_mtsy (S-0-0003)
public const ushort ATConfig = 0x0010; // AT 구성 - 입력 매핑 (S-0-0016)
public const ushort ProcedureCommandList = 0x0011;// 절차 명령 IDN 목록 (S-0-0017)
public const ushort MDTConfig = 0x0018; // MDT 구성 - 출력 매핑 (S-0-0024)
public const ushort WritableIDNs = 0x0019; // 쓰기 가능한 IDN 목록 (S-0-0025)
public const ushort ConfigurationIDNs = 0x001A; // 구성 IDN 목록 (S-0-0026)
public const ushort NotificationRequest = 0x007F; // 알림 요청 (S-0-0127)
public const ushort PrimaryOperationMode = 0x0020;// 주 동작 모드 (S-0-0032)
public const ushort VelocityLoopKv = 0x002C; // 속도 루프 비례 이득 Kv (S-0-0044)
public const ushort PositionCommand = 0x002F; // 위치 명령 (S-0-0047)
public const ushort PositionFeedback = 0x0033; // 위치 피드백 (S-0-0051)
public const ushort DiagnosticMessage = 0x005F; // 진단 메시지 (S-0-0095)
public const ushort PositionLoopKv = 0x0064; // 위치 제어기 Kv (S-0-0100)
}
전체 예제
var slave = master.Slaves[0];
if (slave.SoE == null)
{
Console.WriteLine("该从站不支持 SoE"); // 이 슬레이브는 SoE를 지원하지 않습니다
return;
}
// 통신 사이클 시간 읽기 (S-0-0001)
byte[]? cycleRaw = slave.SoE.Read(0x0001);
if (cycleRaw == null)
{
Console.WriteLine($"读取失败: {slave.SoE.LastSoEError}"); // 읽기 실패: {slave.SoE.LastSoEError}
}
else
{
Console.WriteLine($"周期时间: {BitConverter.ToUInt32(cycleRaw, 0)} μs"); // 사이클 시간: {BitConverter.ToUInt32(cycleRaw, 0)} µs
}
// 목표 위치 기록 (S-0-0047)
byte[] targetPosition = BitConverter.GetBytes(100000);
if (!slave.SoE.Write(0x002F, targetPosition))
{
Console.WriteLine($"写入失败: {slave.SoE.LastSoEError}"); // 쓰기 실패: {slave.SoE.LastSoEError}
}
// 실제 위치 다시 읽기 (S-0-0051)
byte[]? actualRaw = slave.SoE.Read(0x0033);
if (actualRaw != null)
Console.WriteLine($"实际位置: {BitConverter.ToInt32(actualRaw, 0)}"); // 실제 위치: {BitConverter.ToInt32(actualRaw, 0)}
파라미터 스캔
if (slave.SoE != null)
{
var idns = slave.SoE.GetAvailableIDNs();
Console.WriteLine($"从站支持 {idns.Count} 个 IDN 参数\n"); // 슬레이브가 {idns.Count}개의 IDN 매개변수를 지원
foreach (var idn in idns.Take(10))
{
var info = slave.SoE.GetParameterInfo(idn);
Console.WriteLine($"{info.SercosIDN}: {info.Name} = {info.FormattedValue} {info.Unit} [{info.AccessMode}]");
}
}
서보 드라이버 제어
if (slave.SoE != null)
{
// 1. 드라이버 상태 읽기
ushort? statusWord = slave.SoE.ReadUInt16(0x0047);
Console.WriteLine($"状态字: 0x{statusWord:X4}"); // 상태 워드: 0x{statusWord:X4}
// 2. AT/MDT 매핑 확인 (주기 데이터 레이아웃 파악)
var mapping = slave.SoE.GetIDNMapping();
Console.WriteLine($"\nAT 映射(输入 {mapping.ATByteSize} 字节):"); // AT 매핑(입력 {mapping.ATByteSize} 바이트):
foreach (var entry in mapping.ATMapping)
Console.WriteLine($" IDN 0x{entry.IDN:X4}: {entry.Name} ({entry.ByteLength}B)");
Console.WriteLine($"\nMDT 映射(输出 {mapping.MDTByteSize} 字节):"); // MDT 매핑(출력 {mapping.MDTByteSize} 바이트):
foreach (var entry in mapping.MDTMapping)
Console.WriteLine($" IDN 0x{entry.IDN:X4}: {entry.Name} ({entry.ByteLength}B)");
// 3. 제어 워드를 기록해 드라이버를 활성화 (S-0-0064)
slave.SoE.WriteUInt16(0x0040, 0x0006);
// 4. 목표 위치 설정 (S-0-0012)
slave.SoE.WriteInt32(0x000C, 50000);
// 5. 실제 위치 읽기 (S-0-0011)
int? actualPos = slave.SoE.ReadInt32(0x000B);
Console.WriteLine($"\n实际位置: {actualPos} inc"); // 실제 위치: {actualPos} inc
}
실패와 대응
| 증상 | 원인 | 대응 |
|---|---|---|
| 읽기가 null 을 반환하고 오류 코드가 IDN 없음을 알림 | 슬레이브에 그 번호의 IDN 이 없다 | 장치 매뉴얼에 실린 IDN 을 쓴다. 먼저 그 파라미터가 표준 범위인지 벤더 정의 범위인지 확인한다 |
| 쓰기가 false 를 반환하고 오류 코드가 쓰기 보호를 알림 | 파라미터가 쓰기 보호되어 있다 (비밀번호, 설정 또는 접근 권한) | 그 파라미터를 쓸 수 있는지 확인하고, 필요하면 쓰기 권한이 있는 접근 레벨로 전환한 뒤 쓴다 |
| 읽기 / 쓰기가 실패하고 오류 코드가 타임아웃을 알림 | 메일박스 트랜잭션이 시간 초과되었거나 슬레이브가 답하지 않았다 | 슬레이브 메일박스가 쓸 수 있고 상태가 정상인지 확인한 뒤 재시도한다. 타임아웃이 반복되면 timeoutMs 를 늘린다 |
| 작업이 거부되고 오류 코드가 상태가 허용하지 않음을 알림 | 그 파라미터는 특정 서보 상태에서만 쓸 수 있다 | 서보가 그 파라미터를 허용하는 상태에 이를 때까지 기다린 뒤 쓴다. 상태 전이 창은 피한다 |