AdsCommunicator.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. using Log;
  2. using ProtocalGeneral;
  3. using System.Collections.Concurrent;
  4. using TwinCAT.Ads.SumCommand;
  5. using TwinCAT.TypeSystem;
  6. namespace AdsCommunicatorNet8;
  7. //this Implementation has removed notification function, only get value and set value available
  8. public class AdsCommunicator(ILog log) : IDisposable
  9. {
  10. private bool _isConnected;
  11. private string? _netID = null;
  12. private int _port = 0;
  13. private AdsClient? _adsClient;
  14. private List<string[]>? _adsCsvInfo;
  15. private ITcpConnectNority? _connectionNotify;
  16. private bool disposedValue;
  17. private readonly ConcurrentDictionary<string, IAdsSymbol> _symbols = [];
  18. public bool IsConnected { get { return _isConnected; } }
  19. public bool Initialize(ITcpConnectNority connectionNotify)
  20. {
  21. if (this._adsClient is not null)
  22. return false;
  23. this._adsClient = new AdsClient();
  24. this._adsCsvInfo = [];
  25. this._connectionNotify = connectionNotify;
  26. return true;
  27. }
  28. public bool Open(string netID, int port, int retry=10)
  29. {
  30. log?.Info($"Try Open {netID} {port}");
  31. if (this._adsClient is null)
  32. {
  33. log?.Warning("Not initialized before Open");
  34. return false;
  35. }
  36. if (this._adsClient.IsConnected)
  37. {
  38. log?.Warning($"Ads {netID} {port} already connected");
  39. return false;
  40. }
  41. this._adsClient.ConnectionStateChanged += AdsClient_ConnectionStateChanged;
  42. for (int i = 1; i <= retry; i++)
  43. {
  44. log?.Info($"Try Connected {i}");
  45. try
  46. {
  47. this._adsClient.Connect(netID, port);
  48. if (this._adsClient.TryReadState(out _) == AdsErrorCode.NoError)
  49. break;
  50. }
  51. catch
  52. {
  53. }
  54. if (i == retry)
  55. {
  56. log?.Error($"Reach Max Retry {i}, connect failed");
  57. return false;
  58. }
  59. Thread.Sleep(300);
  60. }
  61. this._netID = netID;
  62. this._port = port;
  63. log?.Info($"Connect success");
  64. this._isConnected = true;
  65. return true;
  66. }
  67. public bool ReConnect()
  68. {
  69. if (string.IsNullOrEmpty(this._netID) || this._port == 0)
  70. return false;
  71. this._adsClient ??= new();
  72. if (this._adsClient.IsConnected)
  73. return true;
  74. for (; ; )
  75. {
  76. log?.Info($"Try ReConnected");
  77. try
  78. {
  79. this._adsClient.Connect(_netID, _port);
  80. if (this._adsClient.TryReadState(out _) == AdsErrorCode.NoError)
  81. break;
  82. }
  83. catch
  84. {
  85. Thread.Sleep(300);
  86. }
  87. }
  88. return true;
  89. }
  90. public bool GetValue<T>(string symbolName, out T? value)
  91. {
  92. value = default;
  93. if (string.IsNullOrEmpty(symbolName))
  94. {
  95. log?.Warning("Symbol Empty");
  96. return false;
  97. }
  98. log?.Info($"Try get value {symbolName}");
  99. if (this._adsClient is null)
  100. {
  101. log?.Error("PLC not connected");
  102. return false;
  103. }
  104. if (!this._symbols.TryGetValue(symbolName, out IAdsSymbol? adsSymbol) || adsSymbol is null)
  105. {
  106. log?.Info($"{symbolName} not Created before try create symbol");
  107. if (this._adsClient.TryReadSymbol(symbolName, out adsSymbol) != AdsErrorCode.NoError || adsSymbol is null)
  108. {
  109. log?.Error($"{symbolName} not exist in PLC");
  110. return false;
  111. }
  112. this._symbols[symbolName] = adsSymbol;
  113. }
  114. try
  115. {
  116. value = (T)this._adsClient.ReadValue(adsSymbol);
  117. log?.Info($"{symbolName} value {value}");
  118. }
  119. catch (Exception ex)
  120. {
  121. log?.Error($"{symbolName} Read failed: {ex.Message}");
  122. return false;
  123. }
  124. return true;
  125. }
  126. public bool SetValue<T>(string symbolName, T value) where T : notnull
  127. {
  128. if (string.IsNullOrEmpty(symbolName))
  129. {
  130. log?.Warning("Set Value Symbol empty");
  131. return false;
  132. }
  133. log?.Info($"Try set value {symbolName}");
  134. if (this._adsClient is null)
  135. {
  136. log?.Error("PLC not connected");
  137. return false;
  138. }
  139. if (value is null)
  140. {
  141. log?.Warning("Value Empty");
  142. return false;
  143. }
  144. log?.Info($"Value {value}");
  145. if (!this._symbols.TryGetValue(symbolName, out IAdsSymbol? adsSymbol) || adsSymbol is null)
  146. {
  147. log?.Info($"{symbolName} not Created before try create symbol");
  148. if (this._adsClient.TryReadSymbol(symbolName, out adsSymbol) != AdsErrorCode.NoError || adsSymbol is null)
  149. {
  150. log?.Error($"{symbolName} not exist in PLC");
  151. return false;
  152. }
  153. this._symbols[symbolName] = adsSymbol;
  154. }
  155. try
  156. {
  157. this._adsClient.WriteValue(adsSymbol, value);
  158. log?.Info($"Set {symbolName} value {value} succeeded");
  159. }
  160. catch (Exception ex)
  161. {
  162. log?.Error($"{symbolName} Set failed: {ex.Message}");
  163. return false;
  164. }
  165. return true;
  166. }
  167. public bool SetBatchValue(IEnumerable<string> symbolCollection, IList<object> valueCollection)
  168. {
  169. if (this._adsClient is null)
  170. return false;
  171. if (symbolCollection is null || valueCollection is null)
  172. return false;
  173. if (symbolCollection.Count() != symbolCollection.Count())
  174. return false;
  175. List<ISymbol> symbols = [];
  176. foreach (var item in symbolCollection)
  177. {
  178. if (!this._symbols.TryGetValue(item, out IAdsSymbol? symbol) || symbol is null)
  179. {
  180. log?.Warning($"BatchSend: {item} not Registered before");
  181. return false;
  182. }
  183. symbols.Add(symbol);
  184. }
  185. SumSymbolWrite writes = new(this._adsClient, symbols);
  186. try
  187. {
  188. writes.Write([.. valueCollection]);
  189. }
  190. catch (Exception ex)
  191. {
  192. log?.Warning(ex.Message);
  193. return false;
  194. }
  195. return true;
  196. }
  197. private void AdsClient_ConnectionStateChanged(object? sender, TwinCAT.ConnectionStateChangedEventArgs e)
  198. {
  199. if (this._adsClient is null)
  200. return;
  201. log?.Info($"{e.NewState} {this._adsClient.Address.NetId} {this._adsClient.Address.Port}");
  202. switch (e.NewState)
  203. {
  204. case TwinCAT.ConnectionState.Connected:
  205. this._isConnected = true;
  206. this._connectionNotify?.Connect(this._adsClient.Address.NetId.ToString(), this._adsClient.Address.Port);
  207. break;
  208. case TwinCAT.ConnectionState.Disconnected:
  209. case TwinCAT.ConnectionState.Lost:
  210. default:
  211. this._isConnected = false;
  212. this._connectionNotify?.DisConnect(this._adsClient.Address.NetId.ToString(), this._adsClient.Address.Port);
  213. break;
  214. }
  215. }
  216. #region Dispose
  217. protected virtual void Dispose(bool disposing)
  218. {
  219. log?.Info("Disposing AdsCommunication");
  220. if (!disposedValue)
  221. {
  222. if (disposing)
  223. {
  224. this._adsClient?.Dispose();
  225. this._adsClient = null;
  226. this._adsCsvInfo?.Clear();
  227. }
  228. disposedValue = true;
  229. }
  230. }
  231. public void Dispose()
  232. {
  233. Dispose(disposing: true);
  234. GC.SuppressFinalize(this);
  235. }
  236. #endregion
  237. }