//! EtherCAT 类型定义 - 与 C# Data/Type.cs 对应
//!
//! 包含 EtherCAT 协议中使用的所有枚举、标志位和辅助类型。

use std::fmt;

// ===================== 错误码 =====================

/// 错误码
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcErr {
    /// 无错误
    Ok = 0,
    /// 已初始化
    AlreadyInitialized = 1,
    /// 未初始化
    NotInitialized = 2,
    /// 超时
    Timeout = 3,
    /// 未发现从站
    NoSlaves = 4,
    /// 操作失败
    Nok = 5,
}

// ===================== EtherCAT 从站状态 =====================

/// EtherCAT 从站状态
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcState {
    /// 无状态
    None = 0x00,
    /// 初始化
    Init = 0x01,
    /// 预运行
    PreOp = 0x02,
    /// Bootstrap
    Boot = 0x03,
    /// 安全运行
    SafeOp = 0x04,
    /// 运行
    OP = 0x08,
    /// 错误确认 / 错误标志 (0x10)
    Ack = 0x10,
    // 注意: Error = 0x10 与 Ack 相同, Rust 不允许重复判别值
    // 使用 Ack 表示, 语义等同于 Error
}

impl EcState {
    /// 从原始值创建
    pub fn from_value(v: u8) -> Self {
        match v & 0x0F {
            0x00 => Self::None,
            0x01 => Self::Init,
            0x02 => Self::PreOp,
            0x03 => Self::Boot,
            0x04 => Self::SafeOp,
            0x08 => Self::OP,
            _ => Self::None,
        }
    }

    /// 检查是否包含 Error 标志 (0x10)
    pub fn has_error(raw: u8) -> bool {
        (raw & 0x10) != 0
    }

    /// 格式化状态为可读字符串, 支持复合状态如 0x14 = SafeOp+Error
    pub fn format(raw: u8) -> String {
        let base = Self::from_value(raw);
        let name = match base {
            Self::None => "None",
            Self::Init => "Init",
            Self::PreOp => "PreOp",
            Self::Boot => "Boot",
            Self::SafeOp => "SafeOp",
            Self::OP => "OP",
            Self::Ack => "Ack",
        };
        if Self::has_error(raw) {
            format!("{}+Error", name)
        } else {
            name.to_string()
        }
    }
}

// ===================== 链路状态 =====================

/// 链路状态
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcLinkState {
    /// 无连接
    Disconnected = 0,
    /// 主网口和冗余网口都连接
    Connected = 1,
    /// 仅主网口连接
    PrimaryOnly = 3,
    /// 仅冗余网口连接
    SecondaryOnly = 4,
}

impl EcLinkState {
    /// 从原始值创建
    pub fn from_value(v: u8) -> Self {
        match v {
            0 => Self::Disconnected,
            1 => Self::Connected,
            3 => Self::PrimaryOnly,
            4 => Self::SecondaryOnly,
            _ => Self::Disconnected,
        }
    }
}

// ===================== 环拓扑冗余模式 =====================

/// 环拓扑冗余运行模式
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RingMode {
    /// 未激活: 冗余监控未初始化
    Inactive = 0,
    /// 双向冗余: P1打开, secondary激活后两端发送LRW
    Dual = 1,
    /// 降级模式: secondary链路不可用, 仅primary工作
    Degraded = 2,
}

impl RingMode {
    /// 从原始值创建
    pub fn from_value(v: i32) -> Self {
        match v {
            0 => Self::Inactive,
            1 => Self::Dual,
            2 => Self::Degraded,
            _ => Self::Inactive,
        }
    }
}

// ===================== 缓冲区状态 =====================

/// 缓冲区状态
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcBufState {
    /// 空
    Empty = 0x00,
    /// 已分配
    Alloc = 0x01,
    /// 发送中
    Tx = 0x02,
    /// 已接收
    Rcvd = 0x03,
    /// 完成
    Complete = 0x04,
}

// ===================== EtherCAT 数据类型 =====================

/// EtherCAT 数据类型
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcDataType {
    /// 布尔
    Boolean = 0x0001,
    /// 有符号8位整数
    Integer8 = 0x0002,
    /// 有符号16位整数
    Integer16 = 0x0003,
    /// 有符号32位整数
    Integer32 = 0x0004,
    /// 无符号8位整数
    Unsigned8 = 0x0005,
    /// 无符号16位整数
    Unsigned16 = 0x0006,
    /// 无符号32位整数
    Unsigned32 = 0x0007,
    /// 32位浮点
    Real32 = 0x0008,
    /// 可见字符串
    VisibleString = 0x0009,
    /// 八进制字符串
    OctetString = 0x000A,
    /// Unicode字符串
    UnicodeString = 0x000B,
    /// 时间
    TimeOfDay = 0x000C,
    /// 时间差
    TimeDifference = 0x000D,
    /// 域数据
    Domain = 0x000F,
    /// 有符号24位整数
    Integer24 = 0x0010,
    /// 64位浮点
    Real64 = 0x0011,
    /// ETG.1000.6 Table 63: 40位有符号整数
    Integer40 = 0x0012,
    /// ETG.1000.6 Table 63: 48位有符号整数
    Integer48 = 0x0013,
    /// ETG.1000.6 Table 63: 56位有符号整数
    Integer56 = 0x0014,
    /// 有符号64位整数
    Integer64 = 0x0015,
    /// 无符号24位整数
    Unsigned24 = 0x0016,
    /// ETG.1000.6 Table 63: 40位无符号整数
    Unsigned40 = 0x0018,
    /// ETG.1000.6 Table 63: 48位无符号整数
    Unsigned48 = 0x0019,
    /// ETG.1000.6 Table 63: 56位无符号整数
    Unsigned56 = 0x001A,
    /// 无符号64位整数
    Unsigned64 = 0x001B,
    /// 1位
    Bit1 = 0x0030,
    /// 2位
    Bit2 = 0x0031,
    /// 3位
    Bit3 = 0x0032,
    /// 4位
    Bit4 = 0x0033,
    /// 5位
    Bit5 = 0x0034,
    /// 6位
    Bit6 = 0x0035,
    /// 7位
    Bit7 = 0x0036,
    /// 8位
    Bit8 = 0x0037,
}

// ===================== EtherCAT 命令类型 =====================

/// EtherCAT 命令类型
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcCmdType {
    /// 无操作
    Nop = 0x00,
    /// 自增寻址物理读
    Aprd = 0x01,
    /// 自增寻址物理写
    Apwr = 0x02,
    /// 自增寻址物理读写
    Aprw = 0x03,
    /// 配置地址物理读
    Fprd = 0x04,
    /// 配置地址物理写
    Fpwr = 0x05,
    /// 配置地址物理读写
    Fprw = 0x06,
    /// 广播读
    Brd = 0x07,
    /// 广播写
    Bwr = 0x08,
    /// 广播读写
    Brw = 0x09,
    /// 逻辑读
    Lrd = 0x0A,
    /// 逻辑写
    Lwr = 0x0B,
    /// 逻辑读写
    Lrw = 0x0C,
    /// 自增寻址物理读-多写
    Armw = 0x0D,
    /// 配置地址物理读-多写
    Frmw = 0x0E,
}

// ===================== EEPROM 命令类型 =====================

/// EtherCAT EEPROM 命令类型
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcEcmdType {
    /// 无操作
    Nop = 0x0000,
    /// 读取
    Read = 0x0100,
    /// 写入
    Write = 0x0201,
    /// 重载
    Reload = 0x0300,
}

// ===================== 日志级别 =====================

/// 日志级别
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    /// 信息
    Info = 0,
    /// 调试
    Debug = 1,
    /// 警告
    Warn = 2,
    /// 错误
    Error = 3,
    /// 致命错误
    Fatal = 4,
}

// ===================== AL 状态码 (ETG.1020) =====================

/// AL 状态码 (ETG.1020)
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcALState {
    /// 无错误
    NoError = 0x0000,
    /// 未指定错误
    UnspecifiedError = 0x0001,
    /// 内存不足
    NoMemory = 0x0002,
    /// 无效的设备设置 (如总线耦合器无物理模块连接)
    InvalidDeviceSetup = 0x0003,
    /// 输出/输入映射与硬件或软件修订版不匹配
    InvalidRevision = 0x0004,
    /// SII/EEPROM 内容与固件不匹配
    SiiEepromMismatch = 0x0006,
    /// 固件更新失败, 旧固件仍在运行
    FirmwareUpdateFailed = 0x0007,
    /// 硬件/软件许可证无效或评估期到期
    LicenseError = 0x000E,
    /// 无效的状态转换
    InvalidStateChange = 0x0011,
    /// 请求了未知状态
    UnknownRequestedState = 0x0012,
    /// 不支持 Bootstrap 模式
    BootstrapNotSupported = 0x0013,
    /// 无有效固件
    NoValidFirmware = 0x0014,
    /// 无效的邮箱配置 (1)
    InvalidMailboxConfig = 0x0015,
    /// 无效的邮箱配置 (2)
    InvalidMailBoxConfig = 0x0016,
    /// 无效的 SyncManager 配置
    InvalidSyncManagerConfig = 0x0017,
    /// 无有效输入
    NoValidInputs = 0x0018,
    /// 无有效输出
    NoValidOutputs = 0x0019,
    /// 同步错误
    SyncError = 0x001A,
    /// SyncManager 看门狗超时
    SyncManagerWatchdog = 0x001B,
    /// 无效的 SyncManager 类型
    InvalidSyncManagerTypes = 0x001C,
    /// 无效的输出配置
    InvalidOutputConfig = 0x001D,
    /// 无效的输入配置
    InvalidInputConfig = 0x001E,
    /// 无效的看门狗配置
    InvalidWatchdogConfig = 0x001F,
    /// 需要冷启动
    NeedsColdStart = 0x0020,
    /// 需要 Init 状态
    NeedsInit = 0x0021,
    /// 需要 PreOp 状态
    NeedsPreOp = 0x0022,
    /// 需要 SafeOp 状态
    NeedsSafeOp = 0x0023,
    /// 无效的输入映射
    InvalidInputMapping = 0x0024,
    /// 无效的输出映射
    InvalidOutputMapping = 0x0025,
    /// 不一致的设置
    InconsistentSettings = 0x0026,
    /// 不支持自由运行模式
    FreerunNotSupported = 0x0027,
    /// 不支持同步模式
    SyncNotSupported = 0x0028,
    /// 自由运行模式需要3缓冲区
    FreerunNeeds3Buffer = 0x0029,
    /// 后台看门狗
    BackgroundWatchdog = 0x002A,
    /// 无有效 IO
    NoValidIO = 0x002B,
    /// 致命同步错误
    FatalSyncError = 0x002C,
    /// 无同步错误
    NoSyncError = 0x002D,
    /// EtherCAT 周期时间小于从站支持的最小周期时间
    CycleTimeTooSmall = 0x002E,
    /// 无效的 DC 同步配置
    InvalidDcSyncConfig = 0x0030,
    /// 无效的 DC Latch 配置
    InvalidDcLatch = 0x0031,
    /// PLL 错误
    PllError = 0x0032,
    /// DC 同步 IO 错误
    DcSyncIOError = 0x0033,
    /// DC 同步超时
    DcSyncTimeout = 0x0034,
    /// 无效的 DC 同步周期
    InvalidDcSyncCycle = 0x0035,
    /// 无效的 Sync0 周期
    InvalidSync0Cycle = 0x0036,
    /// 无效的 Sync1 周期
    InvalidSync1Cycle = 0x0037,
    /// 邮箱 AoE 协议错误
    MailboxAoe = 0x0041,
    /// 邮箱 EoE 协议错误
    MailboxEoe = 0x0042,
    /// 邮箱 CoE 协议错误
    MailboxCoe = 0x0043,
    /// 邮箱 FoE 协议错误
    MailboxFoe = 0x0044,
    /// 邮箱 SoE 协议错误
    MailboxSoe = 0x0045,
    /// 邮箱 VoE 协议错误
    MailboxVoe = 0x004F,
    /// EEPROM 无访问权限
    EepromNoAccess = 0x0050,
    /// EEPROM 错误
    EepromError = 0x0051,
    /// 外部硬件未就绪 (外部连接或信号缺失)
    ExternalHardwareNotReady = 0x0052,
    /// 从站重启
    SlaveRestarted = 0x0060,
    /// 设备 ID 更新
    DeviceIdUpdated = 0x0061,
    /// 检测到的模块标识列表与配置不匹配
    ModuleIdentListMismatch = 0x0070,
    /// 供电电压过低
    SupplyVoltageTooLow = 0x0080,
    /// 供电电压过高
    SupplyVoltageTooHigh = 0x0081,
    /// 温度过低
    TemperatureTooLow = 0x0082,
    /// 温度过高
    TemperatureTooHigh = 0x0083,
    /// 应用控制器可用
    AppControllerAvailable = 0x00F0,
    /// 未知错误
    Unknown = 0xFFFF,
}

impl EcALState {
    /// 从原始 i32 值创建
    pub fn from_value(v: i32) -> Self {
        match v {
            0x0000 => Self::NoError,
            0x0001 => Self::UnspecifiedError,
            0x0002 => Self::NoMemory,
            0x0003 => Self::InvalidDeviceSetup,
            0x0004 => Self::InvalidRevision,
            0x0006 => Self::SiiEepromMismatch,
            0x0007 => Self::FirmwareUpdateFailed,
            0x000E => Self::LicenseError,
            0x0011 => Self::InvalidStateChange,
            0x0012 => Self::UnknownRequestedState,
            0x0013 => Self::BootstrapNotSupported,
            0x0014 => Self::NoValidFirmware,
            0x0015 => Self::InvalidMailboxConfig,
            0x0016 => Self::InvalidMailBoxConfig,
            0x0017 => Self::InvalidSyncManagerConfig,
            0x0018 => Self::NoValidInputs,
            0x0019 => Self::NoValidOutputs,
            0x001A => Self::SyncError,
            0x001B => Self::SyncManagerWatchdog,
            0x001C => Self::InvalidSyncManagerTypes,
            0x001D => Self::InvalidOutputConfig,
            0x001E => Self::InvalidInputConfig,
            0x001F => Self::InvalidWatchdogConfig,
            0x0020 => Self::NeedsColdStart,
            0x0021 => Self::NeedsInit,
            0x0022 => Self::NeedsPreOp,
            0x0023 => Self::NeedsSafeOp,
            0x0024 => Self::InvalidInputMapping,
            0x0025 => Self::InvalidOutputMapping,
            0x0026 => Self::InconsistentSettings,
            0x0027 => Self::FreerunNotSupported,
            0x0028 => Self::SyncNotSupported,
            0x0029 => Self::FreerunNeeds3Buffer,
            0x002A => Self::BackgroundWatchdog,
            0x002B => Self::NoValidIO,
            0x002C => Self::FatalSyncError,
            0x002D => Self::NoSyncError,
            0x002E => Self::CycleTimeTooSmall,
            0x0030 => Self::InvalidDcSyncConfig,
            0x0031 => Self::InvalidDcLatch,
            0x0032 => Self::PllError,
            0x0033 => Self::DcSyncIOError,
            0x0034 => Self::DcSyncTimeout,
            0x0035 => Self::InvalidDcSyncCycle,
            0x0036 => Self::InvalidSync0Cycle,
            0x0037 => Self::InvalidSync1Cycle,
            0x0041 => Self::MailboxAoe,
            0x0042 => Self::MailboxEoe,
            0x0043 => Self::MailboxCoe,
            0x0044 => Self::MailboxFoe,
            0x0045 => Self::MailboxSoe,
            0x004F => Self::MailboxVoe,
            0x0050 => Self::EepromNoAccess,
            0x0051 => Self::EepromError,
            0x0052 => Self::ExternalHardwareNotReady,
            0x0060 => Self::SlaveRestarted,
            0x0061 => Self::DeviceIdUpdated,
            0x0070 => Self::ModuleIdentListMismatch,
            0x0080 => Self::SupplyVoltageTooLow,
            0x0081 => Self::SupplyVoltageTooHigh,
            0x0082 => Self::TemperatureTooLow,
            0x0083 => Self::TemperatureTooHigh,
            0x00F0 => Self::AppControllerAvailable,
            _ => Self::Unknown,
        }
    }
}

// ===================== AL 错误分类 =====================

/// AL 错误分类
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ALErrorCategory {
    /// 无错误
    None,
    /// 临时错误 - 可通过重试自动恢复
    Transient,
    /// 配置错误 - 需要重新配置
    Configuration,
    /// 硬件错误 - 需要用户干预
    Hardware,
    /// 未知错误
    Unknown,
}

/// 根据 AL Status Code 判断错误类别 (参考 ETG.1020)
pub fn classify_al_error(code: u16) -> ALErrorCategory {
    match code {
        0x0000 => ALErrorCategory::None,
        // 临时错误 (可自动恢复)
        0x0011 | // 无效的状态请求
        0x001B | // SM 看门狗超时
        0x001D | // 无效的 SM 类型
        0x0032 | // PLL 错误
        0x0033 | // DC Sync IO 错误
        0x0034   // DC Sync 超时
            => ALErrorCategory::Transient,
        // 配置错误 (需要重新配置)
        0x0015 | // 无效的邮箱配置
        0x0016 | // 无效的邮箱配置
        0x0017 | // 无效的 SM 配置
        0x0018 | // 无有效输入
        0x0019 | // 无有效输出
        0x001A | // 同步错误
        0x001C | // 无效的 SM 配置
        0x001E | // 无效的输入配置
        0x001F | // 无效的看门狗配置
        0x0030 | // 无效的 DC SYNC 配置
        0x0031   // 无效的 DC Latch 配置
            => ALErrorCategory::Configuration,
        // 硬件错误 (需要用户干预)
        0x0042 | // 邮箱 EoE 协议错误
        0x0043 | // 邮箱 CoE 协议错误
        0x0050 | // EEPROM 无访问权限
        0x0051 | // EEPROM 错误
        0x0060   // 从站重启
            => ALErrorCategory::Hardware,
        _ => {
            if code >= 0x0040 && code <= 0x005F {
                ALErrorCategory::Hardware
            } else {
                ALErrorCategory::Unknown
            }
        }
    }
}

// ===================== ETG.1510 诊断消息 =====================

/// ETG.1510 诊断消息
#[derive(Debug, Clone)]
pub struct DiagnosticMessage {
    /// 子索引
    pub sub_index: u8,
    /// 诊断代码
    pub diag_code: u32,
    /// 标志位
    pub flags: u16,
    /// 文本索引
    pub text_index: u16,
    /// 原始数据
    pub raw_data: Vec<u8>,
}

impl fmt::Display for DiagnosticMessage {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Diag[{}]: Code=0x{:08X}, Flags=0x{:04X}",
            self.sub_index, self.diag_code, self.flags)
    }
}

// ===================== 从站错误计数器 =====================

/// 从站级错误统计 (ETG.1020, 寄存器 0x0300-0x0307)
#[derive(Debug, Clone, Default)]
pub struct SlaveErrorCounters {
    /// 从站编号
    pub slave_index: i32,
    /// 端口 0 CRC 错误 (寄存器 0x0300)
    pub port0_crc_errors: u32,
    /// 端口 1 CRC 错误 (寄存器 0x0302)
    pub port1_crc_errors: u32,
    /// 端口 2 CRC 错误 (寄存器 0x0304)
    pub port2_crc_errors: u32,
    /// 端口 3 CRC 错误 (寄存器 0x0306)
    pub port3_crc_errors: u32,
    /// 帧错误计数
    pub frame_errors: u32,
    /// 丢帧计数
    pub lost_frames: u32,
}

// ===================== 邮箱错误 =====================

/// 邮箱错误
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MailboxError {
    /// 无错误
    NoError = 0x0000,
    /// 语法错误
    SyntaxError = 0x0001,
    /// 协议不支持
    ProtocolNotSupported = 0x0002,
    /// 通道字段错误
    WrongChannelField = 0x0003,
    /// 服务不支持
    ServiceNotSupported = 0x0004,
    /// 无效的邮箱头
    InvalidMailboxHeader = 0x0005,
    /// 数据太短
    DataTooShort = 0x0006,
    /// 从站内存不足
    NoMemoryInSlave = 0x0007,
    /// 数据长度不一致
    InconsistentDataLength = 0x0008,
    /// 未知错误
    UnknownError = 0xFFFF,
}

// ===================== 邮箱类型 =====================

/// 邮箱类型
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MailboxType {
    /// 错误邮箱
    ErrorMailbox = 0x00,
    /// ADS over EtherCAT
    ADSOverEtherCAT = 0x01,
    /// Ethernet over EtherCAT
    EthernetOverEtherCAT = 0x02,
    /// CANopen over EtherCAT
    CANopenOverEtherCAT = 0x03,
    /// File over EtherCAT
    FileOverEtherCAT = 0x04,
    /// Servo over EtherCAT
    ServoOverEtherCAT = 0x05,
    /// Vendor over EtherCAT
    VendorOverEtherCAT = 0x0F,
}

// ===================== CoE 对象访问权限 =====================

/// CoE 对象访问权限标志位 (ETG1000.6 Object Access)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CoEObjectAccess(pub u16);

impl CoEObjectAccess {
    /// 无权限
    pub const NONE: Self = Self(0x00);
    /// Pre-Operational 状态下的读访问
    pub const READ_PRE_OP: Self = Self(0x01);
    /// Safe-Operational 状态下的读访问
    pub const READ_SAFE_OP: Self = Self(0x02);
    /// Operational 状态下的读访问
    pub const READ_OP: Self = Self(0x04);
    /// Pre-Operational 状态下的写访问
    pub const WRITE_PRE_OP: Self = Self(0x08);
    /// Safe-Operational 状态下的写访问
    pub const WRITE_SAFE_OP: Self = Self(0x10);
    /// Operational 状态下的写访问
    pub const WRITE_OP: Self = Self(0x20);
    /// 所有读权限
    pub const READ_ANY: Self = Self(0x07);
    /// 所有写权限
    pub const WRITE_ANY: Self = Self(0x38);
    /// 所有读写权限
    pub const READ_WRITE_ALL: Self = Self(0x3F);

    /// 检查是否包含指定标志
    pub fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// 合并标志
    pub fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

// ===================== SDO 中止码 =====================

/// SDO 中止码
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SDOError {
    /// 无错误
    NoError = 0x00000000,
    /// 切换位未变化
    ToggleBitNotChanged = 0x05030000,
    /// SDO 协议超时
    SDOProtocolTimeout = 0x05040000,
    /// 无效的命令指示符
    InvalidCommandSpecifier = 0x05040001,
    /// 内存不足
    OutOfMemory = 0x05040005,
    /// 不支持的访问
    UnsupportedAccess = 0x06010000,
    /// 尝试读写只读对象
    ReadWriteOnlyError = 0x06010001,
    /// 尝试写只读对象
    WriteReadOnlyError = 0x06010002,
    /// 子索引写错误
    SubindexWriteError = 0x06010003,
    /// 不支持完整访问
    CompleteAccessNotSupported = 0x06010004,
    /// 对象长度超出
    ObjectLengthExceeded = 0x06010005,
    /// 对象已映射到 RxPDO
    ObjectMappedToRxPDO = 0x06010006,
    /// 对象不存在
    ObjectDoesNotExist = 0x06020000,
    /// 不能映射到 PDO
    CannotBeMappedToPDO = 0x06040041,
    /// 超出 PDO 长度
    ExceedsPDOLength = 0x06040042,
    /// 参数不兼容
    ParameterIncompatibility = 0x06040043,
    /// 内部不兼容
    InternalIncompatibility = 0x06040047,
    /// 硬件访问错误
    HardwareAccessError = 0x06060000,
    /// 数据类型不匹配
    DataTypeMismatch = 0x06070010,
    /// 数据类型值过高
    DataTypeTooHigh = 0x06070012,
    /// 数据类型值过低
    DataTypeTooLow = 0x06070013,
    /// 子索引不存在
    SubindexDoesNotExist = 0x06090011,
    /// 值超出范围
    ValueRangeExceeded = 0x06090030,
    /// 值过高
    ValueTooHigh = 0x06090031,
    /// 值过低
    ValueTooLow = 0x06090032,
    /// 配置的模块列表与检测到的模块列表不匹配
    ModuleIdentListMismatch = 0x06090033,
    /// 最大值小于最小值
    MaxLessThanMin = 0x06090036,
    /// 一般错误
    GeneralError = 0x08000000,
    /// 数据传输错误
    DataTransferError = 0x08000020,
    /// 本地控制错误
    LocalControlError = 0x08000021,
    /// 设备状态错误
    DeviceStateError = 0x08000022,
    /// 字典错误
    DictionaryError = 0x08000023,
    /// 未知错误
    UnknownError = 0xFFFFFFFF,
}

impl SDOError {
    /// 从 u32 值创建 SDOError，未知值返回 UnknownError
    pub fn from_u32(val: u32) -> Self {
        match val {
            0x00000000 => Self::NoError,
            0x05030000 => Self::ToggleBitNotChanged,
            0x05040000 => Self::SDOProtocolTimeout,
            0x05040001 => Self::InvalidCommandSpecifier,
            0x05040005 => Self::OutOfMemory,
            0x06010000 => Self::UnsupportedAccess,
            0x06010001 => Self::ReadWriteOnlyError,
            0x06010002 => Self::WriteReadOnlyError,
            0x06010003 => Self::SubindexWriteError,
            0x06010004 => Self::CompleteAccessNotSupported,
            0x06010005 => Self::ObjectLengthExceeded,
            0x06010006 => Self::ObjectMappedToRxPDO,
            0x06020000 => Self::ObjectDoesNotExist,
            0x06040041 => Self::CannotBeMappedToPDO,
            0x06040042 => Self::ExceedsPDOLength,
            0x06040043 => Self::ParameterIncompatibility,
            0x06040047 => Self::InternalIncompatibility,
            0x06060000 => Self::HardwareAccessError,
            0x06070010 => Self::DataTypeMismatch,
            0x06070012 => Self::DataTypeTooHigh,
            0x06070013 => Self::DataTypeTooLow,
            0x06090011 => Self::SubindexDoesNotExist,
            0x06090030 => Self::ValueRangeExceeded,
            0x06090031 => Self::ValueTooHigh,
            0x06090032 => Self::ValueTooLow,
            0x06090033 => Self::ModuleIdentListMismatch,
            0x06090036 => Self::MaxLessThanMin,
            0x08000000 => Self::GeneralError,
            0x08000020 => Self::DataTransferError,
            0x08000021 => Self::LocalControlError,
            0x08000022 => Self::DeviceStateError,
            0x08000023 => Self::DictionaryError,
            _ => Self::UnknownError,
        }
    }
}

// ===================== SoE 错误码 =====================

/// SoE 错误码
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SoEError {
    /// 无错误
    NoError = 0x0000,
    /// 无 IDN
    NoIDN = 0x1001,
    /// 无效的元素1访问
    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,
    /// 无效的操作数据, 配置的 IDN 不支持
    InvalidOperationDataConfiguredIDNNotSupported = 0x7008,
    /// 操作数据受密码写保护
    OperationDataWriteProtectedByPassword = 0x7009,
    /// 操作数据周期性写保护
    OperationDataCyclicallyWriteProtected = 0x700A,
    /// 无效的间接寻址
    InvalidIndirectAddressing = 0x700B,
    /// 操作数据受设置写保护
    OperationDataWriteProtectedBySettings = 0x700C,
    /// 保留 (0x700D)
    Reserved700D = 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,
}

// ===================== 通信类型 =====================

/// 通信类型枚举 (用于自适应超时)
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcCommType {
    /// 邮箱发送
    MailboxTx = 0,
    /// 邮箱接收
    MailboxRx = 1,
    /// SDO 读取
    SdoRead = 2,
    /// SDO 写入
    SdoWrite = 3,
    /// PDO 传输
    Pdo = 4,
    /// 寄存器访问
    Register = 5,
    /// EEPROM 访问
    Eeprom = 6,
    /// DC 同步
    Dc = 7,
    /// 枚举值数量
    Count = 8,
}

// ===================== 物理端口类型 =====================

/// 物理端口类型 (ESC Port Physical Type)
/// 每个端口用2位编码, 从物理类型寄存器中提取
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcPortType {
    /// 未使用/未连接
    NotUsed = 0,
    /// MII (Media Independent Interface)
    MII = 1,
    /// EBUS (E-Bus)
    EBUS = 2,
    /// EBUS 增强型
    EBUSEnhanced = 3,
}

impl fmt::Display for EcPortType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::NotUsed => "未使用",
            Self::MII => "MII",
            Self::EBUS => "EBUS",
            Self::EBUSEnhanced => "EBUS+",
        };
        write!(f, "{}", desc)
    }
}

// ===================== 拓扑类型 =====================

/// 从站拓扑类型
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcTopologyType {
    /// 无链接
    NoLink = 0,
    /// 端点 - 只有1个端口活动
    EndPoint = 1,
    /// 中间节点 - 2个端口活动, 线性拓扑
    Line = 2,
    /// 分支点 - 3个端口活动
    Fork = 3,
    /// 交叉点 - 4个端口活动
    Cross = 4,
}

impl fmt::Display for EcTopologyType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::NoLink => "无链接 (No Link)",
            Self::EndPoint => "端点 (End Point)",
            Self::Line => "中间节点 (Line)",
            Self::Fork => "分支点 (Fork)",
            Self::Cross => "交叉点 (Cross)",
        };
        write!(f, "{}", desc)
    }
}

// ===================== PDI 类型 =====================

/// PDI (Process Data Interface) 类型
/// 定义从站的物理数据接口类型
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcPdiType {
    /// 接口未激活
    None = 0x00,
    /// 4个数字输入
    DigitalInput4 = 0x01,
    /// 4个数字输出
    DigitalOutput4 = 0x02,
    /// 2个数字输入 + 2个数字输出
    DigitalIO2x2 = 0x03,
    /// 数字I/O
    DigitalIO = 0x04,
    /// SPI从站
    SPISlave = 0x05,
    /// 过载保护输出
    OverloadOutput = 0x06,
    /// ESC同步管理器
    EscSyncManager = 0x07,
    /// 微控制器异步16位
    UCAsync16 = 0x08,
    /// 微控制器异步8位
    UCAsync8 = 0x09,
    /// 微控制器同步16位
    UCSync16 = 0x0A,
    /// 微控制器同步8位
    UCSync8 = 0x0B,
    /// 32个数字输入/输出
    DigitalIO32 = 0x10,
    /// 24个数字输入 + 8个数字输出
    DigitalIO24x8 = 0x11,
    /// 16个数字输入 + 16个数字输出
    DigitalIO16x16 = 0x12,
    /// 8个数字输入 + 24个数字输出
    DigitalIO8x24 = 0x13,
    /// On-chip bus (如 Xilinx LocalLink)
    OnChipBus = 0x80,
    /// 未知类型
    Unknown = 0xFF,
}

impl fmt::Display for EcPdiType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::None => "无PDI (Interface deactivated)",
            Self::DigitalInput4 => "4个数字输入",
            Self::DigitalOutput4 => "4个数字输出",
            Self::DigitalIO2x2 => "2个数字输入 + 2个数字输出",
            Self::DigitalIO => "数字I/O",
            Self::SPISlave => "SPI从站",
            Self::OverloadOutput => "过载保护输出",
            Self::EscSyncManager => "ESC同步管理器",
            Self::UCAsync16 => "uC async. 16bit",
            Self::UCAsync8 => "uC async. 8bit",
            Self::UCSync16 => "uC sync. 16bit",
            Self::UCSync8 => "uC sync. 8bit",
            Self::DigitalIO32 => "32个数字输入/输出",
            Self::DigitalIO24x8 => "24个数字输入 + 8个数字输出",
            Self::DigitalIO16x16 => "16个数字输入 + 16个数字输出",
            Self::DigitalIO8x24 => "8个数字输入 + 24个数字输出",
            Self::OnChipBus => "On-chip bus",
            Self::Unknown => "未知类型",
        };
        write!(f, "{}", desc)
    }
}

// ===================== 设备类型 =====================

/// 从站设备类型 (Dtype)
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcDeviceType {
    /// 未定义
    Undefined = 0,
    /// 静态设备 (无IO映射, 如EK1100耦合器)
    Static = 1,
    /// 输入设备 (无邮箱)
    InputNoMailbox = 2,
    /// 输出设备 (无邮箱)
    OutputNoMailbox = 3,
    /// 输入设备 (有邮箱)
    InputWithMailbox = 4,
    /// 输出设备 (有邮箱)
    OutputWithMailbox = 5,
    /// 输入输出设备 (无邮箱)
    IONoMailbox = 6,
    /// 输入输出设备 (有邮箱)
    IOWithMailbox = 7,
}

impl fmt::Display for EcDeviceType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::Undefined => "未定义",
            Self::Static => "静态设备(无IO映射)",
            Self::InputNoMailbox => "输入设备(无邮箱)",
            Self::OutputNoMailbox => "输出设备(无邮箱)",
            Self::InputWithMailbox => "输入设备(有邮箱)",
            Self::OutputWithMailbox => "输出设备(有邮箱)",
            Self::IONoMailbox => "输入输出设备(无邮箱)",
            Self::IOWithMailbox => "输入输出设备(有邮箱)",
        };
        write!(f, "{}", desc)
    }
}

// ===================== SyncManager 类型 =====================

/// SyncManager 类型
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcSyncManagerType {
    /// 未使用
    NotUsed = 0,
    /// 邮箱输出 (主站->从站)
    MailboxOut = 1,
    /// 邮箱输入 (从站->主站)
    MailboxIn = 2,
    /// 过程数据输出 (RxPDO, 主站->从站)
    ProcessDataOut = 3,
    /// 过程数据输入 (TxPDO, 从站->主站)
    ProcessDataIn = 4,
}

impl fmt::Display for EcSyncManagerType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::NotUsed => "未使用",
            Self::MailboxOut => "邮箱输出",
            Self::MailboxIn => "邮箱输入",
            Self::ProcessDataOut => "过程数据输出",
            Self::ProcessDataIn => "过程数据输入",
        };
        write!(f, "{}", desc)
    }
}

// ===================== FMMU 类型 =====================

/// FMMU 类型
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcFmmuType {
    /// 未使用
    NotUsed = 0,
    /// 输出 (逻辑->物理)
    Output = 1,
    /// 输入 (物理->逻辑)
    Input = 2,
    /// 同步管理器状态
    SyncManagerStatus = 3,
}

impl fmt::Display for EcFmmuType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::NotUsed => "未使用",
            Self::Output => "输出",
            Self::Input => "输入",
            Self::SyncManagerStatus => "同步管理器状态",
        };
        write!(f, "{}", desc)
    }
}

// ===================== CoE 详情标志位 =====================

/// CoE 详情标志位
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EcCoEDetails(pub u8);

impl EcCoEDetails {
    /// 无
    pub const NONE: Self = Self(0x00);
    /// 支持 SDO
    pub const SDO: Self = Self(0x01);
    /// 支持 SDO Info
    pub const SDO_INFO: Self = Self(0x02);
    /// 支持 PDO Assign
    pub const PDO_ASSIGN: Self = Self(0x04);
    /// 支持 PDO Config
    pub const PDO_CONFIG: Self = Self(0x08);
    /// 支持 Startup
    pub const STARTUP: Self = Self(0x10);
    /// 支持 Complete Access
    pub const COMPLETE_ACCESS: Self = Self(0x20);

    /// 检查是否包含指定标志
    pub fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// 合并标志
    pub fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

// ===================== EoE 详情标志位 =====================

/// EoE 详情标志位
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EcEoEDetails(pub u8);

impl EcEoEDetails {
    /// 无
    pub const NONE: Self = Self(0x00);
    /// 支持发送帧
    pub const SEND_FRAME: Self = Self(0x01);
    /// 支持接收帧
    pub const RECEIVE_FRAME: Self = Self(0x02);
    /// 支持设置 IP 参数
    pub const SET_IP_PARAM: Self = Self(0x04);
    /// 支持获取 IP 参数
    pub const GET_IP_PARAM: Self = Self(0x08);

    /// 检查是否包含指定标志
    pub fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    /// 合并标志
    pub fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }
}

// ===================== 状态格式化 =====================

/// EtherCAT 状态格式化选项
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EcStateFormat {
    /// 短格式 (如 "OP")
    Short,
    /// 长格式 (如 "Operational")
    Long,
    /// 带十六进制的格式 (如 "OP (0x08)")
    WithHex,
}

/// 格式化 EtherCAT 状态
pub fn format_ec_state(state: u8, format: EcStateFormat) -> String {
    let (short, long) = match state & 0x0F {
        0x01 => ("INIT", "Init"),
        0x02 => ("PREOP", "Pre-Operational"),
        0x03 => ("BOOT", "Bootstrap"),
        0x04 => ("SAFEOP", "Safe-Operational"),
        0x08 => ("OP", "Operational"),
        _ => ("???", "Unknown"),
    };
    let err = if state & 0x10 != 0 { "+ERR" } else { "" };
    match format {
        EcStateFormat::Short => format!("{}{}", short, err),
        EcStateFormat::Long => format!("{}{}", long, err),
        EcStateFormat::WithHex => format!("{}{} (0x{:02X})", short, err, state),
    }
}

// ===================== DC 同步模式 =====================

/// DC 同步模式
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DcSyncMode {
    /// 自由运行模式
    FreeRun = 0,
    /// SM 同步模式
    SmSynchron = 1,
    /// DC 同步模式 - 仅 SYNC0
    DcSynchron = 2,
    /// DC 同步模式 - SYNC0 + SYNC1
    DcSynchron01 = 3,
}

// ===================== 启动转换 =====================

/// 启动转换
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartupTransition {
    /// Init -> PreOp (对应 C# IP=0, C EC_TRANS_IP=0)
    IP = 0,
    /// PreOp -> SafeOp (对应 C# PS=1, C EC_TRANS_PS=1)
    PS = 1,
    /// SafeOp -> OP (对应 C# SO=2, C EC_TRANS_SO=2)
    SO = 2,
    /// OP -> SafeOp (对应 C# OS=3, C EC_TRANS_OS=3)
    OS = 3,
    /// SafeOp -> PreOp (对应 C# SP=4, C EC_TRANS_SP=4)
    SP = 4,
    /// PreOp -> Init (对应 C# PI=5, C EC_TRANS_PI=5)
    PI = 5,
}

// ===================== 启动写入时序 =====================

/// 启动写入时序
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartupWriteTiming {
    /// 转换前写入
    BeforeTransition = 0,
    /// 转换后写入
    AfterTransition = 1,
}

// ===================== ESM 超时常量 =====================

/// ETG.1020 ESM 状态转换超时配置 (毫秒)
pub mod esm_timeouts {
    /// Init -> PreOp 默认超时 (ms) - ETG.1020 建议 3000ms
    pub const INIT_TO_PRE_OP: i32 = 3000;
    /// PreOp -> SafeOp 默认超时 (ms) - ETG.1020 建议 10000ms
    pub const PRE_OP_TO_SAFE_OP: i32 = 10000;
    /// SafeOp -> OP 默认超时 (ms) - ETG.1020 建议 3000ms
    pub const SAFE_OP_TO_OP: i32 = 3000;
    /// OP -> SafeOp 默认超时 (ms) - ETG.1020 建议 200ms
    pub const OP_TO_SAFE_OP: i32 = 200;
    /// SafeOp -> PreOp 默认超时 (ms) - ETG.1020 建议 200ms
    pub const SAFE_OP_TO_PRE_OP: i32 = 200;
    /// PreOp -> Init 默认超时 (ms) - ETG.1020 建议 200ms
    pub const PRE_OP_TO_INIT: i32 = 200;
    /// 任意状态 -> Boot 默认超时 (ms) - ETG.1020 建议 3000ms
    pub const TO_BOOT: i32 = 3000;
    /// Boot -> Init 默认超时 (ms) - ETG.1020 建议 3000ms
    pub const BOOT_TO_INIT: i32 = 3000;
    /// SDO 通信超时 (ms)
    pub const SDO_TIMEOUT: i32 = 3000;
    /// 邮箱通信超时 (ms)
    pub const MAILBOX_TIMEOUT: i32 = 5000;
    /// 状态切换后稳定等待时间 (ms)
    pub const STATE_STABILIZE_DELAY: i32 = 100;

    /// 根据当前状态和目标状态获取超时值
    pub fn get_transition_timeout(current: u8, target: u8) -> i32 {
        match (current, target) {
            (0x01, 0x02) => INIT_TO_PRE_OP,       // Init -> PreOp
            (0x02, 0x04) => PRE_OP_TO_SAFE_OP,    // PreOp -> SafeOp
            (0x04, 0x08) => SAFE_OP_TO_OP,        // SafeOp -> OP
            (0x08, 0x04) => OP_TO_SAFE_OP,        // OP -> SafeOp
            (0x04, 0x02) => SAFE_OP_TO_PRE_OP,    // SafeOp -> PreOp
            (0x02, 0x01) => PRE_OP_TO_INIT,       // PreOp -> Init
            (_, 0x03) => TO_BOOT,                  // 任意 -> Boot
            (0x03, 0x01) => BOOT_TO_INIT,          // Boot -> Init
            _ => 3000,                             // 默认超时
        }
    }
}

// ===================== CiA 402 驱动器状态 =====================

/// CiA 402 驱动器状态机状态
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateCiA402 {
    /// 初始化中
    NotReadyToSwitchOn = 0,
    /// 驱动禁用
    SwitchOnDisabled = 1,
    /// 准备就绪
    ReadyToSwitchOn = 2,
    /// 已开启
    SwitchedOn = 3,
    /// 运行使能
    OperationEnabled = 4,
    /// 快速停止
    QuickStopActive = 5,
    /// 故障反应中
    FaultReactionActive = 6,
    /// 故障
    Fault = 7,
    /// 未知状态
    Unknown = 99,
}

/// CiA 402 操作模式
#[repr(i8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModeCiA402 {
    /// 轮廓位置模式 (Profile Position)
    PP = 1,
    /// 速度模式 (Velocity)
    VL = 2,
    /// 轮廓速度模式 (Profile Velocity)
    PV = 3,
    /// 轮廓转矩模式 (Profile Torque)
    PT = 4,
    /// 回零模式 (Homing)
    HM = 6,
    /// 插补位置模式 (Interpolated Position)
    IP = 7,
    /// 周期同步位置模式
    CSP = 8,
    /// 周期同步速度模式
    CSV = 9,
    /// 周期同步转矩模式
    CST = 10,
    /// 周期同步转矩加速度模式
    CSTCA = 11,
}

// ===================== 日志类别 =====================

/// 日志类别 - 与DLL中的LogCategory对应
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogCategory {
    /// 错误 - 系统错误和异常
    Error = 0,
    /// 警告 - 潜在问题
    Warning = 1,
    /// 消息 - 一般信息
    Message = 2,
    /// Mailbox - CoE/SoE/FoE/EoE通信
    Mailbox = 3,
    /// PDO - 过程数据对象交换
    PDO = 4,
    /// 调试 - 详细调试信息
    Debug = 5,
    /// 本地 - 控制台输出捕获
    Local = 6,
}

// ===================== 授权状态 =====================

/// 授权状态
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LicenseStatus {
    /// 未验证
    NotVerified = 0,
    /// 验证中
    Verifying = 1,
    /// 已验证
    Verified = 2,
    /// 验证失败
    Failed = 3,
    /// 已过期
    Expired = 4,
    /// 机器ID不匹配
    MachineIdMismatch = 5,
}
