TwincatAdoManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. using Aitex.Core.RT.Event;
  2. using Aitex.Core.RT.IOCore;
  3. using Aitex.Core.RT.Log;
  4. using Aitex.Core.Util;
  5. using MECF.Framework.Common.Beckhoff.IOAxis;
  6. using MECF.Framework.Common.IOCore;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Xml;
  15. using TwinCAT;
  16. using TwinCAT.Ads;
  17. using TwinCAT.Ads.TypeSystem;
  18. using TwinCAT.Ads.ValueAccess;
  19. using TwinCAT.TypeSystem;
  20. namespace MECF.Framework.Common.TwinCat
  21. {
  22. public class TwincatAdoManager : Singleton<TwincatAdoManager>
  23. {
  24. #region 内部变量
  25. private TcAdsClient _adsClient = null;
  26. private string _ipAddress = "";
  27. private int _port = 851;
  28. private BeckhoffCfg _cfg;
  29. private Dictionary<int, BeckhoffItem> _handleItemDic = new Dictionary<int, BeckhoffItem>();
  30. private Dictionary<string, int> _notificationNameHandleDic = new Dictionary<string, int>();
  31. private Dictionary<string, int> _writeNameHandleDic = new Dictionary<string, int>();
  32. private AdsStream _adsStream;
  33. private BinaryReader _reader;
  34. private bool _isConnected = false;
  35. /// <summary>
  36. /// BitOperated地址数值字典(key-BitOperated为true地址,value-数值)
  37. /// </summary>
  38. private Dictionary<string, byte> _bitOperatedAddressValueDic = new Dictionary<string, byte>();
  39. /// <summary>
  40. /// BitOperated锁
  41. /// </summary>
  42. private object _bitOperatedLocker = new object();
  43. #endregion
  44. #region 属性
  45. public bool IsConnect
  46. {
  47. get { return _isConnected; }
  48. set { _isConnected = value; }
  49. }
  50. #endregion
  51. /// <summary>
  52. /// 初始化
  53. /// </summary>
  54. public void Initialize()
  55. {
  56. int size=BeckhoffIOManager.Instance.Size+BeckhoffAxisManager.Instance.Size+BeckhoffCounterManager.Instance.Size;
  57. Init(BeckhoffManager.Instance.BeckhoffCfg, size+100);
  58. }
  59. /// <summary>
  60. /// 初始化
  61. /// </summary>
  62. /// <param name="ipAddress"></param>
  63. /// <param name="port"></param>
  64. private void Init(BeckhoffCfg beckhoffCfg,int size)
  65. {
  66. _adsClient = new TcAdsClient();
  67. _adsClient.ConnectionStateChanged += AdsClient_ConnectionStateChanged;
  68. _cfg = beckhoffCfg;
  69. _ipAddress = beckhoffCfg.Controller.IPAddress;
  70. _port = int.Parse(beckhoffCfg.Controller.PortAddress);
  71. _adsStream = new AdsStream(size);
  72. _reader=new BinaryReader(_adsStream);
  73. _adsClient.AdsNotification += AdsClient_AdsNotification;
  74. _adsClient.AdsNotificationError += AdsClient_AdsNotificationError;
  75. Start();
  76. }
  77. private void AdsClient_AdsNotificationError(object sender, AdsNotificationErrorEventArgs e)
  78. {
  79. }
  80. /// <summary>
  81. /// 连接状态变化
  82. /// </summary>
  83. /// <param name="sender"></param>
  84. /// <param name="e"></param>
  85. private void AdsClient_ConnectionStateChanged(object sender, TwinCAT.ConnectionStateChangedEventArgs e)
  86. {
  87. LOG.WriteLog(eEvent.INFO_TWINCAT, "System", $"Twincat connect{_cfg.Controller.IPAddress}:{_cfg.Controller.PortAddress} stated changed from {e.OldState} to {e.NewState}");
  88. if (e.NewState==TwinCAT.ConnectionState.Connected)
  89. {
  90. try
  91. {
  92. StateInfo stateInfo = _adsClient.ReadState();
  93. CreateWriteHandle();
  94. SubscribeNotification();
  95. _isConnected = true;
  96. BeckhoffAxisManager.Instance.StartCoeInterface();
  97. }
  98. catch(Exception ex)
  99. {
  100. _isConnected = false;
  101. LOG.WriteLog(eEvent.ERR_TWINCAT,"System",$"Twincat connect{_cfg.Controller.IPAddress}:{_cfg.Controller.PortAddress} error");
  102. return;
  103. }
  104. }
  105. else
  106. {
  107. _isConnected = false;
  108. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat connect{_cfg.Controller.IPAddress}:{_cfg.Controller.PortAddress} error");
  109. }
  110. }
  111. /// <summary>
  112. /// 启动
  113. /// </summary>
  114. public void Start()
  115. {
  116. try
  117. {
  118. _adsClient.Connect(_ipAddress, _port);
  119. }
  120. catch
  121. {
  122. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat connect{_cfg.Controller.IPAddress}:{_cfg.Controller.PortAddress} error");
  123. }
  124. }
  125. /// <summary>
  126. /// 订阅变量
  127. /// </summary>
  128. private void SubscribeNotification()
  129. {
  130. _notificationNameHandleDic.Clear();
  131. _handleItemDic.Clear();
  132. int count = 0;
  133. List<BeckhoffItem> beckhoffItems = BeckhoffItemManager.Instance.GetIOItems();
  134. foreach(BeckhoffItem item in beckhoffItems)
  135. {
  136. try
  137. {
  138. int handle = _adsClient.AddDeviceNotification(item.Address, _adsStream, count, item.Size, AdsTransMode.OnChange, 0, 0, item);
  139. _notificationNameHandleDic[item.Name] = handle;
  140. _handleItemDic[handle] = item;
  141. count += item.Size;
  142. }
  143. catch(Exception ex)
  144. {
  145. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat add variable {item.Name} error");
  146. }
  147. }
  148. }
  149. /// <summary>
  150. /// 创建写入句柄
  151. /// </summary>
  152. private void CreateWriteHandle()
  153. {
  154. _writeNameHandleDic.Clear();
  155. foreach(BeckhoffItem item in BeckhoffItemManager.Instance.GetWriteItems())
  156. {
  157. try
  158. {
  159. int handle = _adsClient.CreateVariableHandle(item.Address);
  160. _writeNameHandleDic[item.Name] = handle;
  161. }
  162. catch
  163. {
  164. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat create variable handle {item.Name} error");
  165. }
  166. }
  167. }
  168. /// <summary>
  169. /// 写入数值
  170. /// </summary>
  171. /// <param name="name"></param>
  172. /// <param name="value"></param>
  173. /// <returns></returns>
  174. public bool WriteValue(string name,object value)
  175. {
  176. if(_writeNameHandleDic.ContainsKey(name))
  177. {
  178. if(!_isConnected)
  179. {
  180. LOG.WriteLog(eEvent.ERR_TWINCAT,"System", $"Twincat connected failed, write variable {name} error");
  181. return false;
  182. }
  183. int handle = _writeNameHandleDic[name];
  184. BeckhoffItem item = BeckhoffItemManager.Instance.GetIOBeckhoffItem(name);
  185. object convertedValue = value;
  186. try
  187. {
  188. if (item != null && item.BitOperated)
  189. {
  190. if (item.Invert && convertedValue is bool)
  191. {
  192. convertedValue = !(bool)convertedValue;
  193. }
  194. lock (_bitOperatedLocker)
  195. {
  196. convertedValue = GetBeckoffItemValue(item, convertedValue);
  197. _adsClient.WriteAny(handle, convertedValue);
  198. _bitOperatedAddressValueDic[item.Address] = (byte)convertedValue;
  199. }
  200. }
  201. else
  202. {
  203. _adsClient.WriteAny(handle, convertedValue);
  204. }
  205. LOG.WriteLog(eEvent.INFO_TWINCAT, "System", $"Twincat write variable {name} value {convertedValue}");
  206. return true;
  207. }
  208. catch(Exception ex)
  209. {
  210. LOG.WriteLog(eEvent.ERR_TWINCAT,"System", $"Twincat write variable {name} error {ex.Message}");
  211. return false;
  212. }
  213. }
  214. else
  215. {
  216. LOG.WriteLog(eEvent.ERR_TWINCAT,"System", $"Twincat doesnot has {name} variable");
  217. }
  218. return false;
  219. }
  220. /// <summary>
  221. /// 获取Beckhoff项数值(用于解决BitOperated为true)
  222. /// </summary>
  223. /// <param name="name"></param>
  224. /// <param name="value"></param>
  225. /// <returns></returns>
  226. private object GetBeckoffItemValue(BeckhoffItem item,object value)
  227. {
  228. if (_bitOperatedAddressValueDic.ContainsKey(item.Address))
  229. {
  230. byte addressValue = _bitOperatedAddressValueDic[item.Address];
  231. bool[] boolArray = Converter.GetboolArrayByByte(addressValue);
  232. bool boolValue = (bool)value;
  233. if (item.Bit < boolArray.Length)
  234. {
  235. boolArray[item.Bit] = boolValue;
  236. }
  237. byte byt = Converter.GetByteValueByBoolArray(boolArray);
  238. return byt;
  239. }
  240. else
  241. {
  242. return value;
  243. }
  244. }
  245. /// <summary>
  246. /// 变量数值发生变化事件
  247. /// </summary>
  248. /// <param name="sender"></param>
  249. /// <param name="e"></param>
  250. private void AdsClient_AdsNotification(object sender, AdsNotificationEventArgs e)
  251. {
  252. try
  253. {
  254. BeckhoffItem item = null;
  255. if (_handleItemDic.ContainsKey(e.NotificationHandle))
  256. {
  257. item = _handleItemDic[e.NotificationHandle];
  258. }
  259. else
  260. {
  261. item = (BeckhoffItem)e.UserData;
  262. }
  263. e.DataStream.Position = e.Offset;
  264. if (item != null)
  265. {
  266. switch (item.IoType)
  267. {
  268. case "di":
  269. BeckhoffDIAccessor diAccessor = BeckhoffIOManager.Instance.GetDIAccessor(item.Name);
  270. if (diAccessor != null)
  271. {
  272. diAccessor.Value = _reader.ReadBoolean();
  273. if (item.Invert)
  274. {
  275. IOModuleManager.Instance.UpdateIoValue(item.Name, !diAccessor.Value);
  276. }
  277. else
  278. {
  279. IOModuleManager.Instance.UpdateIoValue(item.Name, diAccessor.Value);
  280. }
  281. }
  282. break;
  283. case "do":
  284. BeckhoffDOAccessor doAccessor = BeckhoffIOManager.Instance.GetDOAccessor(item.Name);
  285. if (doAccessor != null)
  286. {
  287. if (item.BitOperated)
  288. {
  289. byte byt = _reader.ReadByte();
  290. lock (_bitOperatedLocker)
  291. {
  292. _bitOperatedAddressValueDic[doAccessor.Address] = byt;
  293. }
  294. doAccessor.Value = ((byt >> item.Bit) & 0x01) == 0x01;
  295. }
  296. else
  297. {
  298. doAccessor.Value = _reader.ReadBoolean();
  299. }
  300. if (item.Invert)
  301. {
  302. IOModuleManager.Instance.UpdateIoValue(item.Name, !doAccessor.Value);
  303. }
  304. else
  305. {
  306. IOModuleManager.Instance.UpdateIoValue(item.Name, doAccessor.Value);
  307. }
  308. }
  309. break;
  310. case "ai":
  311. BeckhoffAIAccessor aiAccessor = BeckhoffIOManager.Instance.GetAIAccessor(item.Name);
  312. if (aiAccessor != null)
  313. {
  314. double twincatValue = GetAnalogValue(item.DataType);
  315. var result = ScalingManager.Instance.CalculateValueByTwincatVariable(item.Name, twincatValue);
  316. if (result.Item1)
  317. {
  318. aiAccessor.Value = result.Item2;
  319. }
  320. else
  321. {
  322. aiAccessor.Value = twincatValue;
  323. }
  324. IOModuleManager.Instance.UpdateIoValue(item.Name, aiAccessor.Value);
  325. }
  326. break;
  327. case "ao":
  328. BeckhoffAOAccessor aoAccessor = BeckhoffIOManager.Instance.GetAOAccesssor(item.Name);
  329. if (aoAccessor != null)
  330. {
  331. double twincatValue = GetAnalogValue(item.DataType);
  332. var result = ScalingManager.Instance.CalculateValueByTwincatVariable(item.Name, twincatValue);
  333. if (result.Item1)
  334. {
  335. aoAccessor.Value = result.Item2;
  336. }
  337. else
  338. {
  339. aoAccessor.Value = twincatValue;
  340. }
  341. IOModuleManager.Instance.UpdateIoValue(item.Name, aoAccessor.Value);
  342. }
  343. break;
  344. case "axis":
  345. object itemValue = GetDataTypeValue(item.DataType);
  346. if (item.Invert)
  347. {
  348. bool boolValue = (bool)itemValue;
  349. BeckhoffAxisManager.Instance.SetAxisValue(item.Name, !boolValue);
  350. }
  351. else
  352. {
  353. BeckhoffAxisManager.Instance.SetAxisValue(item.Name, itemValue);
  354. }
  355. break;
  356. case "counter":
  357. if (item.Invert)
  358. {
  359. object counterItemValue = GetDataTypeValue(item.DataType);
  360. bool boolValue = (bool)counterItemValue;
  361. BeckhoffCounterManager.Instance.SetCounterValue(item.Name, !boolValue);
  362. }
  363. else
  364. {
  365. object counterItemValue = GetDataTypeValue(item.DataType);
  366. BeckhoffCounterManager.Instance.SetCounterValue(item.Name, counterItemValue);
  367. }
  368. break;
  369. }
  370. }
  371. }
  372. catch(Exception ex)
  373. {
  374. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", ex.Message);
  375. }
  376. }
  377. /// <summary>
  378. /// 获取模拟数量数值
  379. /// </summary>
  380. /// <param name="dataType"></param>
  381. /// <returns></returns>
  382. private double GetAnalogValue(string dataType)
  383. {
  384. return double.Parse(GetDataTypeValue(dataType).ToString());
  385. }
  386. /// <summary>
  387. /// 获取数据类型数值
  388. /// </summary>
  389. /// <param name="dataType"></param>
  390. /// <returns></returns>
  391. private object GetDataTypeValue(string dataType)
  392. {
  393. switch (dataType)
  394. {
  395. case "byte":
  396. return _reader.ReadByte();
  397. case "sint":
  398. return _reader.ReadSByte();
  399. case "usint":
  400. return _reader.ReadByte();
  401. case "short":
  402. return _reader.ReadInt16();
  403. case "int":
  404. return _reader.ReadInt16();
  405. case "uint":
  406. return _reader.ReadUInt16();
  407. case "dint":
  408. return _reader.ReadInt32();
  409. case "udint":
  410. return _reader.ReadUInt32();
  411. case "long":
  412. return _reader.ReadInt64();
  413. case "float":
  414. return _reader.ReadSingle();
  415. case "ulong":
  416. return _reader.ReadUInt64();
  417. case "double":
  418. return _reader.ReadDouble();
  419. case "bool":
  420. return _reader.ReadBoolean();
  421. default:
  422. return _reader.ReadDouble();
  423. }
  424. }
  425. /// <summary>
  426. /// 停止
  427. /// </summary>
  428. public void Stop()
  429. {
  430. _adsClient.Dispose();
  431. }
  432. #region 支持写入结构体
  433. /* T必须字段必须为连续地址,
  434. * [StructLayout(LayoutKind.Sequential)]
  435. public class Tag
  436. {
  437. [MarshalAs(UnmanagedType.I1)]
  438. public bool DO_PVN21;
  439. [MarshalAs(UnmanagedType.I1)]
  440. public bool DO_PV11;
  441. [MarshalAs(UnmanagedType.R4)]
  442. public float AI_Chamber_Pressure_10t;
  443. }
  444. * */
  445. /// <summary>
  446. /// 写入类
  447. /// </summary>
  448. /// <typeparam name="T"></typeparam>
  449. /// <param name="name"></param>
  450. /// <param name="data"></param>
  451. /// <returns></returns>
  452. public (bool success, int status) WriteStruct<T>(string name, T data)
  453. {
  454. if (_writeNameHandleDic.ContainsKey(name))
  455. {
  456. if (!_isConnected)
  457. {
  458. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat connected failed, write variable {name} error");
  459. return (false, 0);
  460. }
  461. try
  462. {
  463. int handle = _writeNameHandleDic[name];
  464. _adsClient.WriteAny(handle, data);
  465. LOG.WriteLog(eEvent.INFO_TWINCAT, "System", $"Twincat write variable {name} value {data}");
  466. return (true, 0);
  467. }
  468. catch (Exception ex)
  469. {
  470. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat write variable {name} error {ex.Message}");
  471. return (false, 1);
  472. }
  473. }
  474. else
  475. {
  476. LOG.WriteLog(eEvent.ERR_TWINCAT, "System", $"Twincat doesnot has {name} variable");
  477. return (false, 0);
  478. }
  479. }
  480. #endregion
  481. }
  482. }