C# 和 OPC UA 服务器通信的代码
时间: 2023-11-09 21:05:55 浏览: 211
以下是使用C#语言和OPC UA协议进行服务器通信的示例代码:
```csharp
using Opc.Ua;
using Opc.Ua.Client;
// 创建一个UA TCP连接
var endpointUrl = "opc.tcp://localhost:62541/Quickstarts/ReferenceServer";
var endpoint = new EndpointDescription(endpointUrl);
var config = EndpointConfiguration.Create();
var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl, false);
var endpointConfiguration = EndpointConfiguration.Create(config);
var session = Session.Create(
endpointConfiguration,
new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration),
false,
"",
60000,
new UserIdentity(new AnonymousIdentityToken()),
null).Result;
// 读取一个节点的值
var nodeToRead = new ReadValueId
{
NodeId = new NodeId("ns=2;s=Machine_1/Status"),
AttributeId = Attributes.Value
};
var readRequest = new ReadRequest
{
NodesToRead = new[] { nodeToRead }
};
var readResponse = session.Read(null, readRequest).Result;
if (readResponse.Results[0].StatusCode == StatusCodes.Good)
{
var value = readResponse.Results[0].GetValueOrDefault<string>();
Console.WriteLine($"The status of Machine_1 is: {value}");
}
// 写一个节点的值
var nodeToWrite = new WriteValue
{
NodeId = new NodeId("ns=2;s=Machine_1/TargetSpeed"),
AttributeId = Attributes.Value,
Value = new DataValue(50)
};
var writeRequest = new WriteRequest
{
NodesToWrite = new[] { nodeToWrite }
};
var writeResponse = session.Write(null, writeRequest).Result;
if (writeResponse.Results[0].StatusCode == StatusCodes.Good)
{
Console.WriteLine("The target speed of Machine_1 has been set to 50.");
}
// 关闭连接
session.Close();
```
以上代码使用了Opc.Ua.Client库来创建连接、读写节点值,并且使用了异步方法来处理请求和响应。请注意,需要安装Opc.Ua.Core和Opc.Ua.Client NuGet包来使用这个库。
阅读全文