OPCCommunication.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. using System;
  2. using System.ComponentModel;
  3. using System.Threading.Tasks;
  4. using Newtonsoft.Json;
  5. using TeamAAS.Communication.Attributes;
  6. using TeamAAS.Communication.Base;
  7. using TeamAAS.Communication.Interfaces;
  8. namespace TeamAAS.Communication.Devices
  9. {
  10. //[Communication("OPC UA", "工业协议", "OPC 统一架构客户端(官方 OPC UA .NET 库)")]
  11. //public class OPCCommunication : BindableCommunicationBase
  12. //{
  13. // [JsonIgnore] private ISessionClientMethods _session;
  14. // [JsonIgnore] private bool _connected;
  15. // public override string TypeKey => typeof(OPCCommunication).FullName;
  16. // private string _endpointUrl = "opc.tcp://localhost:4840";
  17. // [Category("II.连接配置"), DisplayName("端点 URL"), Description("OPC UA 服务器地址,如 opc.tcp://localhost:4840")]
  18. // public override string EndpointUrl
  19. // {
  20. // get => _endpointUrl;
  21. // set => SetProperty(ref _endpointUrl, value);
  22. // }
  23. // private string _userName = "";
  24. // [Category("II.连接配置"), DisplayName("用户名"), Description("空则匿名")]
  25. // public string UserName
  26. // {
  27. // get => _userName;
  28. // set => SetProperty(ref _userName, value);
  29. // }
  30. // private string _password = "";
  31. // [Category("II.连接配置"), DisplayName("密码")]
  32. // [PasswordPropertyText]
  33. // public string Password
  34. // {
  35. // get => _password;
  36. // set => SetProperty(ref _password, value);
  37. // }
  38. // private int _timeout = 5000;
  39. // [Category("II.连接配置"), DisplayName("超时(ms)")]
  40. // public int Timeout
  41. // {
  42. // get => _timeout;
  43. // set => SetProperty(ref _timeout, value);
  44. // }
  45. // [JsonIgnore, Browsable(false)]
  46. // public override bool IsConnected => _connected;
  47. // public override event Action<object, bool> ConnectChangedEvent;
  48. // public override event Action<object, string> DataReceivedEvent;
  49. // public OPCCommunication() { }
  50. // public override void Connect()
  51. // {
  52. // try
  53. // {
  54. // Disconnect();
  55. // if (string.IsNullOrWhiteSpace(EndpointUrl))
  56. // throw new InvalidOperationException("OPC UA 端点 URL 不能为空。");
  57. // var config = new ApplicationConfiguration
  58. // {
  59. // ApplicationName = "TeamAAS.OpcUaClient",
  60. // ApplicationType = ApplicationType.Client,
  61. // TransportQuotas = new TransportQuotas { OperationTimeout = Timeout },
  62. // ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }
  63. // };
  64. // var endpointDesc = CoreClientUtils.SelectEndpoint(EndpointUrl, false);
  65. // if (endpointDesc == null)
  66. // throw new InvalidOperationException("未发现可用的 OPC UA 端点。");
  67. // var endpoint = new ConfiguredEndpoint(null, endpointDesc, EndpointConfiguration.Create(config));
  68. // var factory = (ISessionFactory)Activator.CreateInstance(typeof(DefaultSessionFactory), true);
  69. // _session = factory.Create(config, null, endpoint, null, null, null);
  70. // IUserIdentity identity;
  71. // if (string.IsNullOrWhiteSpace(UserName))
  72. // identity = new UserIdentity(new AnonymousIdentityToken());
  73. // else
  74. // identity = new UserIdentity(UserName, Password);
  75. // var userIdentityToken = new ExtensionObject(identity.GetIdentityToken());
  76. // _session.ActivateSession(null, null, null, null, userIdentityToken, null, out _, out _, out _);
  77. // _connected = true;
  78. // ConnectChangedEvent?.Invoke(this, true);
  79. // Notify(nameof(IsConnected));
  80. // AppendLog($"已连接 {EndpointUrl}");
  81. // }
  82. // catch (Exception ex)
  83. // {
  84. // Disconnect();
  85. // throw new InvalidOperationException("OPC UA 连接失败: " + ex.Message, ex);
  86. // }
  87. // }
  88. // public override Task ConnectAsync() => Task.Run(() => Connect());
  89. // public override void Disconnect()
  90. // {
  91. // _connected = false;
  92. // try
  93. // {
  94. // if (_session != null)
  95. // _session.CloseSession(null, true);
  96. // }
  97. // catch { }
  98. // _session = null;
  99. // ConnectChangedEvent?.Invoke(this, false);
  100. // Notify(nameof(IsConnected));
  101. // }
  102. // public override void Dispose() => Disconnect();
  103. // private NodeId ParseNodeId(string address)
  104. // {
  105. // if (string.IsNullOrWhiteSpace(address))
  106. // throw new ArgumentException("NodeId 不能为空。", nameof(address));
  107. // var trimmed = address.Trim();
  108. // if (trimmed.StartsWith("ns=", StringComparison.OrdinalIgnoreCase) ||
  109. // trimmed.StartsWith("s=", StringComparison.OrdinalIgnoreCase) ||
  110. // trimmed.StartsWith("i=", StringComparison.OrdinalIgnoreCase))
  111. // {
  112. // return new NodeId(trimmed);
  113. // }
  114. // return new NodeId("s=" + trimmed);
  115. // }
  116. // public override object ReadValue(string address)
  117. // {
  118. // if (_session == null || !_connected)
  119. // throw new InvalidOperationException("OPC UA 尚未连接。");
  120. // var nodeId = ParseNodeId(address);
  121. // var nodesToRead = new ReadValueIdCollection
  122. // {
  123. // new ReadValueId { NodeId = nodeId, AttributeId = Opc.Ua.Attributes.Value }
  124. // };
  125. // _session.Read(null, 0.0, TimestampsToReturn.Neither, nodesToRead,
  126. // out var dataValues, out _);
  127. // if (dataValues != null && dataValues.Count > 0 && StatusCode.IsGood(dataValues[0].StatusCode))
  128. // return dataValues[0].Value;
  129. // throw new InvalidOperationException($"读取节点 {address} 失败");
  130. // }
  131. // public override Task<object> ReadValueAsync(string address) => Task.Run(() => ReadValue(address));
  132. // public override void WriteValue(string address, object value)
  133. // {
  134. // if (_session == null || !_connected)
  135. // throw new InvalidOperationException("OPC UA 尚未连接。");
  136. // if (value == null)
  137. // throw new ArgumentNullException(nameof(value));
  138. // var nodeId = ParseNodeId(address);
  139. // var nodesToWrite = new WriteValueCollection
  140. // {
  141. // new WriteValue
  142. // {
  143. // NodeId = nodeId,
  144. // AttributeId = Opc.Ua.Attributes.Value,
  145. // Value = new DataValue(new Variant(value))
  146. // }
  147. // };
  148. // _session.Write(null, nodesToWrite, out var results, out _);
  149. // if (results != null && results.Count > 0 && !StatusCode.IsGood(results[0]))
  150. // throw new InvalidOperationException($"写入节点 {address} 失败: {results[0]}");
  151. // }
  152. // public override Task WriteValueAsync(string address, object value) => Task.Run(() => WriteValue(address, value));
  153. //}
  154. }