TwincatCoeInterface.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. /// <summary>
  239. /// 停止
  240. /// </summary>
  241. public void Stop()
  242. {
  243. try
  244. {
  245. _nameCoeInputDic.Clear();
  246. _nameCoeOutputDic.Clear();
  247. }
  248. catch
  249. {
  250. }
  251. try
  252. {
  253. _adsClientCOE.Dispose();
  254. }
  255. catch
  256. {
  257. }
  258. _adsClientCOE = null;
  259. }
  260. #region 写数据
  261. /// <summary>
  262. /// 写数据
  263. /// </summary>
  264. /// <param name="moduleName"></param>
  265. /// <param name="variableName"></param>
  266. /// <param name="value"></param>
  267. /// <returns></returns>
  268. public bool WriteModuleCoeData(string moduleName,string variableName,object value)
  269. {
  270. if(_isConnected)
  271. {
  272. string str = $"{moduleName}.{variableName}";
  273. if(_nameCoeOutputDic.ContainsKey(str))
  274. {
  275. BeckhoffAxisOutput output = _nameCoeOutputDic[str];
  276. try
  277. {
  278. var sdoResult = AnalyseSdoIndex(output.Address);
  279. if(sdoResult.Item1)
  280. {
  281. bool result=WriteCOEData(sdoResult.Item2, sdoResult.Item3, value);
  282. if (result&&_nameCoeInputDic.ContainsKey(str))
  283. {
  284. object rdValue = ReadCOEData(sdoResult.Item2, sdoResult.Item3, DataTypeUtil.GetSystemDataTypeByBeckhoffDataType(output.DataType));
  285. if (rdValue != null)
  286. {
  287. IOModuleManager.Instance.UpdateIoValue(str, rdValue);
  288. }
  289. }
  290. return true;
  291. }
  292. else
  293. {
  294. return false;
  295. }
  296. }
  297. catch(Exception ex)
  298. {
  299. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat cannot write COE data, message is [{ex.Message}]");
  300. return false;
  301. }
  302. }
  303. else
  304. {
  305. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat doesnot have [{moduleName}.{variableName}] variable ,cannot write COE data");
  306. return false;
  307. }
  308. }
  309. else
  310. {
  311. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", "twincat connect failed,cannot write COE data");
  312. return false;
  313. }
  314. }
  315. /// <summary>
  316. /// 解析Sdo索引
  317. /// </summary>
  318. /// <param name="address"></param>
  319. /// <returns></returns>
  320. private (bool,int,int) AnalyseSdoIndex(string address)
  321. {
  322. string[] strAry = address.Split(':');
  323. if (strAry.Length != 2)
  324. {
  325. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat invalid address is {address}");
  326. return (false,0,0);
  327. }
  328. else
  329. {
  330. if (int.TryParse(strAry[0].Remove(0,2), System.Globalization.NumberStyles.HexNumber, System.Globalization.NumberFormatInfo.InvariantInfo, out int sdoIndex) &&
  331. int.TryParse(strAry[1], out int sdoSubIndex))
  332. {
  333. return (true,sdoIndex,sdoSubIndex);
  334. }
  335. else
  336. {
  337. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat invalid address is {address}");
  338. return (false,0,0);
  339. }
  340. }
  341. }
  342. /// <summary>
  343. /// 写COE Byte数据
  344. /// </summary>
  345. /// <param name="sdoIndex"></param>
  346. /// <param name="sdoSubIndex"></param>
  347. /// <param name="value"></param>
  348. private bool WriteCOEData(int sdoIndex,int sdoSubIndex,object value)
  349. {
  350. if (_isConnected)
  351. {
  352. int indexOffset = (int)sdoIndex * 65536 + sdoSubIndex;
  353. try
  354. {
  355. _adsClientCOE.WriteAny(INDEXGROUP_SDO_UPLOAD_DOWNLOAD, indexOffset, value);
  356. return true;
  357. }
  358. catch (Exception ex)
  359. {
  360. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat write COE data failed {ex.Message}.IndexOffset:{sdoIndex}:{sdoSubIndex}");
  361. return false;
  362. }
  363. }
  364. else
  365. {
  366. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", "twincat connect failed,cannot write COE data");
  367. return false;
  368. }
  369. }
  370. #endregion
  371. #region 读数据
  372. /// <summary>
  373. /// 读取COE Byte数据
  374. /// </summary>
  375. /// <param name="sdoIndex"></param>
  376. /// <param name="sdoSubIndex"></param>
  377. /// <returns></returns>
  378. public object ReadCOEData(int sdoIndex,int sdoSubIndex,Type type)
  379. {
  380. if (_isConnected)
  381. {
  382. int indexOffset = (int)sdoIndex * 65536 + sdoSubIndex;
  383. try
  384. {
  385. return _adsClientCOE.ReadAny(INDEXGROUP_SDO_UPLOAD_DOWNLOAD, indexOffset, type);
  386. }
  387. catch(Exception ex)
  388. {
  389. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat read COE data failed {ex.Message}.IndexOffset:{sdoIndex}:{sdoSubIndex}");
  390. return null;
  391. }
  392. }
  393. else
  394. {
  395. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", "twincat connect failed,cannot read COE data");
  396. return null;
  397. }
  398. }
  399. /// <summary>
  400. /// 读取第一个COE数据
  401. /// </summary>
  402. /// <param name="sdoIndex"></param>
  403. /// <param name="sdoSubIndex"></param>
  404. /// <param name="type"></param>
  405. /// <returns></returns>
  406. private object ReadFirstCOEData(int sdoIndex, int sdoSubIndex, Type type)
  407. {
  408. int indexOffset = (int)sdoIndex * 65536 + sdoSubIndex;
  409. try
  410. {
  411. return _adsClientCOE.ReadAny(INDEXGROUP_SDO_UPLOAD_DOWNLOAD, indexOffset, type);
  412. }
  413. catch (Exception ex)
  414. {
  415. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"twincat read COE data failed {ex.Message}.IndexOffset:{sdoIndex}:{sdoSubIndex}");
  416. return null;
  417. }
  418. }
  419. #endregion
  420. }
  421. }