OpcUaClient.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Opc.Ua;
  9. using Opc.Ua.Client;
  10. using Siemens.OpcUA;
  11. using Subscription = Opc.Ua.Client.Subscription;
  12. namespace IMCS_CCS.Utils.DeviceProtocol
  13. {
  14. public class OpcUaClient : AProtocolBase
  15. {
  16. public OpcUaClient(ushort index)
  17. {
  18. mServer = new Server();
  19. namespaceIndex = index;
  20. mServer.CertificateEvent += m_Server_CertificateEvent;
  21. mServer.serverMessage += m_Server_serverMessage;
  22. }
  23. public override void ConnectAsync()
  24. {
  25. try
  26. {
  27. var task = Task.Run(() =>
  28. {
  29. if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(UserPassword))
  30. mServer.Connect(IpEndPort);
  31. else
  32. mServer.Connect(IpEndPort, UserName, UserPassword);
  33. });
  34. IsConnected = task.Wait(5000);
  35. }
  36. catch (Exception ex)
  37. {
  38. IsConnected = false;
  39. }
  40. finally
  41. {
  42. if (IsConnected)
  43. {
  44. mSession = mServer.Session;
  45. StartAlarmMonitor();
  46. }
  47. else
  48. mSession = null;
  49. }
  50. }
  51. public override void CloseConnect()
  52. {
  53. try
  54. {
  55. if (mAlarmMonitorItem == null)
  56. {
  57. mServer?.Disconnect();
  58. mSession = this.mServer?.Session;
  59. IsConnected = false;
  60. return;
  61. }
  62. this.mAlarmSubscription?.RemoveItem(this.mAlarmMonitorItem);
  63. this.mAlarmSubscription?.Delete(true);
  64. mAlarmSubscription?.Dispose();
  65. this.mAlarmSubscription = (Subscription)null;
  66. this.mAlarmMonitorItem = (MonitoredItem)null;
  67. mFilter = null;
  68. this.eventMonitorStart = false;
  69. mServer?.Disconnect();
  70. mSession = this.mServer?.Session;
  71. IsConnected = false;
  72. }
  73. catch (Exception ex)
  74. {
  75. IsConnected = false;
  76. }
  77. }
  78. public override object ReadData(int dataType, object dataParameter)
  79. {
  80. try
  81. {
  82. List<object> resultList = new List<object>();
  83. var dataAddress = dataParameter as List<string>;
  84. NodeIdCollection nodesToRead = new NodeIdCollection();
  85. if (dataAddress != null)
  86. foreach (var item in dataAddress)
  87. {
  88. var nodeId = new NodeId(item, namespaceIndex);
  89. nodesToRead.Add(nodeId);
  90. }
  91. mServer.ReadValues(nodesToRead, out var results);
  92. if (results.Any())
  93. {
  94. foreach (var value in results)
  95. {
  96. if (typeof(int[]) == value.Value.GetType())
  97. {
  98. resultList.Add(((int[])(value.Value))[1]);
  99. continue;
  100. }
  101. if (typeof(double[]) == value.Value.GetType())
  102. {
  103. resultList.Add(((double[])value.Value)[0]);
  104. continue;
  105. }
  106. if (typeof(UInt16[]) == value.Value.GetType())
  107. {
  108. resultList.Add(value.Value);
  109. continue;
  110. }
  111. resultList.Add(value?.Value);
  112. }
  113. }
  114. return resultList;
  115. }
  116. catch (Exception ex)
  117. {
  118. CloseConnect();
  119. return null;
  120. }
  121. }
  122. public override bool WriteData(object obj)
  123. {
  124. return false;
  125. }
  126. private string ReadFilesData(string valueStr)
  127. {
  128. string ncFileStream = "";
  129. if (mServer == null) return ncFileStream;
  130. try
  131. {
  132. DiagnosticInfoCollection diagnosticInfos = (DiagnosticInfoCollection)null;
  133. CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection();
  134. CallMethodResultCollection results = new CallMethodResultCollection();
  135. CallMethodRequest callMethodRequest = new CallMethodRequest();
  136. callMethodRequest.MethodId = new NodeId("/Methods/CopyFileFromServer", 2);
  137. callMethodRequest.ObjectId = new NodeId("/Methods", 2);
  138. callMethodRequest.InputArguments.Add((Opc.Ua.Variant)valueStr);
  139. methodsToCall.Add(callMethodRequest);
  140. RequestHeader requestHeader = new RequestHeader();
  141. mServer.Session.Call((RequestHeader)null, methodsToCall, out results, out diagnosticInfos);
  142. if (results.Count > 0) ncFileStream = Encoding.Default.GetString((byte[])results[0].OutputArguments[0].Value);
  143. return ncFileStream;
  144. }
  145. catch (Exception ex)
  146. {
  147. CloseConnect();
  148. return ncFileStream;
  149. }
  150. }
  151. #region Alarm Event
  152. private bool eventMonitorStart = false;
  153. private Subscription mAlarmSubscription;
  154. private Session mSession;
  155. private FilterDefinition mFilter;
  156. private MonitoredItem mAlarmMonitorItem;
  157. public override event MonitoredItemNotificationEventHandler OpcUaAlarmNotificationHandle;
  158. private void StartAlarmMonitor()
  159. {
  160. if (!this.eventMonitorStart)
  161. {
  162. try
  163. {
  164. if (this.mAlarmSubscription == null)
  165. {
  166. this.mAlarmSubscription = new Subscription
  167. {
  168. DisplayName = "AlarmSubscription",
  169. PublishingInterval = 1000,
  170. KeepAliveCount = 10U,
  171. LifetimeCount = 100U,
  172. MaxNotificationsPerPublish = 1000U,
  173. PublishingEnabled = true,
  174. TimestampsToReturn = TimestampsToReturn.Server
  175. };
  176. this.mSession?.AddSubscription(this.mAlarmSubscription);
  177. this.mFilter = new FilterDefinition
  178. {
  179. AreaId = new NodeId("Sinumerik", (ushort)2),
  180. Severity = EventSeverity.Min,
  181. IgnoreSuppressedOrShelved = true,
  182. EventTypes = (IList<NodeId>)new NodeId[1] { ObjectTypeIds.ConditionType }
  183. };
  184. this.mFilter.SelectClauses = this.mFilter.ConstructSelectClauses(this.mSession, ObjectTypeIds.ConditionType);
  185. }
  186. if (!mAlarmSubscription.Created) this.mAlarmSubscription.Create();
  187. this.mAlarmMonitorItem = this.mFilter.CreateMonitoredItem(this.mSession);
  188. this.mAlarmMonitorItem.DisplayName = "AlarmMonitorItem";
  189. this.mAlarmMonitorItem.Notification += new MonitoredItemNotificationEventHandler(this.Notification_MonitoredAlarm);
  190. this.mAlarmSubscription?.AddItem(this.mAlarmMonitorItem);
  191. this.mAlarmSubscription?.ApplyChanges();
  192. this.RefreshAlarmCall();
  193. this.eventMonitorStart = true;
  194. }
  195. catch (Exception ex)
  196. {
  197. }
  198. }
  199. }
  200. private void RefreshAlarmCall()
  201. {
  202. CallMethodRequestCollection methodsToCall = new CallMethodRequestCollection(1);
  203. CallMethodRequest callMethodRequest = new CallMethodRequest
  204. {
  205. ObjectId = new NodeId(ObjectTypeIds.ConditionType),
  206. MethodId = new NodeId(MethodIds.ConditionType_ConditionRefresh)
  207. };
  208. callMethodRequest.InputArguments.Add((Opc.Ua.Variant)this.mAlarmSubscription.Id);
  209. methodsToCall.Add(callMethodRequest);
  210. this.mSession.Call((RequestHeader)null, methodsToCall, out _, out _);
  211. }
  212. private void Notification_MonitoredAlarm(
  213. MonitoredItem monitoredItem,
  214. MonitoredItemNotificationEventArgs e)
  215. {
  216. try
  217. {
  218. EventFieldList notificationValue = e.NotificationValue as EventFieldList;
  219. if (notificationValue == null)
  220. return;
  221. lock (this)
  222. OpcUaAlarmNotificationHandle?.Invoke(monitoredItem, e);
  223. this.eventMonitorStart = true;
  224. }
  225. catch (Exception ex)
  226. {
  227. }
  228. }
  229. #endregion
  230. #region Props
  231. public override bool IsConnected { get; set; } = false;
  232. private readonly Server mServer;
  233. private readonly ushort namespaceIndex;
  234. public void Dispose()
  235. {
  236. Dispose(true);
  237. GC.SuppressFinalize(this);
  238. }
  239. private void m_Server_CertificateEvent(
  240. CertificateValidator validator,
  241. CertificateValidationEventArgs e)
  242. {
  243. e.Accept = true;
  244. }
  245. private void m_Server_serverMessage(string message)
  246. {
  247. }
  248. private void ReleaseUnmanagedResources()
  249. {
  250. CloseConnect();
  251. // TODO release unmanaged resources here
  252. }
  253. protected virtual void Dispose(bool disposing)
  254. {
  255. ReleaseUnmanagedResources();
  256. if (disposing)
  257. {
  258. }
  259. }
  260. ~OpcUaClient()
  261. {
  262. Dispose(false);
  263. }
  264. #endregion
  265. }
  266. }