• C#使用UA-.NETStandard开发OPC UA客户端


    OpcUa作为客户端测试代码

    1、打开服务端,使用开源代码GitHub - OPCFoundation/UA-.NETStandard: OPC Unified Architecture .NET Standard中Quickstarts.ReferenceServer启动服务端

    2、运行打印结果如下

    1. 测试标准OPC UA
    2. Session_KeepAlive
    3. 2023/9/27 21:09:39Connected, loading complex type system.
    4. ReadNode查询到这个Node的属性
    5. data value : 55

    3、测试启动

    MyOpcUaServer myOpcUaServer = new MyOpcUaServer();

    4、连接服务端测试类,引用NuGet:OPCFoundation.NetStandard.Opc.Ua

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. using System.Windows.Forms;
    7. using Microsoft.Extensions.Configuration;
    8. using Opc.Ua;
    9. using Opc.Ua.Client;
    10. using Opc.Ua.Client.ComplexTypes;
    11. using Org.BouncyCastle.Asn1.X509;
    12. namespace 标准OPC_UA
    13. {
    14. internal class MyOpcUaClient
    15. {
    16. public string OpcUaName = "My Opc ua";
    17. private ApplicationConfiguration m_configuration;
    18. private Session m_session;
    19. private SessionReconnectHandler m_reconnectHandler;
    20. private CertificateValidationEventHandler m_CertificateValidation;
    21. //private Dictionary<Uri, EndpointDescription> m_endpoints;
    22. public MyOpcUaClient(string uri = "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer", bool useSecurity = false, int sessionTimeout = 1000) {
    23. InitConfiguration();
    24. // 连接测试
    25. Connect(uri, useSecurity, sessionTimeout);
    26. //Read();
    27. ConfiguredEndpointCollection configuredEndpoints = new ConfiguredEndpointCollection();
    28. List<ConfiguredEndpoint> list = configuredEndpoints.GetEndpoints("opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer");
    29. if (m_session != null)
    30. {
    31. // 读取属性和值
    32. Node node = m_session.ReadNode("ns=7;s=Alarms.AnalogSource");
    33. if (node != null)
    34. {
    35. Console.WriteLine("ReadNode查询到这个Node的属性");
    36. }
    37. WriteValueCollection nodesToWrite = new WriteValueCollection();
    38. WriteValue writeValue = new WriteValue();
    39. writeValue.NodeId = "ns=7;s=Alarms.AnalogSource"; // 看下属性是否是可写
    40. writeValue.AttributeId = 13u; // 不定义无法正常设置
    41. writeValue.Value = new DataValue(new Variant(55)); // 设置值
    42. nodesToWrite.Add(writeValue);
    43. StatusCodeCollection statusCodes = new StatusCodeCollection();
    44. DiagnosticInfoCollection diagnosticInfos = new DiagnosticInfoCollection();
    45. ResponseHeader rep = m_session.Write(null, nodesToWrite, out statusCodes, out diagnosticInfos);
    46. DataValue value = m_session.ReadValue("ns=7;s=Alarms.AnalogSource");
    47. if(value != null)
    48. {
    49. Console.WriteLine("data value : " + value.ToString());
    50. }
    51. }
    52. //TranslateBrowsePathsToNodeIds();
    53. }
    54. void InitConfiguration()
    55. {
    56. var certificateValidator = new CertificateValidator();
    57. certificateValidator.CertificateValidation += (sender, eventArgs) =>
    58. {
    59. if (ServiceResult.IsGood(eventArgs.Error))
    60. eventArgs.Accept = true;
    61. else if (eventArgs.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)
    62. eventArgs.Accept = true;
    63. else
    64. throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", eventArgs.Error.Code, eventArgs.Error.AdditionalInfo));
    65. };
    66. SecurityConfiguration securityConfigurationcv = new SecurityConfiguration
    67. {
    68. AutoAcceptUntrustedCertificates = true,
    69. RejectSHA1SignedCertificates = false,
    70. MinimumCertificateKeySize = 1024,
    71. };
    72. certificateValidator.Update(securityConfigurationcv);
    73. // Build the application configuration
    74. var configuration = new ApplicationConfiguration
    75. {
    76. ApplicationName = OpcUaName,
    77. ApplicationType = ApplicationType.Client,
    78. CertificateValidator = certificateValidator,
    79. ApplicationUri = "urn:MyClient", //Kepp this syntax
    80. ProductUri = "OpcUaClient",
    81. ServerConfiguration = new ServerConfiguration
    82. {
    83. MaxSubscriptionCount = 100000,
    84. MaxMessageQueueSize = 1000000,
    85. MaxNotificationQueueSize = 1000000,
    86. MaxPublishRequestCount = 10000000,
    87. },
    88. SecurityConfiguration = new SecurityConfiguration
    89. {
    90. AutoAcceptUntrustedCertificates = true,
    91. RejectSHA1SignedCertificates = false,
    92. MinimumCertificateKeySize = 1024,
    93. SuppressNonceValidationErrors = true,
    94. ApplicationCertificate = new CertificateIdentifier
    95. {
    96. StoreType = CertificateStoreType.X509Store,
    97. StorePath = "CurrentUser\\My",
    98. SubjectName = OpcUaName,
    99. },
    100. TrustedIssuerCertificates = new CertificateTrustList
    101. {
    102. StoreType = CertificateStoreType.X509Store,
    103. StorePath = "CurrentUser\\Root",
    104. },
    105. TrustedPeerCertificates = new CertificateTrustList
    106. {
    107. StoreType = CertificateStoreType.X509Store,
    108. StorePath = "CurrentUser\\Root",
    109. }
    110. },
    111. TransportQuotas = new TransportQuotas
    112. {
    113. OperationTimeout = 6000000,
    114. MaxStringLength = int.MaxValue,
    115. MaxByteStringLength = int.MaxValue,
    116. MaxArrayLength = 65535,
    117. MaxMessageSize = 419430400,
    118. MaxBufferSize = 65535,
    119. ChannelLifetime = -1,
    120. SecurityTokenLifetime = -1
    121. },
    122. ClientConfiguration = new ClientConfiguration
    123. {
    124. DefaultSessionTimeout = -1,
    125. MinSubscriptionLifetime = -1,
    126. },
    127. DisableHiResClock = true
    128. };
    129. configuration.Validate(ApplicationType.Client);
    130. m_configuration = configuration;
    131. }
    132. async void Connect(string uri = "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer", bool useSecurity = false, int sessionTimeout = 1000)
    133. {
    134. if (m_session != null)
    135. {
    136. m_session.KeepAlive -= Session_KeepAlive;
    137. m_session.Close(10000);
    138. m_session = null;
    139. }
    140. // select the best endpoint.
    141. var endpointDescription = CoreClientUtils.SelectEndpoint(m_configuration, uri, useSecurity, sessionTimeout);
    142. var endpointConfiguration = EndpointConfiguration.Create(m_configuration);
    143. var endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration);
    144. m_session = await Session.Create(
    145. m_configuration,
    146. //connection,
    147. endpoint,
    148. false,
    149. //true, //DisableDomainCheck
    150. "Quickstart Reference Client", //(String.IsNullOrEmpty(SessionName)) ? m_configuration.ApplicationName : SessionName,
    151. (uint)sessionTimeout,
    152. null, //UserIdentity,
    153. null); //PreferredLocales
    154. // set up keep alive callback.
    155. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive);
    156. // set up reconnect handler.
    157. m_reconnectHandler = new SessionReconnectHandler(true, 10 * 1000);
    158. try
    159. {
    160. Console.WriteLine(DateTime.Now + "Connected, loading complex type system.");
    161. var typeSystemLoader = new ComplexTypeSystem(m_session);
    162. await typeSystemLoader.Load();
    163. }
    164. catch (Exception e)
    165. {
    166. Console.WriteLine(DateTime.Now + "Connected, failed to load complex type system.");
    167. Utils.LogError(e, "Failed to load complex type system.");
    168. }
    169. }
    170. bool Read()
    171. {
    172. DataValueCollection dataValues = new DataValueCollection();
    173. DiagnosticInfoCollection diagnosticInfos = new DiagnosticInfoCollection();
    174. ResponseHeader resp = m_session.Read(null, 0, TimestampsToReturn.Both, null, out dataValues, out diagnosticInfos);
    175. return true;
    176. }
    177. void TranslateBrowsePathsToNodeIds()
    178. //RequestHeader requestHeader,
    179. //BrowsePathCollection browsePaths)
    180. //out BrowsePathResultCollection results,
    181. //out DiagnosticInfoCollection diagnosticInfos)
    182. {
    183. //m_session.TranslateBrowsePathsToNodeIds(null, "opc.tcp://lplsszsz4435n:62541/Quickstarts/ReferenceServer");
    184. BrowsePathResultCollection results;
    185. DiagnosticInfoCollection diagnosticInfos;
    186. var startNodeId = new NodeId(Objects.ObjectsFolder);
    187. var browsePaths1 = new BrowsePathCollection
    188. {
    189. new BrowsePath
    190. {
    191. RelativePath = RelativePath.Parse("Objects", m_session.TypeTree, m_session.NamespaceUris, m_session.NamespaceUris),
    192. StartingNode = startNodeId
    193. }
    194. };
    195. ResponseHeader resp = m_session.TranslateBrowsePathsToNodeIds(null, browsePaths1, out results, out diagnosticInfos);
    196. }
    197. private void ChangeSession(Session session, bool refresh)
    198. {
    199. //m_session = session;
    200. //if (AttributesControl != null)
    201. //{
    202. // AttributesControl.ChangeSession(session);
    203. //}
    204. //BrowseTV.Nodes.Clear();
    205. //if (m_session != null)
    206. //{
    207. // INode node = m_session.NodeCache.Find(m_rootId);
    208. // if (node != null)
    209. // {
    210. // TreeNode root = new TreeNode(node.ToString());
    211. // root.ImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, false);
    212. // root.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, true);
    213. // ReferenceDescription reference = new ReferenceDescription();
    214. // reference.NodeId = node.NodeId;
    215. // reference.NodeClass = node.NodeClass;
    216. // reference.BrowseName = node.BrowseName;
    217. // reference.DisplayName = node.DisplayName;
    218. // reference.TypeDefinition = node.TypeDefinitionId;
    219. // root.Tag = reference;
    220. // root.Nodes.Add(new TreeNode());
    221. // BrowseTV.Nodes.Add(root);
    222. // root.Expand();
    223. // BrowseTV.SelectedNode = root;
    224. // }
    225. //}
    226. }
    227. private void Session_KeepAlive(ISession session, KeepAliveEventArgs e)
    228. {
    229. Console.WriteLine("Session_KeepAlive");
    230. }
    231. }
    232. }

  • 相关阅读:
    实习打怪之路:JS中检测数据类型的方法
    触发器,寄存器,三态输出电路
    2024.7.31 Spyglass lint tcl 使用总结
    基于JavaSwing进销存管理系统的设计与实现
    mysql-集群-二进制部署
    一、前端开发
    Linux之shell条件测试
    shiro-第一篇-基本介绍及使用
    java毕业生设计员工婚恋交友平台计算机源码+系统+mysql+调试部署+lw
    APP网站如何防止短信验证码接口被攻击
  • 原文地址:https://blog.csdn.net/qq_17242837/article/details/133363979