TwincatAdoManager.cs 23 KB

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