| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015 |
- using CanTest;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace CCDCount.DLL.CanBus
- {
- /// <summary>
- /// CANopen从站设备 - 基于Nameless.eds文件实现
- /// 支持4个RPDO和4个TPDO,符合CiA DS301标准
- /// </summary>
- public class CanOpenSlaveDevice : IDisposable
- {
- #region 私有字段
-
- private CanOpenManager m_canManager;
- private byte m_nodeId = 1; // 默认节点ID
- private NmtState m_currentState = NmtState.Initializing;
-
- // PDO配置 - 根据EDS文件定义
- private PdoConfig[] m_rpdoConfigs = new PdoConfig[4]; // 接收PDO
- private PdoConfig[] m_tpdoConfigs = new PdoConfig[4]; // 发送PDO
-
- // PDO映射对象
- private PdoMapping[,] m_rpdoMappings = new PdoMapping[4, 4]; // RPDO映射表
- private PdoMapping[,] m_tpdoMappings = new PdoMapping[4, 4]; // TPDO映射表
-
- // 应用数据缓冲区 (用于PDO数据交换)
- private Dictionary<ushort, object> m_objectDictionary = new Dictionary<ushort, object>();
-
- // 心跳参数
- private ushort m_producerHeartbeatTime = 0; // 心跳时间(ms),0表示禁用
- private Timer m_heartbeatTimer;
-
- // SYNC参数
- private bool m_syncEnabled = false;
- private byte m_syncCounter = 0;
-
- // 线程控制
- private CancellationTokenSource m_cancellationTokenSource;
- private Task m_receiveTask;
- private bool m_isRunning = false;
-
- #endregion
-
- #region 事件定义
-
- /// <summary>
- /// RPDO接收事件
- /// </summary>
- public event Action<byte, byte, byte[]> OnRpdoReceived;
-
- /// <summary>
- /// NMT状态改变事件
- /// </summary>
- public event Action<NmtState, NmtState> OnNmtStateChanged;
-
- /// <summary>
- /// SDO读取请求事件
- /// </summary>
- public event Action<byte, ushort, byte> OnSdoReadRequest;
-
- /// <summary>
- /// SDO写入请求事件
- /// </summary>
- public event Action<byte, ushort, byte, uint> OnSdoWriteRequest;
-
- #endregion
-
- #region 构造函数
-
- /// <summary>
- /// 构造函数
- /// </summary>
- /// <param name="nodeId">节点ID(1-127)</param>
- /// <param name="deviceType">设备类型</param>
- /// <param name="deviceIndex">设备索引</param>
- /// <param name="canIndex">CAN通道索引</param>
- public CanOpenSlaveDevice(byte nodeId = 1, UInt32 deviceType = 4, UInt32 deviceIndex = 0, UInt32 canIndex = 0)
- {
- if (nodeId < 1 || nodeId > 127)
- throw new ArgumentException("节点ID必须在1-127之间");
-
- m_nodeId = nodeId;
- m_canManager = new CanOpenManager(deviceType, deviceIndex, canIndex);
-
- InitializePdoConfigs();
- InitializeObjectDictionary();
- }
-
- #endregion
-
- #region 初始化方法
-
- /// <summary>
- /// 初始化PDO配置 - 根据EDS文件
- /// </summary>
- private void InitializePdoConfigs()
- {
- // 初始化RPDO配置 (1400-1403)
- for (int i = 0; i < 4; i++)
- {
- m_rpdoConfigs[i] = new PdoConfig
- {
- CobId = GetRpdoCobId((byte)(i + 1), m_nodeId),
- TransmissionType = 0xFF, // 事件驱动
- Enabled = true
- };
-
- // 初始化映射表为空
- for (int j = 0; j < 4; j++)
- {
- m_rpdoMappings[i, j] = new PdoMapping
- {
- Index = 0,
- SubIndex = 0,
- BitLength = 0
- };
- }
- }
-
- // 初始化TPDO配置 (1800-1803)
- for (int i = 0; i < 4; i++)
- {
- m_tpdoConfigs[i] = new PdoConfig
- {
- CobId = GetTpdoCobId((byte)(i + 1), m_nodeId),
- TransmissionType = 0xFF, // 事件驱动
- Enabled = true
- };
-
- // 初始化映射表为空
- for (int j = 0; j < 4; j++)
- {
- m_tpdoMappings[i, j] = new PdoMapping
- {
- Index = 0,
- SubIndex = 0,
- BitLength = 0
- };
- }
- }
- }
-
- /// <summary>
- /// 初始化对象字典 - 根据EDS文件定义
- /// </summary>
- private void InitializeObjectDictionary()
- {
- // 1000h - Device type
- m_objectDictionary[(ushort)0x1000] = (uint)0x00000000; // 默认值
-
- // 1001h - Error register
- m_objectDictionary[(ushort)0x1001] = (byte)0x00;
-
- // 1017h - Producer Heartbeat Time (心跳时间)
- // 根据CANopen标准,此对象用于配置心跳发送间隔
- m_objectDictionary[(ushort)0x1017] = (ushort)1000; // 默认1000ms
-
- // 1018h - Identity Object
- m_objectDictionary[(ushort)0x1018] = new IdentityObject
- {
- VendorId = 0x0000000D, // HanLin
- ProductCode = 0x00000001, // CCDCountCanOpenSlave
- RevisionNumber = 0x00010001
- };
-
- // 1800-1803h - TPDO communication parameters
- for (int i = 0; i < 4; i++)
- {
- m_objectDictionary[(ushort)(0x1800 + i)] = new TpdoCommParam
- {
- CobId = GetTpdoCobId((byte)(i + 1), m_nodeId),
- TransmissionType = 0xFF
- };
- }
-
- // 1A00-1A03h - TPDO mapping parameters
- for (int i = 0; i < 4; i++)
- {
- m_objectDictionary[(ushort)(0x1A00 + i)] = new PdoMappingParam
- {
- NumberOfEntries = 4,
- Mappings = new uint[4]
- };
- }
-
- // 1400-1403h - RPDO communication parameters
- for (int i = 0; i < 4; i++)
- {
- m_objectDictionary[(ushort)(0x1400 + i)] = new RpdoCommParam
- {
- CobId = GetRpdoCobId((byte)(i + 1), m_nodeId),
- TransmissionType = 0xFF
- };
- }
-
- // 1600-1603h - RPDO mapping parameters
- for (int i = 0; i < 4; i++)
- {
- m_objectDictionary[(ushort)(0x1600 + i)] = new PdoMappingParam
- {
- NumberOfEntries = 4,
- Mappings = new uint[4]
- };
- }
- }
-
- #endregion
-
- #region 启动和停止
-
- /// <summary>
- /// 启动从站设备
- /// </summary>
- /// <param name="baudRate">波特率</param>
- /// <returns>是否成功</returns>
- public bool Start(CanBaudRate baudRate = CanBaudRate.BaudRate_1M)
- {
- if (m_isRunning)
- {
- Console.WriteLine("从站设备已在运行");
- return true;
- }
-
- // 初始化CAN
- if (!m_canManager.Initialize(baudRate))
- {
- Console.WriteLine("CAN初始化失败");
- return false;
- }
-
- m_isRunning = true;
- m_currentState = NmtState.Initializing;
-
- // 默认配置心跳为1000ms
- ConfigureHeartbeat(1000);
-
- // 发送无错误紧急报文,表明设备正常
- SendNoErrorEmcy();
-
- // 等待主站发送NMT命令来控制状态转换
- Console.WriteLine($"NMT: 节点{m_nodeId}已初始化,等待主站命令...");
-
- // 启动接收线程
- m_cancellationTokenSource = new CancellationTokenSource();
- m_receiveTask = Task.Run(() => ReceiveLoop(m_cancellationTokenSource.Token));
-
- Console.WriteLine($"CANopen从站启动成功 - 节点ID: {m_nodeId}");
- return true;
- }
-
- /// <summary>
- /// 停止从站设备
- /// </summary>
- public void Stop()
- {
- if (!m_isRunning)
- return;
-
- m_isRunning = false;
-
- // 停止接收线程
- m_cancellationTokenSource?.Cancel();
- m_receiveTask?.Wait(1000);
- m_receiveTask?.Dispose();
-
- // 停止心跳定时器
- m_heartbeatTimer?.Dispose();
-
- // 关闭CAN
- m_canManager.Close();
-
- m_currentState = NmtState.Stopped;
- Console.WriteLine("CANopen从站已停止");
- }
-
- #endregion
-
- #region 接收处理循环
-
- /// <summary>
- /// CAN帧接收循环
- /// </summary>
- private void ReceiveLoop(CancellationToken cancellationToken)
- {
- while (!cancellationToken.IsCancellationRequested)
- {
- try
- {
- var frames = m_canManager.ReceiveCanFrames(50);
-
- foreach (var frame in frames)
- {
- ProcessCanFrame(frame);
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"接收错误: {ex.Message}");
- }
- Thread.Sleep(1); // 避免CPU占用过高
- }
- }
-
- /// <summary>
- /// 处理接收到的CAN帧
- /// </summary>
- private void ProcessCanFrame(CanOpenFrame frame)
- {
- // 记录所有接收到的帧(用于调试)
- Console.WriteLine($"[接收详细] COB-ID: 0x{frame.CobId:X3}, Len: {frame.DataLength}, Data: {BitConverter.ToString(frame.Data, 0, frame.DataLength).Replace("-", " ")}");
-
- // 检查是否是NMT命令 (COB-ID = 0x000)
- if (frame.CobId == (uint)0x000 && frame.DataLength >= 2)
- {
- Console.WriteLine($"[NMT命令] COB-ID: 0x{frame.CobId:X3}, Data: {BitConverter.ToString(frame.Data, 0, frame.DataLength).Replace("-", " ")}");
- ProcessNmtCommand(frame.Data);
- return;
- }
-
- // 检查是否是SYNC (COB-ID = 0x080)
- if (frame.CobId == (uint)0x080)
- {
- Console.WriteLine($"[SYNC] COB-ID: 0x{frame.CobId:X3}");
- ProcessSync(frame.Data);
- return;
- }
-
- // 检查是否是SDO请求 (COB-ID = 0x600 + nodeId)
- uint sdoRequestCobId = (uint)0x600 + m_nodeId;
- if (frame.CobId == sdoRequestCobId)
- {
- Console.WriteLine($"[SDO请求] COB-ID: 0x{frame.CobId:X3}, Data: {BitConverter.ToString(frame.Data, 0, frame.DataLength).Replace("-", " ")}");
- ProcessSdoRequest(frame.Data);
- return;
- }
-
- // 检查是否是RPDO
- for (int i = 0; i < 4; i++)
- {
- if (frame.CobId == m_rpdoConfigs[i].CobId && m_rpdoConfigs[i].Enabled)
- {
- Console.WriteLine($"[RPDO{i+1}] COB-ID: 0x{frame.CobId:X3}, Data: {BitConverter.ToString(frame.Data, 0, frame.DataLength).Replace("-", " ")}");
- ProcessRpdo((byte)(i + 1), frame.Data, frame.DataLength);
- return;
- }
- }
-
- // 其他未知帧
- Console.WriteLine($"[未知帧] COB-ID: 0x{frame.CobId:X3}, Len: {frame.DataLength}, Data: {BitConverter.ToString(frame.Data, 0, frame.DataLength).Replace("-", " ")}");
- }
-
- #endregion
-
- #region NMT处理
-
- /// <summary>
- /// 处理NMT命令
- /// </summary>
- private void ProcessNmtCommand(byte[] data)
- {
- byte commandSpecifier = data[0];
- byte nodeId = data[1];
-
- // 检查是否是广播命令或针对本节点的命令
- if (nodeId != 0 && nodeId != m_nodeId)
- return;
-
- NmtState oldState = m_currentState;
-
- Console.WriteLine($"[NMT详细] 收到命令: 0x{commandSpecifier:X2}, 目标节点: {nodeId}, 当前状态: {m_currentState}");
-
- switch (commandSpecifier)
- {
- case 0x01: // 启动节点
- Console.WriteLine($"[NMT详细] 执行启动节点命令");
- m_currentState = NmtState.Operational;
- Console.WriteLine($"NMT: 节点{m_nodeId}进入运行状态");
- break;
-
- case 0x02: // 停止节点
- Console.WriteLine($"[NMT详细] 执行停止节点命令");
- m_currentState = NmtState.Stopped;
- Console.WriteLine($"NMT: 节点{m_nodeId}进入停止状态");
- break;
-
- case 0x80: // 进入预操作状态
- Console.WriteLine($"[NMT详细] 执行进入预操作状态命令");
- m_currentState = NmtState.PreOperational;
- Console.WriteLine($"NMT: 节点{m_nodeId}进入预操作状态");
- break;
-
- case 0x81: // 重置节点
- Console.WriteLine($"[NMT详细] 执行重置节点命令 - 开始初始化流程");
- // 执行节点重置逻辑
- m_currentState = NmtState.Initializing;
-
- // 打印当前对象字典状态(用于调试)
- Console.WriteLine($"[NMT调试] 当前对象字典关键参数:");
- if (m_objectDictionary.ContainsKey((ushort)0x1000))
- Console.WriteLine($" - 设备类型(0x1000): {m_objectDictionary[(ushort)0x1000]}");
- if (m_objectDictionary.ContainsKey((ushort)0x1001))
- Console.WriteLine($" - 错误寄存器(0x1001): {m_objectDictionary[(ushort)0x1001]}");
- if (m_objectDictionary.ContainsKey((ushort)0x1017))
- Console.WriteLine($" - 心跳时间(0x1017): {m_objectDictionary[(ushort)0x1017]}ms");
- if (m_objectDictionary.ContainsKey((ushort)0x1018))
- {
- var identity = m_objectDictionary[(ushort)0x1018] as IdentityObject;
- if (identity != null)
- Console.WriteLine($" - 厂商ID(0x1018.1): 0x{identity.VendorId:X4}");
- }
-
- // 短暂延迟后自动进入预操作状态(模拟初始化过程)
- Task.Delay(50).ContinueWith(_ =>
- {
- // 立即发送一次心跳,确认状态转换
- SendHeartbeat();
- m_currentState = NmtState.PreOperational;
- Console.WriteLine($"NMT: 节点{m_nodeId}初始化完成,进入预操作状态");
-
-
- OnNmtStateChanged?.Invoke(oldState, m_currentState);
- });
- return; // 提前返回,等待异步完成
-
- case 0x82: // 重置通信
- Console.WriteLine($"[NMT详细] 执行重置通信命令");
- m_currentState = NmtState.PreOperational;
- Console.WriteLine($"NMT: 节点{m_nodeId}通信重置");
- // TODO: 执行通信重置逻辑
- break;
-
- default:
- Console.WriteLine($"[NMT详细] 未知命令: 0x{commandSpecifier:X2}");
- break;
- }
-
- // 触发状态改变事件
- if (oldState != m_currentState)
- {
- Console.WriteLine($"[NMT详细] 状态改变: {oldState} → {m_currentState}");
- OnNmtStateChanged?.Invoke(oldState, m_currentState);
- }
- else
- {
- Console.WriteLine($"[NMT详细] 状态未改变: {oldState}");
- }
- }
-
- #endregion
-
- #region SYNC处理
-
- /// <summary>
- /// 处理SYNC帧
- /// </summary>
- private void ProcessSync(byte[] data)
- {
- if (data.Length > 0)
- {
- m_syncCounter = data[0];
- }
-
- // 如果TPDO配置为同步触发,则发送
- for (int i = 0; i < 4; i++)
- {
- if (m_tpdoConfigs[i].Enabled &&
- m_tpdoConfigs[i].TransmissionType >= 1 &&
- m_tpdoConfigs[i].TransmissionType <= 240)
- {
- SendTpdo((byte)(i + 1));
- }
- }
- }
-
- #endregion
-
- #region SDO处理
-
- /// <summary>
- /// 处理SDO请求
- /// </summary>
- private void ProcessSdoRequest(byte[] data)
- {
- if (data.Length < 8)
- return;
-
- byte cs = (byte)(data[0] >> 5); // 命令 specifier
- ushort index = (ushort)(data[1] | (data[2] << 8));
- byte subIndex = data[3];
-
- switch (cs)
- {
- case 2: // SDO上传请求 (读)
- HandleSdoUpload(index, subIndex);
- break;
-
- case 1: // SDO下载请求 (写)
- HandleSdoDownload(index, subIndex, data);
- break;
-
- default:
- Console.WriteLine($"未支持的SDO命令: CS={cs}");
- break;
- }
- }
-
- /// <summary>
- /// 处理SDO上传 (读对象字典)
- /// </summary>
- private void HandleSdoUpload(ushort index, byte subIndex)
- {
- byte[] response = new byte[8];
-
- Console.WriteLine($"[SDO详细] 收到上传请求: 索引0x{index:X4}, 子索引{subIndex}");
-
- // 触发自定义事件
- OnSdoReadRequest?.Invoke(m_nodeId, index, subIndex);
-
- // 根据索引返回数据
- if (m_objectDictionary.TryGetValue(index, out object value))
- {
- Console.WriteLine($"[SDO详细] 找到对象 0x{index:X4}");
-
- if (subIndex == 0)
- {
- // 返回子索引数量
- response[0] = 0x4F; // 快速上传响应
- response[1] = (byte)(index & 0xFF);
- response[2] = (byte)(index >> 8);
- response[3] = subIndex;
-
- if (value is IdentityObject identity)
- {
- response[4] = 4; // 4个子条目
- Console.WriteLine($"[SDO详细] 返回Identity对象,子条目数: 4");
- }
- else if (value is PdoMappingParam mappingParam)
- {
- response[4] = mappingParam.NumberOfEntries;
- Console.WriteLine($"[SDO详细] 返回PDO映射参数,子条目数: {mappingParam.NumberOfEntries}");
- }
- else
- {
- response[4] = 0;
- Console.WriteLine($"[SDO详细] 返回简单对象,子条目数: 0");
- }
- }
- else
- {
- // 返回具体子索引的值
- response[0] = 0x4B; // 4字节快速上传
- response[1] = (byte)(index & 0xFF);
- response[2] = (byte)(index >> 8);
- response[3] = subIndex;
-
- uint dataValue = 0;
-
- if (index == (ushort)0x1000 && value is uint deviceType)
- {
- dataValue = deviceType;
- Console.WriteLine($"[SDO详细] 返回设备类型: 0x{dataValue:X8}");
- }
- else if (index == (ushort)0x1001 && value is byte errorReg)
- {
- response[0] = 0x4F; // 1字节
- dataValue = errorReg;
- Console.WriteLine($"[SDO详细] 返回错误寄存器: 0x{dataValue:X2}");
- }
- else if (index == (ushort)0x1017 && value is ushort heartbeatTime)
- {
- response[0] = 0x4B; // 2字节
- dataValue = heartbeatTime;
- Console.WriteLine($"[SDO详细] 返回心跳时间: {heartbeatTime}ms");
- }
- else if (index == (ushort)0x1018 && value is IdentityObject identity)
- {
- response[0] = 0x4B;
- switch (subIndex)
- {
- case 1: dataValue = identity.VendorId; break;
- case 2: dataValue = identity.ProductCode; break;
- case 3: dataValue = identity.RevisionNumber; break;
- default: dataValue = 0; break;
- }
- Console.WriteLine($"[SDO详细] 返回Identity子索引{subIndex}: 0x{dataValue:X8}");
- }
- else if ((index >= (ushort)0x1800 && index <= (ushort)0x1803) && value is TpdoCommParam tpdoParam)
- {
- switch (subIndex)
- {
- case 1: dataValue = tpdoParam.CobId; break;
- case 2: dataValue = tpdoParam.TransmissionType; break;
- default: dataValue = 0; break;
- }
- Console.WriteLine($"[SDO详细] 返回TPDO{index - 0x1800 + 1}通信参数子索引{subIndex}: 0x{dataValue:X8}");
- }
- else if ((index >= (ushort)0x1400 && index <= (ushort)0x1403) && value is RpdoCommParam rpdoParam)
- {
- switch (subIndex)
- {
- case 1: dataValue = rpdoParam.CobId; break;
- case 2: dataValue = rpdoParam.TransmissionType; break;
- default: dataValue = 0; break;
- }
- Console.WriteLine($"[SDO详细] 返回RPDO{index - 0x1400 + 1}通信参数子索引{subIndex}: 0x{dataValue:X8}");
- }
-
- response[4] = (byte)(dataValue & 0xFF);
- response[5] = (byte)((dataValue >> 8) & 0xFF);
- response[6] = (byte)((dataValue >> 16) & 0xFF);
- response[7] = (byte)((dataValue >> 24) & 0xFF);
- }
-
- // 发送SDO响应
- uint responseCobId = (uint)0x580 + m_nodeId;
- Console.WriteLine($"[SDO响应] COB-ID: 0x{responseCobId:X3}, Index: 0x{index:X4}, SubIndex: {subIndex}, Data: {BitConverter.ToString(response).Replace("-", " ")}");
- m_canManager.SendCanFrame(responseCobId, response);
- }
- else
- {
- // 对象不存在,发送错误响应
- Console.WriteLine($"[SDO详细] 对象 0x{index:X4} 不存在,返回错误");
- response[0] = 0x80; // 错误响应
- response[1] = (byte)(index & 0xFF);
- response[2] = (byte)(index >> 8);
- response[3] = subIndex;
- response[4] = 0x06; // 错误代码: 对象不存在
- response[5] = 0x02;
- response[6] = 0x00;
- response[7] = 0x00;
-
- uint responseCobId = (uint)0x580 + m_nodeId;
- Console.WriteLine($"[SDO错误响应] COB-ID: 0x{responseCobId:X3}, Index: 0x{index:X4}, SubIndex: {subIndex}");
- m_canManager.SendCanFrame(responseCobId, response);
- }
- }
-
- /// <summary>
- /// 处理SDO下载 (写对象字典)
- /// </summary>
- private void HandleSdoDownload(ushort index, byte subIndex, byte[] data)
- {
- uint value = (uint)(data[4] | (data[5] << 8) | (data[6] << 16) | (data[7] << 24));
-
- // 触发自定义事件
- OnSdoWriteRequest?.Invoke(m_nodeId, index, subIndex, value);
-
- // 更新对象字典
- if (m_objectDictionary.ContainsKey(index))
- {
- // 特殊处理:心跳时间对象 (0x1017)
- if (index == (ushort)0x1017 && subIndex == 0)
- {
- ushort heartbeatTime = (ushort)value;
- m_objectDictionary[index] = heartbeatTime;
- ConfigureHeartbeat(heartbeatTime); // 重新配置心跳
- Console.WriteLine($"[SDO写入] 心跳时间已更新为: {heartbeatTime}ms");
- }
- else if (index >= (ushort)0x1800 && index <= (ushort)0x1803 && m_objectDictionary[index] is TpdoCommParam tpdoParam)
- {
- int pdoIndex = index - (ushort)0x1800;
- if (subIndex == 1)
- {
- tpdoParam.CobId = value;
- m_tpdoConfigs[pdoIndex].CobId = value;
- }
- else if (subIndex == 2)
- {
- tpdoParam.TransmissionType = (byte)value;
- m_tpdoConfigs[pdoIndex].TransmissionType = (byte)value;
- }
- }
- else if (index >= (ushort)0x1400 && index <= (ushort)0x1403 && m_objectDictionary[index] is RpdoCommParam rpdoParam)
- {
- int pdoIndex = index - (ushort)0x1400;
- if (subIndex == 1)
- {
- rpdoParam.CobId = value;
- m_rpdoConfigs[pdoIndex].CobId = value;
- }
- else if (subIndex == 2)
- {
- rpdoParam.TransmissionType = (byte)value;
- m_rpdoConfigs[pdoIndex].TransmissionType = (byte)value;
- }
- }
- }
-
- // 发送SDO确认响应
- byte[] response = new byte[8];
- response[0] = 0x60; // SDO下载确认
- response[1] = (byte)(index & 0xFF);
- response[2] = (byte)(index >> 8);
- response[3] = subIndex;
-
- uint responseCobId = (uint)0x580 + m_nodeId;
- m_canManager.SendCanFrame(responseCobId, response);
- }
-
- #endregion
-
- #region RPDO处理
-
- /// <summary>
- /// 处理接收到的RPDO
- /// </summary>
- private void ProcessRpdo(byte pdoNumber, byte[] data, byte length)
- {
- Console.WriteLine($"收到RPDO{pdoNumber}: 长度{length}字节");
-
- // 复制有效数据
- byte[] validData = new byte[length];
- Array.Copy(data, validData, length);
-
- // 触发事件
- OnRpdoReceived?.Invoke(m_nodeId, pdoNumber, validData);
- }
-
- #endregion
-
- #region TPDO发送
-
- /// <summary>
- /// 发送TPDO
- /// </summary>
- public void SendTpdo(byte pdoNumber)
- {
- if (pdoNumber < 1 || pdoNumber > 4)
- throw new ArgumentException("PDO编号必须在1-4之间");
-
- if (!m_tpdoConfigs[pdoNumber - 1].Enabled)
- {
- Console.WriteLine($"TPDO{pdoNumber}未启用");
- return;
- }
-
- // TODO: 根据映射表构建PDO数据
- // 此处数据长度不可以超过PLC中PDO映射的长度
- // 这里使用示例数据
- byte[] pdoData = new byte[8];
-
- // 示例: 填充一些测试数据
- pdoData[0] = (byte)(255);
- pdoData[1] = (byte)(255);
- pdoData[2] = (byte)(255);
- pdoData[3] = (byte)(255);
- pdoData[4] = (byte)(255);
- pdoData[5] = (byte)(255);
- pdoData[6] = (byte)(255);
- pdoData[7] = (byte)(255);
- uint cobId = m_tpdoConfigs[pdoNumber - 1].CobId;
- m_canManager.SendCanFrame(cobId, pdoData);
-
- Console.WriteLine($"发送TPDO{pdoNumber}: COB-ID 0x{cobId:X3}");
- }
-
- /// <summary>
- /// 发送所有启用的TPDO
- /// </summary>
- public void SendAllTpdos()
- {
- for (byte i = 1; i <= 4; i++)
- {
- if (m_tpdoConfigs[i - 1].Enabled)
- {
- SendTpdo(i);
- }
- }
- }
-
- #endregion
-
- #region 心跳机制
-
- /// <summary>
- /// 配置心跳
- /// </summary>
- /// <param name="heartbeatTimeMs">心跳时间(毫秒),0表示禁用</param>
- public void ConfigureHeartbeat(ushort heartbeatTimeMs)
- {
- m_producerHeartbeatTime = heartbeatTimeMs;
-
- // 同步更新对象字典中的 1017h 对象
- if (m_objectDictionary.ContainsKey((ushort)0x1017))
- {
- m_objectDictionary[(ushort)0x1017] = heartbeatTimeMs;
- }
-
- // 停止旧的定时器
- m_heartbeatTimer?.Dispose();
-
- if (heartbeatTimeMs > 0)
- {
- // 创建新的定时器
- m_heartbeatTimer = new Timer(state =>
- {
- // 只在PreOperational和Operational状态下发送心跳
- // Initializing和Stopped状态下不发送心跳
- if (m_currentState == NmtState.Operational ||
- m_currentState == NmtState.PreOperational)
- {
- SendHeartbeat();
- }
- else
- {
- // 在其他状态下跳过心跳发送
- //Console.WriteLine($"[心跳跳过] 当前状态: {m_currentState}, 不发送心跳");
- }
- }, null, heartbeatTimeMs, heartbeatTimeMs);
-
- Console.WriteLine($"心跳已配置: {heartbeatTimeMs}ms");
- }
- else
- {
- Console.WriteLine("心跳已禁用");
- }
- }
-
- /// <summary>
- /// 发送心跳
- /// </summary>
- private void SendHeartbeat()
- {
- byte[] heartbeatData = new byte[1];
-
- // 根据当前状态设置心跳字节
- switch (m_currentState)
- {
- case NmtState.Initializing:
- heartbeatData[0] = 0x00;
- break;
- case NmtState.PreOperational:
- heartbeatData[0] = 0x7F;
- break;
- case NmtState.Operational:
- heartbeatData[0] = 0x05;
- break;
- case NmtState.Stopped:
- heartbeatData[0] = 0x04;
- break;
- default:
- heartbeatData[0] = 0x00;
- break;
- }
-
- uint heartbeatCobId = (uint)0x700 + (uint)m_nodeId;
- //Console.WriteLine($"[心跳发送] COB-ID: 0x{heartbeatCobId:X3}, Data: {heartbeatData[0]:X2} (状态: {m_currentState})");
- m_canManager.SendCanFrame(heartbeatCobId, heartbeatData);
- }
-
- /// <summary>
- /// 发送无错误紧急报文 (EMCY)
- /// 用于在启动时表明设备无错误状态
- /// </summary>
- private void SendNoErrorEmcy()
- {
- byte[] emcyData = new byte[8];
- emcyData[0] = 0x00; // 错误代码低字节 - 无错误
- emcyData[1] = 0x00; // 错误代码高字节
- emcyData[2] = 0x00; // 错误寄存器
-
- uint emcyCobId = (uint)0x080 + (uint)m_nodeId;
- Console.WriteLine($"[EMCY] 发送无错误报文 - COB-ID: 0x{emcyCobId:X3}");
- m_canManager.SendCanFrame(emcyCobId, emcyData);
- }
- #endregion
-
- #region 辅助方法
-
- /// <summary>
- /// 获取RPDO的COB-ID
- /// </summary>
- private uint GetRpdoCobId(byte pdoNumber, byte nodeId)
- {
- switch (pdoNumber)
- {
- case 1: return (uint)0x200 + nodeId;
- case 2: return (uint)0x300 + nodeId;
- case 3: return (uint)0x400 + nodeId;
- case 4: return (uint)0x500 + nodeId;
- default: throw new ArgumentException("无效的PDO编号");
- }
- }
-
- /// <summary>
- /// 获取TPDO的COB-ID
- /// </summary>
- private uint GetTpdoCobId(byte pdoNumber, byte nodeId)
- {
- switch (pdoNumber)
- {
- case 1: return (uint)0x180 + nodeId;
- case 2: return (uint)0x280 + nodeId;
- case 3: return (uint)0x380 + nodeId;
- case 4: return (uint)0x480 + nodeId;
- default: throw new ArgumentException("无效的PDO编号");
- }
- }
-
- #endregion
-
- #region 资源管理
-
- /// <summary>
- /// 释放资源
- /// </summary>
- public void Dispose()
- {
- Stop();
- m_canManager?.Dispose();
- m_cancellationTokenSource?.Dispose();
- m_heartbeatTimer?.Dispose();
- }
-
- #endregion
-
- #region 公共属性
-
- /// <summary>
- /// 获取当前节点ID
- /// </summary>
- public byte NodeId => m_nodeId;
-
- /// <summary>
- /// 获取当前NMT状态
- /// </summary>
- public NmtState CurrentState => m_currentState;
-
- /// <summary>
- /// 获取是否正在运行
- /// </summary>
- public bool IsRunning => m_isRunning;
-
- #endregion
- }
-
- #region 数据结构定义
-
- /// <summary>
- /// NMT状态枚举
- /// </summary>
- public enum NmtState
- {
- Initializing = 0x00,
- PreOperational = 0x7F,
- Operational = 0x05,
- Stopped = 0x04
- }
-
- /// <summary>
- /// PDO配置
- /// </summary>
- public class PdoConfig
- {
- public uint CobId { get; set; }
- public byte TransmissionType { get; set; } // 0xFF=事件驱动, 1-240=同步周期
- public bool Enabled { get; set; }
- }
-
- /// <summary>
- /// PDO映射
- /// </summary>
- public class PdoMapping
- {
- public ushort Index { get; set; }
- public byte SubIndex { get; set; }
- public byte BitLength { get; set; }
- }
-
- /// <summary>
- /// PDO映射参数
- /// </summary>
- public class PdoMappingParam
- {
- public byte NumberOfEntries { get; set; }
- public uint[] Mappings { get; set; }
- }
-
- /// <summary>
- /// 身份对象 (1018h)
- /// </summary>
- public class IdentityObject
- {
- public uint VendorId { get; set; }
- public uint ProductCode { get; set; }
- public uint RevisionNumber { get; set; }
- }
-
- /// <summary>
- /// TPDO通信参数 (1800-1803h)
- /// </summary>
- public class TpdoCommParam
- {
- public uint CobId { get; set; }
- public byte TransmissionType { get; set; }
- }
-
- /// <summary>
- /// RPDO通信参数 (1400-1403h)
- /// </summary>
- public class RpdoCommParam
- {
- public uint CobId { get; set; }
- public byte TransmissionType { get; set; }
- }
-
- #endregion
- }
|