TwincatAdoManager.cs 14 KB

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