TwincatAdoManager.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. using Aitex.Core.RT.IOCore;
  2. using Aitex.Core.RT.Log;
  3. using Aitex.Core.Util;
  4. using DocumentFormat.OpenXml.Wordprocessing;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Runtime.InteropServices;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. using TwinCAT.Ads;
  15. using Venus_Core;
  16. namespace MECF.Framework.Common.Twincat
  17. {
  18. /// <summary>
  19. /// 变量数值发生变化委托声明
  20. /// </summary>
  21. /// <param name="variableName"></param>
  22. /// <param name="value"></param>
  23. public delegate void OnUpdateModuleVariableValue(string variableName, object value);
  24. /// <summary>
  25. /// Twicat Ado通信
  26. /// </summary>
  27. public class TwincatAdoManager
  28. {
  29. #region 内部变量
  30. /// <summary>
  31. /// IO长度字典(key-变量名称,value-变量数据长度)
  32. /// </summary>
  33. private ConcurrentDictionary<string, int> _ioLengthDic = new ConcurrentDictionary<string, int>();
  34. /// <summary>
  35. /// 输出变量集合
  36. /// </summary>
  37. private ConcurrentBag<string> _outputBag = new ConcurrentBag<string>();
  38. /// <summary>
  39. /// 主动读取变量集合
  40. /// </summary>
  41. private ConcurrentBag<string> _inputBag = new ConcurrentBag<string>();
  42. /// <summary>
  43. /// Twincat 对象
  44. /// </summary>
  45. private TcAdsClient _adsClient = null;
  46. /// <summary>
  47. /// 地址
  48. /// </summary>
  49. private string _ipAddress = "";
  50. /// <summary>
  51. /// 端口号
  52. /// </summary>
  53. private int _port = 851;
  54. /// <summary>
  55. /// 句柄变量名称字典(key-创建句柄,value-变量名称)
  56. /// </summary>
  57. private Dictionary<int, string> _notificationHandleNameDic = new Dictionary<int, string>();
  58. /// <summary>
  59. /// 模块变量更新委托字典(key-模块.变量,value-变量委托事件
  60. /// </summary>
  61. private Dictionary<string, OnUpdateModuleVariableValue> _moduleVariableActionDic = new Dictionary<string, OnUpdateModuleVariableValue>();
  62. /// <summary>
  63. /// 写变更名称句柄字典(key-变量名称,value-创建句柄)
  64. /// </summary>
  65. private Dictionary<string, int> _writeNameHandleDic = new Dictionary<string, int>();
  66. /// <summary>
  67. /// 主动读取名称字典(key-变量名称,value-创建句柄)
  68. /// </summary>
  69. private Dictionary<string, int> _readNameHandleDic = new Dictionary<string, int>();
  70. private AdsStream _adsStream;
  71. private BinaryReader _reader;
  72. /// <summary>
  73. /// 连接状态
  74. /// </summary>
  75. private bool _isConnected;
  76. #endregion
  77. /// <summary>
  78. /// 订阅变量
  79. /// </summary>
  80. /// <param name="itemName"></param>
  81. /// <param name="itemLength"></param>
  82. public void Subscribe(string itemName,int itemLength, OnUpdateModuleVariableValue onUpdateModuleVariableValue)
  83. {
  84. _ioLengthDic[itemName] = itemLength;
  85. _moduleVariableActionDic[itemName] = onUpdateModuleVariableValue;
  86. }
  87. /// <summary>
  88. /// 订阅输出变量名称
  89. /// </summary>
  90. /// <param name="itemName"></param>
  91. public void SubscribeOutput(string itemName)
  92. {
  93. _outputBag.Add(itemName);
  94. }
  95. /// <summary>
  96. /// 订阅主动读取变量名称
  97. /// </summary>
  98. /// <param name="itemName"></param>
  99. public void SubscribeInput(string itemName)
  100. {
  101. _inputBag.Add(itemName);
  102. }
  103. /// <summary>
  104. /// 初始化
  105. /// </summary>
  106. /// <param name="ipAddress"></param>
  107. /// <param name="port"></param>
  108. public void Initialize(string ipAddress,int port)
  109. {
  110. _ipAddress = ipAddress;
  111. _port = port;
  112. }
  113. /// <summary>
  114. /// 获取所有数据长度
  115. /// </summary>
  116. /// <returns></returns>
  117. private int GetAllSize()
  118. {
  119. int size = 0;
  120. foreach(string item in _ioLengthDic.Keys)
  121. {
  122. size+= _ioLengthDic[item];
  123. }
  124. return size;
  125. }
  126. /// <summary>
  127. /// ADO变量变化通知,twincat->上位机
  128. /// </summary>
  129. /// <param name="sender"></param>
  130. /// <param name="e"></param>
  131. private void AdsClient_AdsNotification(object sender, AdsNotificationEventArgs e)
  132. {
  133. try
  134. {
  135. if (_notificationHandleNameDic.ContainsKey(e.NotificationHandle))
  136. {
  137. string item = _notificationHandleNameDic[e.NotificationHandle];
  138. if(!_ioLengthDic.ContainsKey(item))
  139. {
  140. LOG.Write(eEvent.ERR_TWINCAT, "System", $"{item} not in twincat io list");
  141. return;
  142. }
  143. int size = _ioLengthDic[item];
  144. e.DataStream.Position = e.Offset;
  145. if(size==1)
  146. {
  147. bool boolValue = _reader.ReadBoolean();
  148. if(_moduleVariableActionDic.ContainsKey(item))
  149. {
  150. _moduleVariableActionDic[item].Invoke(item, boolValue);
  151. }
  152. }
  153. else if(size==4)
  154. {
  155. float floatValue= _reader.ReadSingle();
  156. if (_moduleVariableActionDic.ContainsKey(item))
  157. {
  158. _moduleVariableActionDic[item].Invoke(item, floatValue);
  159. }
  160. }
  161. else
  162. {
  163. byte[] byt = new byte[size];
  164. var value = _reader.Read(byt, 0, byt.Length);
  165. if (_moduleVariableActionDic.ContainsKey(item))
  166. {
  167. _moduleVariableActionDic[item].Invoke(item, byt);
  168. }
  169. //LOG.Write(eEvent.ERR_TWINCAT, "System", $"{item} size is invalid");
  170. }
  171. }
  172. }
  173. catch (Exception ex)
  174. {
  175. LOG.Write(eEvent.ERR_TWINCAT, "System", ex.Message);
  176. }
  177. }
  178. /// <summary>
  179. /// 连接状态变化
  180. /// </summary>
  181. /// <param name="sender"></param>
  182. /// <param name="e"></param>
  183. private void AdsClient_ConnectionStateChanged(object sender, TwinCAT.ConnectionStateChangedEventArgs e)
  184. {
  185. if (e.NewState == TwinCAT.ConnectionState.Connected)
  186. {
  187. try
  188. {
  189. StateInfo stateInfo = _adsClient.ReadState();
  190. CreateWriteHandle();
  191. CreateReadHandle();
  192. SubscribeNotification();
  193. _isConnected = true;
  194. }
  195. catch (Exception ex)
  196. {
  197. _isConnected = false;
  198. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat connect{_ipAddress}:{_port} error");
  199. return;
  200. }
  201. }
  202. else
  203. {
  204. _isConnected = false;
  205. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat connect{_ipAddress}:{_port} error");
  206. }
  207. }
  208. /// <summary>
  209. /// 启动
  210. /// </summary>
  211. public void Start()
  212. {
  213. _adsClient = new TcAdsClient();
  214. _adsClient.ConnectionStateChanged += AdsClient_ConnectionStateChanged;
  215. _adsClient.AdsNotification += AdsClient_AdsNotification;
  216. _adsStream = new AdsStream(GetAllSize());
  217. _reader = new BinaryReader(_adsStream);
  218. try
  219. {
  220. _adsClient.Connect(_ipAddress, _port);
  221. }
  222. catch
  223. {
  224. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat connect{_ipAddress}:{_port} error");
  225. }
  226. }
  227. /// <summary>
  228. /// 创建写入句柄
  229. /// </summary>
  230. private void CreateWriteHandle()
  231. {
  232. _writeNameHandleDic.Clear();
  233. foreach (string item in _outputBag)
  234. {
  235. try
  236. {
  237. int handle = _adsClient.CreateVariableHandle(item);
  238. _writeNameHandleDic[item] = handle;
  239. }
  240. catch
  241. {
  242. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat create variable handle {item} error");
  243. }
  244. }
  245. }
  246. /// <summary>
  247. /// 创建主动读取句柄
  248. /// </summary>
  249. private void CreateReadHandle()
  250. {
  251. _readNameHandleDic.Clear();
  252. foreach (string item in _inputBag)
  253. {
  254. try
  255. {
  256. int handle = _adsClient.CreateVariableHandle(item);
  257. _readNameHandleDic[item] = handle;
  258. }
  259. catch
  260. {
  261. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat create variable handle {item} error");
  262. }
  263. }
  264. }
  265. /// <summary>
  266. /// 订阅变量
  267. /// </summary>
  268. private void SubscribeNotification()
  269. {
  270. _notificationHandleNameDic.Clear();
  271. int count = 0;
  272. foreach (string item in _ioLengthDic.Keys)
  273. {
  274. int size = _ioLengthDic[item];
  275. try
  276. {
  277. int handle = _adsClient.AddDeviceNotification(item, _adsStream, count, size, AdsTransMode.OnChange, 0, 0, null);
  278. _notificationHandleNameDic[handle] = item;
  279. count += size;
  280. }
  281. catch
  282. {
  283. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat add variable {item} error");
  284. }
  285. }
  286. }
  287. /// <summary>
  288. /// 写入数值
  289. /// </summary>
  290. /// <param name="name"></param>
  291. /// <param name="value"></param>
  292. /// <returns></returns>
  293. public (bool success,int status) WriteValue(string name, object value)
  294. {
  295. if (_writeNameHandleDic.ContainsKey(name))
  296. {
  297. if (!_isConnected)
  298. {
  299. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat connected failed, write variable {name} error");
  300. return (false,0);
  301. }
  302. try
  303. {
  304. int handle = _writeNameHandleDic[name];
  305. _adsClient.WriteAny(handle, value);
  306. if (value.ToString() == "System.Byte[]")
  307. {
  308. byte[] result = ((byte[])value).Where(b => b != 0).ToArray();
  309. string _value = System.Text.Encoding.UTF8.GetString(result);
  310. LOG.Write(eEvent.EV_TWINCAT, "System", $"Twincat write variable {name} value {_value}");
  311. }
  312. else
  313. {
  314. LOG.Write(eEvent.EV_TWINCAT, "System", $"Twincat write variable {name} value {value}");
  315. }
  316. return (true,0);
  317. }
  318. catch (Exception ex)
  319. {
  320. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat write variable {name} error {ex.Message}");
  321. return (false,1);
  322. }
  323. }
  324. else
  325. {
  326. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat doesnot has {name} variable");
  327. return (false, 0);
  328. }
  329. }
  330. /// <summary>
  331. /// 主动读取
  332. /// </summary>
  333. /// <param name="name"></param>
  334. /// <param name="type"></param>
  335. /// <returns></returns>
  336. public (bool success,object obj) ReadValue(string name,Type type)
  337. {
  338. if (_readNameHandleDic.ContainsKey(name))
  339. {
  340. if (!_isConnected)
  341. {
  342. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat connected failed, read variable {name} error");
  343. return (false, null);
  344. }
  345. try
  346. {
  347. int handle = _readNameHandleDic[name];
  348. return (true, _adsClient.ReadAny(handle,type));
  349. }
  350. catch (Exception ex)
  351. {
  352. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat write variable {name} error {ex.Message}");
  353. return (false, null);
  354. }
  355. }
  356. else
  357. {
  358. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat doesnot has {name} variable");
  359. return (false, null);
  360. }
  361. }
  362. #region 支持写入结构体
  363. /* T必须字段必须为连续地址,
  364. * [StructLayout(LayoutKind.Sequential)]
  365. public class Tag
  366. {
  367. [MarshalAs(UnmanagedType.I1)]
  368. public bool DO_PVN21;
  369. [MarshalAs(UnmanagedType.I1)]
  370. public bool DO_PV11;
  371. [MarshalAs(UnmanagedType.R4)]
  372. public float AI_Chamber_Pressure_10t;
  373. }
  374. * */
  375. /// <summary>
  376. /// 写入类
  377. /// </summary>
  378. /// <typeparam name="T"></typeparam>
  379. /// <param name="name"></param>
  380. /// <param name="data"></param>
  381. /// <returns></returns>
  382. public (bool success,int status) WriteStruct<T>(string name,T data)
  383. {
  384. if (_writeNameHandleDic.ContainsKey(name))
  385. {
  386. if (!_isConnected)
  387. {
  388. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat connected failed, write variable {name} error");
  389. return (false, 0);
  390. }
  391. try
  392. {
  393. int handle = _writeNameHandleDic[name];
  394. _adsClient.WriteAny(handle, data);
  395. LOG.Write(eEvent.EV_TWINCAT, "System", $"Twincat write variable {name} value {data}");
  396. return (true, 0);
  397. }
  398. catch (Exception ex)
  399. {
  400. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat write variable {name} error {ex.Message}");
  401. return (false, 1);
  402. }
  403. }
  404. else
  405. {
  406. LOG.Write(eEvent.ERR_TWINCAT, "System", $"Twincat doesnot has {name} variable");
  407. return (false, 0);
  408. }
  409. }
  410. #endregion
  411. }
  412. }