OPC在自动化行业使用很广泛,好一点的PLC支持OPC协议,比如国内的汇川、禾川PLC对应高端的PLC都支持OPC UA协议,低端一点的则使用Modbus和上位机通讯,或者TCP自定义格式。相比于modbus协议,OPC不用确定寄存器地址,可以主动查询到OPC服务端对应的所有变量及属性,以object为根节点。
OPC在C#中开发使用客户端方法很多,可以自行搜索,如果OpcUaHelper等。作为服务端,可以使用github上OPC开源代码,也可以使用如下介绍的opc.uafx.advanced(使用简单)。
更多OPC介绍,参考我之前我的内容。
参考网站:OPC UA SDK for .NET - Client / Server in C# VB.NET schnell und einfach
NuGet添加引用:opc.uafx.advanced
服务端示例代码:https://docs.traeger.en/de/software/sdk/opc-ua/net/server.development.guide
客户端示例代码:Client Development Guide & Tutorial - TRAEGER Docs
客户端
using System;
using System.Threading;
using Opc.UaFx.Client;
public class Program
{
public static void Main()
{
using (var client = new OpcClient("opc.tcp://localhost:4840")) {
client.Connect();
while (true) {
var temperature = client.ReadNode("ns=2;s=Temperature");
Console.WriteLine("Current Temperature is {0} °C", temperature);
Thread.Sleep(1000);
}
}
}
}
服务端
using System.Threading;
using Opc.UaFx;
using Opc.UaFx.Server;
class Program
{
public static void Main()
{
var node = new OpcDataVariableNode<double>("Temperature", 100.0);
using (var server = new OpcServer("opc.tcp://localhost:4840/", node)) {
server.Start();
while (true) {
if (node.Value == 110)
node.Value = 100;
else
node.Value++;
node.ApplyChanges(server.SystemContext);
Thread.Sleep(1000);
}
}
}
}
打开服务端和客户端的示例代码
using Opc.UaFx;
using Opc.UaFx.Client;
using Opc.UaFx.Server;
// Define the root node of server
var machineNode = new OpcObjectNode("Machine");
// Declear a variable Hello world like very started.
var messageNode = new OpcDataVariableNode<string>("Message", "Hello World!");
// It's a variable set to false.
bool variableValue = false;
// bind the variable to root.
var isRunningNode = new OpcDataVariableNode<bool>(
machineNode,
"IsRunning",
value: variableValue);
// bind another one in case.
var jobNode = new OpcObjectNode(
machineNode,
"Job",
new OpcDataVariableNode<bool>("Cancel", false),
new OpcDataVariableNode<int>("State", -1));
// New a opc server. Make sure tcp port 4840 haven't been used before
using var server = new OpcServer(
"opc.tcp://localhost:4840/", machineNode, messageNode);
// Start it
server.Start();
// Wait a second
Thread.Sleep(1000);
//while (true) ;
// New a client to connect to 4840
using var client = new OpcClient("opc.tcp://localhost:4840/");
// Connect anyway
client.Connect();
// Print the variable value. It should be false here.
Console.WriteLine(client.ReadNode("ns=2;s=Machine/IsRunning"));
// Write some values.
OpcStatusCollection results = client.WriteNodes(
new OpcWriteNode("ns=2;s=Machine/Job/Cancel", true),
new OpcWriteNode("ns=2;s=Machine/Job/State", 0));
// Print them.
Console.WriteLine(client.ReadNode("ns=2;s=Machine/Job/Cancel"));
Console.WriteLine(client.ReadNode("ns=2;s=Machine/Job/State"));