TwincatCoeInterface.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. using Aitex.Core.RT.Log;
  2. using MECF.Framework.Common.Beckhoff.IOAxis;
  3. using MECF.Framework.Common.IOCore;
  4. using MECF.Framework.Common.Utilities;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Globalization;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using TwinCAT.Ads;
  13. namespace MECF.Framework.Common.TwinCat
  14. {
  15. public class TwincatCoeInterface
  16. {
  17. #region 常量
  18. private const int INDEXGROUP_SDO_UPLOAD_DOWNLOAD = 0x0000f302;
  19. #endregion
  20. #region 内部变量
  21. /// <summary>
  22. /// ads COE对象
  23. /// </summary>
  24. private TcAdsClient _adsClientCOE;
  25. /// <summary>
  26. /// Net Id
  27. /// </summary>
  28. private string _netId;
  29. /// <summary>
  30. /// 端口号
  31. /// </summary>
  32. private int _port;
  33. /// <summary>
  34. /// 轴对象
  35. /// </summary>
  36. private BeckhoffAxis _axis;
  37. /// <summary>
  38. /// 连接输入变量(连接后读取变量)
  39. /// </summary>
  40. private BeckhoffAxisInput _connectInputVariable;
  41. /// <summary>
  42. /// 连接状态
  43. /// </summary>
  44. private bool _isConnected = false;
  45. /// <summary>
  46. /// coe输入变量(key-名称,value-输入变量对象)
  47. /// </summary>
  48. private Dictionary<string,BeckhoffAxisInput> _nameCoeInputDic = new Dictionary<string, BeckhoffAxisInput>();
  49. /// <summary>
  50. /// COE名称变量字典(key-名称,value-输出变量对象)
  51. /// </summary>
  52. private Dictionary<string, BeckhoffAxisOutput> _nameCoeOutputDic = new Dictionary<string, BeckhoffAxisOutput>();
  53. /// <summary>
  54. /// 连接是否完成
  55. /// </summary>
  56. private bool _isConnectComplete = false;
  57. /// <summary>
  58. /// 启动读取线程
  59. /// </summary>
  60. private Thread _startReadThread = null;
  61. #endregion
  62. /// <summary>
  63. /// 模拟
  64. /// </summary>
  65. /// <param name="moduleName"></param>
  66. /// <param name="netId"></param>
  67. /// <param name="port"></param>
  68. public TwincatCoeInterface(BeckhoffAxis beckhoffAxis)
  69. {
  70. _axis = beckhoffAxis;
  71. _netId = beckhoffAxis.COEAddress;
  72. _port = beckhoffAxis.COEPort;
  73. AnalyseConnectInputVariable();
  74. _adsClientCOE = new TcAdsClient();
  75. _adsClientCOE.ConnectionStateChanged += AdsClientCOE_ConnectionStateChanged;
  76. }
  77. /// <summary>
  78. /// 解析连接变量
  79. /// </summary>
  80. private void AnalyseConnectInputVariable()
  81. {
  82. foreach(BeckhoffAxisInput item in _axis.Inputs)
  83. {
  84. if(item.Address.StartsWith("0x"))
  85. {
  86. _connectInputVariable = item;
  87. break;
  88. }
  89. }
  90. }
  91. /// <summary>
  92. /// 初始化输入输出变量
  93. /// </summary>
  94. public void InnitialInputAndOutputVariable(BeckhoffAxis beckhoffAxis)
  95. {
  96. foreach (BeckhoffAxisInput item in beckhoffAxis.Inputs)
  97. {
  98. if (item.Address.StartsWith("0x"))
  99. {
  100. _nameCoeInputDic[$"{beckhoffAxis.Name}.{item.Type}"] = item;
  101. }
  102. }
  103. foreach(BeckhoffAxisOutput item in beckhoffAxis.Outputs)
  104. {
  105. if (item.Address.StartsWith("0x"))
  106. {
  107. _nameCoeOutputDic[$"{beckhoffAxis.Name}.{item.Type}"] = item;
  108. }
  109. }
  110. }
  111. /// <summary>
  112. /// 开启读取变量线程
  113. /// </summary>
  114. public void StartReadInputDataThread()
  115. {
  116. if (_startReadThread == null)
  117. {
  118. _startReadThread = new Thread(new ThreadStart(StartReadInputData));
  119. _startReadThread.IsBackground = true;
  120. _startReadThread.Start();
  121. }
  122. }
  123. /// <summary>
  124. /// 读取变量
  125. /// </summary>
  126. private void StartReadInputData()
  127. {
  128. DateTime dt = DateTime.Now;
  129. while(true)
  130. {
  131. if(DateTime.Now.Subtract(dt).TotalSeconds>=5)
  132. {
  133. break;
  134. }
  135. if(!_isConnectComplete)
  136. {
  137. continue;
  138. }
  139. if(!_isConnected)
  140. {
  141. continue;
  142. }
  143. if (_nameCoeInputDic.Count != 0)
  144. {
  145. ReadAllCoeInputs();
  146. break;
  147. }
  148. else
  149. {
  150. Thread.Sleep(500);
  151. }
  152. }
  153. }
  154. /// <summary>
  155. /// 读取所有COE变量
  156. /// </summary>
  157. private void ReadAllCoeInputs()
  158. {
  159. if(_nameCoeInputDic.Keys==null|| _nameCoeInputDic.Count==0)
  160. {
  161. return;
  162. }
  163. List<string> keys = _nameCoeInputDic.Keys.ToList();
  164. foreach (string key in keys)
  165. {
  166. BeckhoffAxisInput item = _nameCoeInputDic[key];
  167. Type type = DataTypeUtil.GetSystemDataTypeByBeckhoffDataType(item.DataType);
  168. var sdoResult = AnalyseSdoIndex(item.Address);
  169. if (sdoResult.Item1)
  170. {
  171. object value = ReadCOEData(sdoResult.Item2, sdoResult.Item3, type);
  172. if (value != null)
  173. {
  174. IOModuleManager.Instance.UpdateIoValue(key, value);
  175. }
  176. else
  177. {
  178. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"read {key} error");
  179. }
  180. }
  181. Thread.Sleep(10);
  182. }
  183. }
  184. /// <summary>
  185. /// 连接状态变化
  186. /// </summary>
  187. /// <param name="sender"></param>
  188. /// <param name="e"></param>
  189. private void AdsClientCOE_ConnectionStateChanged(object sender, TwinCAT.ConnectionStateChangedEventArgs e)
  190. {
  191. if (e.NewState == TwinCAT.ConnectionState.Connected)
  192. {
  193. try
  194. {
  195. if (_connectInputVariable != null)
  196. {
  197. var inputResult = AnalyseSdoIndex(_connectInputVariable.Address);
  198. if (inputResult.Item1)
  199. {
  200. object obj= ReadFirstCOEData(inputResult.Item2, inputResult.Item3, DataTypeUtil.GetSystemDataTypeByBeckhoffDataType(_connectInputVariable.DataType));
  201. if (obj != null)
  202. {
  203. _isConnected = true;
  204. _isConnectComplete = true;
  205. }
  206. }
  207. }
  208. }
  209. catch (Exception ex)
  210. {
  211. _isConnectComplete = true;
  212. _isConnected = false;
  213. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat connect{_netId}:{_port} error");
  214. return;
  215. }
  216. }
  217. else
  218. {
  219. _isConnected = false;
  220. LOG.WriteLog(eEvent.ERR_TWINCAT,"System", $"Twincat connect{_netId}:{_port} error");
  221. }
  222. }
  223. /// <summary>
  224. /// 连接
  225. /// </summary>
  226. /// <returns></returns>
  227. public void Connect()
  228. {
  229. try
  230. {
  231. _adsClientCOE.Connect(_netId, _port);
  232. }
  233. catch(Exception ex)
  234. {
  235. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", ex.Message);
  236. }
  237. }
  238. #region 写数据
  239. /// <summary>
  240. /// 写数据
  241. /// </summary>
  242. /// <param name="moduleName"></param>
  243. /// <param name="variableName"></param>
  244. /// <param name="value"></param>
  245. /// <returns></returns>
  246. public bool WriteModuleCoeData(string moduleName,string variableName,object value)
  247. {
  248. if(_isConnected)
  249. {
  250. string str = $"{moduleName}.{variableName}";
  251. if(_nameCoeOutputDic.ContainsKey(str))
  252. {
  253. BeckhoffAxisOutput output = _nameCoeOutputDic[str];
  254. try
  255. {
  256. var sdoResult = AnalyseSdoIndex(output.Address);
  257. if(sdoResult.Item1)
  258. {
  259. bool result=WriteCOEData(sdoResult.Item2, sdoResult.Item3, value);
  260. if (result&&_nameCoeInputDic.ContainsKey(str))
  261. {
  262. object rdValue = ReadCOEData(sdoResult.Item2, sdoResult.Item3, DataTypeUtil.GetSystemDataTypeByBeckhoffDataType(output.DataType));
  263. if (rdValue != null)
  264. {
  265. IOModuleManager.Instance.UpdateIoValue(str, rdValue);
  266. }
  267. }
  268. return true;
  269. }
  270. else
  271. {
  272. return false;
  273. }
  274. }
  275. catch(Exception ex)
  276. {
  277. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat cannot write COE data, message is [{ex.Message}]");
  278. return false;
  279. }
  280. }
  281. else
  282. {
  283. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat doesnot have [{moduleName}.{variableName}] variable ,cannot write COE data");
  284. return false;
  285. }
  286. }
  287. else
  288. {
  289. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", "twincat connect failed,cannot write COE data");
  290. return false;
  291. }
  292. }
  293. /// <summary>
  294. /// 解析Sdo索引
  295. /// </summary>
  296. /// <param name="address"></param>
  297. /// <returns></returns>
  298. private (bool,int,int) AnalyseSdoIndex(string address)
  299. {
  300. string[] strAry = address.Split(':');
  301. if (strAry.Length != 2)
  302. {
  303. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat invalid address is {address}");
  304. return (false,0,0);
  305. }
  306. else
  307. {
  308. if (int.TryParse(strAry[0].Remove(0,2), System.Globalization.NumberStyles.HexNumber, System.Globalization.NumberFormatInfo.InvariantInfo, out int sdoIndex) &&
  309. int.TryParse(strAry[1], out int sdoSubIndex))
  310. {
  311. return (true,sdoIndex,sdoSubIndex);
  312. }
  313. else
  314. {
  315. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat invalid address is {address}");
  316. return (false,0,0);
  317. }
  318. }
  319. }
  320. /// <summary>
  321. /// 写COE Byte数据
  322. /// </summary>
  323. /// <param name="sdoIndex"></param>
  324. /// <param name="sdoSubIndex"></param>
  325. /// <param name="value"></param>
  326. private bool WriteCOEData(int sdoIndex,int sdoSubIndex,object value)
  327. {
  328. if (_isConnected)
  329. {
  330. int indexOffset = (int)sdoIndex * 65536 + sdoSubIndex;
  331. try
  332. {
  333. _adsClientCOE.WriteAny(INDEXGROUP_SDO_UPLOAD_DOWNLOAD, indexOffset, value);
  334. return true;
  335. }
  336. catch (Exception ex)
  337. {
  338. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat write COE data failed {ex.Message}.IndexOffset:{sdoIndex}:{sdoSubIndex}");
  339. return false;
  340. }
  341. }
  342. else
  343. {
  344. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", "twincat connect failed,cannot write COE data");
  345. return false;
  346. }
  347. }
  348. #endregion
  349. #region 读数据
  350. /// <summary>
  351. /// 读取COE Byte数据
  352. /// </summary>
  353. /// <param name="sdoIndex"></param>
  354. /// <param name="sdoSubIndex"></param>
  355. /// <returns></returns>
  356. public object ReadCOEData(int sdoIndex,int sdoSubIndex,Type type)
  357. {
  358. if (_isConnected)
  359. {
  360. int indexOffset = (int)sdoIndex * 65536 + sdoSubIndex;
  361. try
  362. {
  363. return _adsClientCOE.ReadAny(INDEXGROUP_SDO_UPLOAD_DOWNLOAD, indexOffset, type);
  364. }
  365. catch(Exception ex)
  366. {
  367. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat read COE data failed {ex.Message}.IndexOffset:{sdoIndex}:{sdoSubIndex}");
  368. return null;
  369. }
  370. }
  371. else
  372. {
  373. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", "twincat connect failed,cannot read COE data");
  374. return null;
  375. }
  376. }
  377. /// <summary>
  378. /// 读取第一个COE数据
  379. /// </summary>
  380. /// <param name="sdoIndex"></param>
  381. /// <param name="sdoSubIndex"></param>
  382. /// <param name="type"></param>
  383. /// <returns></returns>
  384. private object ReadFirstCOEData(int sdoIndex, int sdoSubIndex, Type type)
  385. {
  386. int indexOffset = (int)sdoIndex * 65536 + sdoSubIndex;
  387. try
  388. {
  389. return _adsClientCOE.ReadAny(INDEXGROUP_SDO_UPLOAD_DOWNLOAD, indexOffset, type);
  390. }
  391. catch (Exception ex)
  392. {
  393. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat read COE data failed {ex.Message}.IndexOffset:{sdoIndex}:{sdoSubIndex}");
  394. return null;
  395. }
  396. }
  397. #endregion
  398. }
  399. }