上位机应用开发中的通信需求
通信过程/通信协议多样性
通信统一化处理方案:OPC(Open Platform Communications)、OPC UA(OPC Unified Architecture)
基于西门子1500PLC的OPC服务器对接
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
OpcUa();
Console.ReadLine();
}
private static async void OpcUa()
{
//ApplicationConfiguration configuration,
//ConfiguredEndpoint endpoint,
//bool updateBeforeConnect,
//string sessionName,
//uint sessionTimeout,
//IUserIdentity identity,
//IList<string> preferredLocales
// 准备第一个参数
ApplicationConfiguration ac = new ApplicationConfiguration();
ac.ClientConfiguration = new ClientConfiguration();
CertificateValidator cv = new CertificateValidator
{
RejectSHA1SignedCertificates = false,
};
cv.CertificateValidation += (se, ev) =>
{
if (ev.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted)
{
ev.Accept = true;
}
};
ac.CertificateValidator = cv;
// 准备第二个参数
EndpointDescription desc = CoreClientUtils.SelectEndpoint(
discoveryUrl: "opc.tcp://OPCSERVER:49320",
false
);
ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, desc);
Session session = await Session.Create(
ac,
endpoint,
false,
"PLC1500_opc",
60000,
new UserIdentity("admin", "admin"),
new string[] { }
);
// 简单 用户名密码
// 证书 服务器 任意证书自动接收 服务器颁发证书
// 浏览节点
//Browser browser = new Browser(session);
//var collection = browser.Browse(new NodeId("ns=2;s=通道 1.设备 1"));
//foreach (var node in collection)
//{
//}
// 读取
//RequestHeader requestHeader,
//double maxAge,
//TimestampsToReturn timestampsToReturn,
//ReadValueIdCollection nodesToRead,
//out DataValueCollection results,
//out DiagnosticInfoCollection diagnosticInfos
ReadValueIdCollection readValueIds = new ReadValueIdCollection();
ReadValueId id = new ReadValueId();
id.NodeId = "ns=2;s=数据类型示例.16 位设备.R 寄存器.Word1";
id.AttributeId = Attributes.Value;
readValueIds.Add(id);
id = new ReadValueId();
id.NodeId = "ns=2;s=数据类型示例.16 位设备.R 寄存器.Word2";
id.AttributeId = Attributes.Value;
readValueIds.Add(id);
id = new ReadValueId();
id.NodeId = "ns=2;s=数据类型示例.16 位设备.R 寄存器.WordArray";
id.AttributeId = Attributes.Value;
readValueIds.Add(id);
session.Read(
new RequestHeader(),
0,
TimestampsToReturn.Both,
readValueIds,
out DataValueCollection results,
out DiagnosticInfoCollection diagnosticInfos
);
foreach (var value in results)
{
if (value.WrappedValue.TypeInfo.ValueRank == -1)//单值
Console.WriteLine(value);
else if (value.WrappedValue.TypeInfo.ValueRank == 1)
{
foreach (var v in (ushort[])value.WrappedValue.Value)
{
Console.WriteLine(v);
}
}
}
}
}