LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

使用C#開發(fā)OPC UA服務(wù)器

freeflydom
2025年5月17日 10:9 本文熱度 40

OPC基金會提供了OPC UA .NET標準庫以及示例程序,但官方文檔過于簡單,光看官方文檔和示例程序很難弄懂OPC UA .NET標準庫怎么用,花了不少時間摸索才略微弄懂如何使用,以下記錄如何從一個控制臺程序開發(fā)一個OPC UA服務(wù)器。

安裝Nuget包

安裝OPCFoundation.NetStandard.Opc.Ua

主程序

修改Program.cs代碼如下:

using Opc.Ua;
using Opc.Ua.Configuration;
using Opc.Ua.Server;
namespace SampleOpcUaServer
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 啟動OPC UA服務(wù)器
            ApplicationInstance application = new ApplicationInstance();
            application.ConfigSectionName = "OpcUaServer";
            application.LoadApplicationConfiguration(false).Wait();
            application.CheckApplicationInstanceCertificate(false, 0).Wait();
            var server = new StandardServer();
            var nodeManagerFactory = new NodeManagerFactory();
            server.AddNodeManager(nodeManagerFactory);
            application.Start(server).Wait();
            // 模擬數(shù)據(jù)
            var nodeManager = nodeManagerFactory.NodeManager;
            var simulationTimer = new System.Timers.Timer(1000);
            var random = new Random();
            simulationTimer.Elapsed += (sender, EventArgs) =>
            {
                nodeManager?.UpdateValue("ns=2;s=Root_Test", random.NextInt64());
            };
            simulationTimer.Start();
            // 輸出OPC UA Endpoint
            Console.WriteLine("Endpoints:");
            foreach (var endpoint in server.GetEndpoints().DistinctBy(x => x.EndpointUrl))
            {
                Console.WriteLine(endpoint.EndpointUrl);
            }
            Console.WriteLine("按Enter添加新變量");
            Console.ReadLine();
            // 添加新變量
            nodeManager?.AddVariable("ns=2;s=Root", null, "Test2", (int)BuiltInType.Int16, ValueRanks.Scalar);
            Console.WriteLine("已添加變量");
            Console.ReadLine();
        }
    }
}

上述代碼中:

  • ApplicationInstance是OPC UA標準庫中用于配置并承載OPC UA Server和檢查證書的類。
  • application.ConfigSectionName指定了配置文件的名稱,配置文件是xml文件,將會在程序文件夾查找名為OpcUaServer.Config.xml的配置文件。配置文件內(nèi)容見后文。
  • application.LoadApplicationConfiguration加載前面指定的配置文件。如果不想使用配置文件,也可通過代碼給application.ApplicationConfiguration賦值。
  • StandardServerReverseConnectServer兩種作為OPC UA服務(wù)器的類,ReverseConnectServer派生于StandardServer,這兩種類的區(qū)別未深入研究,用StandardServer可滿足基本的需求。
  • OPC UA的地址空間由節(jié)點組成,簡單理解節(jié)點就是提供給OPC UA客戶端訪問的變量和文件夾。通過server.AddNodeManager方法添加節(jié)點管理工廠類,NodeManagerFactory類定義見后文。
  • 調(diào)用application.Start(server)方法后,OPC UA Server就會開始運行,并不會阻塞代碼,為了保持在控制臺程序中運行,所以使用Console.ReadLine()阻塞程序。
  • nodeManager?.UpdateValue是自定義的更新OPC UA地址空間中變量值的方法。
  • nodeManager?.AddVariable在此演示動態(tài)添加一個新的變量。

OPC UA配置文件

新建OpcUaServer.Config.xml文件。

在屬性中設(shè)為“始終賦值”。

內(nèi)容如下:

<?xml version="1.0" encoding="utf-8"?>
<ApplicationConfiguration
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:ua="http://opcfoundation.org/UA/2008/02/Types.xsd"
  xmlns="http://opcfoundation.org/UA/SDK/Configuration.xsd"
>
	<ApplicationName>Sample OPC UA Server</ApplicationName>
	<ApplicationUri>urn:localhost:UA:OpcUaServer</ApplicationUri>
	<ProductUri>uri:opcfoundation.org:OpcUaServer</ProductUri>
	<ApplicationType>Server_0</ApplicationType>
	<SecurityConfiguration>
		<!-- Where the application instance certificate is stored (MachineDefault) -->
		<ApplicationCertificate>
			<StoreType>Directory</StoreType>
			<StorePath>%CommonApplicationData%\OPC Foundation\pki\own</StorePath>
			<SubjectName>CN=Sample Opc Ua Server, C=US, S=Arizona, O=SomeCompany, DC=localhost</SubjectName>
		</ApplicationCertificate>
		<!-- Where the issuer certificate are stored (certificate authorities) -->
		<TrustedIssuerCertificates>
			<StoreType>Directory</StoreType>
			<StorePath>%CommonApplicationData%\OPC Foundation\pki\issuer</StorePath>
		</TrustedIssuerCertificates>
		<!-- Where the trust list is stored -->
		<TrustedPeerCertificates>
			<StoreType>Directory</StoreType>
			<StorePath>%CommonApplicationData%\OPC Foundation\pki\trusted</StorePath>
		</TrustedPeerCertificates>
		<!-- The directory used to store invalid certficates for later review by the administrator. -->
		<RejectedCertificateStore>
			<StoreType>Directory</StoreType>
			<StorePath>%CommonApplicationData%\OPC Foundation\pki\rejected</StorePath>
		</RejectedCertificateStore>
	</SecurityConfiguration>
	<TransportConfigurations></TransportConfigurations>
	<TransportQuotas>
		<OperationTimeout>600000</OperationTimeout>
		<MaxStringLength>1048576</MaxStringLength>
		<MaxByteStringLength>1048576</MaxByteStringLength>
		<MaxArrayLength>65535</MaxArrayLength>
		<MaxMessageSize>4194304</MaxMessageSize>
		<MaxBufferSize>65535</MaxBufferSize>
		<ChannelLifetime>300000</ChannelLifetime>
		<SecurityTokenLifetime>3600000</SecurityTokenLifetime>
	</TransportQuotas>
	<ServerConfiguration>
		<BaseAddresses>
			<ua:String>https://localhost:62545/OpcUaServer/</ua:String>
			<ua:String>opc.tcp://localhost:62546/OpcUaServer</ua:String>
		</BaseAddresses>
		<SecurityPolicies>
			<ServerSecurityPolicy>
				<SecurityMode>SignAndEncrypt_3</SecurityMode>
				<SecurityPolicyUri>http://opcfoundation.org/UA/SecurityPolicy#Basic256Sha256</SecurityPolicyUri>
			</ServerSecurityPolicy>
			<ServerSecurityPolicy>
				<SecurityMode>None_1</SecurityMode>
				<SecurityPolicyUri>http://opcfoundation.org/UA/SecurityPolicy#None</SecurityPolicyUri>
			</ServerSecurityPolicy>
			<ServerSecurityPolicy>
				<SecurityMode>Sign_2</SecurityMode>
				<SecurityPolicyUri></SecurityPolicyUri>
			</ServerSecurityPolicy>
			<ServerSecurityPolicy>
				<SecurityMode>SignAndEncrypt_3</SecurityMode>
				<SecurityPolicyUri></SecurityPolicyUri>
			</ServerSecurityPolicy>
		</SecurityPolicies>
		<UserTokenPolicies>
			<ua:UserTokenPolicy>
				<ua:TokenType>Anonymous_0</ua:TokenType>
			</ua:UserTokenPolicy>
			<ua:UserTokenPolicy>
				<ua:TokenType>UserName_1</ua:TokenType>
			</ua:UserTokenPolicy>
			<ua:UserTokenPolicy>
				<ua:TokenType>Certificate_2</ua:TokenType>
			</ua:UserTokenPolicy>
			<!--
      <ua:UserTokenPolicy>
        <ua:TokenType>IssuedToken_3</ua:TokenType>
        <ua:IssuedTokenType>urn:oasis:names:tc:SAML:1.0:assertion:Assertion</ua:IssuedTokenType>
      </ua:UserTokenPolicy>
      -->
		</UserTokenPolicies>
		<DiagnosticsEnabled>false</DiagnosticsEnabled>
		<MaxSessionCount>100</MaxSessionCount>
		<MinSessionTimeout>10000</MinSessionTimeout>
		<MaxSessionTimeout>3600000</MaxSessionTimeout>
		<MaxBrowseContinuationPoints>10</MaxBrowseContinuationPoints>
		<MaxQueryContinuationPoints>10</MaxQueryContinuationPoints>
		<MaxHistoryContinuationPoints>100</MaxHistoryContinuationPoints>
		<MaxRequestAge>600000</MaxRequestAge>
		<MinPublishingInterval>100</MinPublishingInterval>
		<MaxPublishingInterval>3600000</MaxPublishingInterval>
		<PublishingResolution>50</PublishingResolution>
		<MaxSubscriptionLifetime>3600000</MaxSubscriptionLifetime>
		<MaxMessageQueueSize>10</MaxMessageQueueSize>
		<MaxNotificationQueueSize>100</MaxNotificationQueueSize>
		<MaxNotificationsPerPublish>1000</MaxNotificationsPerPublish>
		<MinMetadataSamplingInterval>1000</MinMetadataSamplingInterval>
		<AvailableSamplingRates>
			<SamplingRateGroup>
				<Start>5</Start>
				<Increment>5</Increment>
				<Count>20</Count>
			</SamplingRateGroup>
			<SamplingRateGroup>
				<Start>100</Start>
				<Increment>100</Increment>
				<Count>4</Count>
			</SamplingRateGroup>
			<SamplingRateGroup>
				<Start>500</Start>
				<Increment>250</Increment>
				<Count>2</Count>
			</SamplingRateGroup>
			<SamplingRateGroup>
				<Start>1000</Start>
				<Increment>500</Increment>
				<Count>20</Count>
			</SamplingRateGroup>
		</AvailableSamplingRates>
		<MaxRegistrationInterval>30000</MaxRegistrationInterval>
		<NodeManagerSaveFile>OpcUaServer.nodes.xml</NodeManagerSaveFile>
	</ServerConfiguration>
	<TraceConfiguration>
		<OutputFilePath>Logs\SampleOpcUaServer.log</OutputFilePath>
		<DeleteOnLoad>true</DeleteOnLoad>
		<!-- Show Only Errors -->
		<!-- <TraceMasks>1</TraceMasks> -->
		<!-- Show Only Security and Errors -->
		<!-- <TraceMasks>513</TraceMasks> -->
		<!-- Show Only Security, Errors and Trace -->
		<TraceMasks>515</TraceMasks>
		<!-- Show Only Security, COM Calls, Errors and Trace -->
		<!-- <TraceMasks>771</TraceMasks> -->
		<!-- Show Only Security, Service Calls, Errors and Trace -->
		<!-- <TraceMasks>523</TraceMasks> -->
		<!-- Show Only Security, ServiceResultExceptions, Errors and Trace -->
		<!-- <TraceMasks>519</TraceMasks> -->
	</TraceConfiguration>
</ApplicationConfiguration>

需要關(guān)注的內(nèi)容有:

  • ApplicationName:在通過OPC UA工具連接此服務(wù)器時,顯示的服務(wù)器名稱就是該值。

  • ApplicationType:應(yīng)用類型,可用的值有:

    • Server_0:服務(wù)器
    • Client_1:客戶端
    • ClientAndServer_2:客戶機和服務(wù)器
    • DisconveryServer_3:發(fā)現(xiàn)服務(wù)器。發(fā)現(xiàn)服務(wù)器用于注冊O(shè)PC UA服務(wù)器,然后提供OPC UA客戶端搜索到服務(wù)器。
  • SecurityConfiguration:該節(jié)點中指定了OPC UA的證書存儲路徑,一般保持默認,不需修改。

  • ServerConfiguration.BaseAddresses:該節(jié)點指定OPC UA服務(wù)器的url地址。

  • ServerConfiguration.SecurityPolicies:該節(jié)點配置允許的服務(wù)器安全策略,配置通訊是否要簽名和加密。

  • ServerConfiguration.UserTokenPolicies:該節(jié)點配置允許的用戶Token策略,例如是否允許匿名訪問。

  • AvailableSamplingRates:配置支持的變量采樣率。

  • TraceConfiguration:配置OPC UA服務(wù)器的日志記錄,設(shè)定日志記錄路徑,配置的路徑是在系統(tǒng)臨時文件夾下的路徑,日志文件的完整路徑是在%TEMP%\Logs\SampleOpcUaServer.log

NodeManagerFactory

新建NodeManagerFactory類,OPC UA server將調(diào)用該類的Create方法創(chuàng)建INodeManager實現(xiàn)類,而INodeManager實現(xiàn)類用于管理OPC UA地址空間。內(nèi)容如下:

using Opc.Ua;
using Opc.Ua.Server;
namespace SampleOpcUaServer
{
    internal class NodeManagerFactory : INodeManagerFactory
    {
        public NodeManager? NodeManager { get; private set; }
        public StringCollection NamespacesUris => new StringCollection() { "http://opcfoundation.org/OpcUaServer" };
        public INodeManager Create(IServerInternal server, ApplicationConfiguration configuration)
        {
            if (NodeManager != null)
                return NodeManager;
            NodeManager = new NodeManager(server, configuration, NamespacesUris.ToArray());
            return NodeManager;
        }
    }
}
  • 實現(xiàn)INodeManagerFactory接口,需實現(xiàn)NamespacesUris屬性和Create方法。
  • NodeManager類是自定義的類,定義見后文。
  • 為了獲取Create方法返回的NodeManager類,定義了NodeManager屬性。

NodeManager

新建NodeManager類:

using Opc.Ua;
using Opc.Ua.Server;
namespace SampleOpcUaServer
{
    internal class NodeManager : CustomNodeManager2
    {
        public NodeManager(IServerInternal server, params string[] namespaceUris)
            : base(server, namespaceUris)
        {
        }
        public NodeManager(IServerInternal server, ApplicationConfiguration configuration, params string[] namespaceUris)
            : base(server, configuration, namespaceUris)
        {
        }
        protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context)
        {
            FolderState root = CreateFolder(null, null, "Root");
            root.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder); // 將節(jié)點添加到服務(wù)器根節(jié)點
            root.EventNotifier = EventNotifiers.SubscribeToEvents;
            AddRootNotifier(root);
            CreateVariable(root, null, "Test", BuiltInType.Int64, ValueRanks.Scalar);
            return new NodeStateCollection(new List<NodeState> { root });
        }
        protected virtual FolderState CreateFolder(NodeState? parent, string? path, string name)
        {
            if (string.IsNullOrWhiteSpace(path))
                path = parent?.NodeId.Identifier is string id ? id + "_" + name : name;
            FolderState folder = new FolderState(parent);
            folder.SymbolicName = name;
            folder.ReferenceTypeId = ReferenceTypes.Organizes;
            folder.TypeDefinitionId = ObjectTypeIds.FolderType;
            folder.NodeId = new NodeId(path, NamespaceIndex);
            folder.BrowseName = new QualifiedName(path, NamespaceIndex);
            folder.DisplayName = new LocalizedText("en", name);
            folder.WriteMask = AttributeWriteMask.None;
            folder.UserWriteMask = AttributeWriteMask.None;
            folder.EventNotifier = EventNotifiers.None;
            if (parent != null)
            {
                parent.AddChild(folder);
            }
            return folder;
        }
        protected virtual BaseDataVariableState CreateVariable(NodeState? parent, string? path, string name, BuiltInType dataType, int valueRank)
        {
            return CreateVariable(parent, path, name, (uint)dataType, valueRank);
        }
        protected virtual BaseDataVariableState CreateVariable(NodeState? parent, string? path, string name, NodeId dataType, int valueRank)
        {
            if (string.IsNullOrWhiteSpace(path))
                path = parent?.NodeId.Identifier is string id ? id + "_" + name : name;
            BaseDataVariableState variable = new BaseDataVariableState(parent);
            variable.SymbolicName = name;
            variable.ReferenceTypeId = ReferenceTypes.Organizes;
            variable.TypeDefinitionId = VariableTypeIds.BaseDataVariableType;
            variable.NodeId = new NodeId(path, NamespaceIndex);
            variable.BrowseName = new QualifiedName(path, NamespaceIndex);
            variable.DisplayName = new LocalizedText("en", name);
            variable.WriteMask = AttributeWriteMask.None;
            variable.UserWriteMask = AttributeWriteMask.None;
            variable.DataType = dataType;
            variable.ValueRank = valueRank;
            variable.AccessLevel = AccessLevels.CurrentReadOrWrite;
            variable.UserAccessLevel = AccessLevels.CurrentReadOrWrite;
            variable.Historizing = false;
            variable.Value = Opc.Ua.TypeInfo.GetDefaultValue(dataType, valueRank, Server.TypeTree);
            variable.StatusCode = StatusCodes.Good;
            variable.Timestamp = DateTime.UtcNow;
            if (valueRank == ValueRanks.OneDimension)
            {
                variable.ArrayDimensions = new ReadOnlyList<uint>(new List<uint> { 0 });
            }
            else if (valueRank == ValueRanks.TwoDimensions)
            {
                variable.ArrayDimensions = new ReadOnlyList<uint>(new List<uint> { 0, 0 });
            }
            if (parent != null)
            {
                parent.AddChild(variable);
            }
            return variable;
        }
        public void UpdateValue(NodeId nodeId, object value)
        {
            var variable = (BaseDataVariableState)FindPredefinedNode(nodeId, typeof(BaseDataVariableState));
            if (variable != null)
            {
                variable.Value = value;
                variable.Timestamp = DateTime.UtcNow;
                variable.ClearChangeMasks(SystemContext, false);
            }
        }
        public NodeId AddFolder(NodeId parentId, string? path, string name)
        {
            var node = Find(parentId);
            var newNode = CreateFolder(node, path, name);
            AddPredefinedNode(SystemContext, node);
            return newNode.NodeId;
        }
        public NodeId AddVariable(NodeId parentId, string? path, string name, BuiltInType dataType, int valueRank)
        {
            return AddVariable(parentId, path, name, (uint)dataType, valueRank);
        }
        public NodeId AddVariable(NodeId parentId, string? path, string name, NodeId dataType, int valueRank)
        {
            var node = Find(parentId);
            var newNode = CreateVariable(node, path, name, dataType, valueRank);
            AddPredefinedNode(SystemContext, node);
            return newNode.NodeId;
        }
    }
}

上述代碼中:

  • 需繼承CustomNodeManager2,這是OPC UA標準庫中提供的類。
  • 重寫LoadPredefinedNodes方法,在該方法中配置預(yù)定義節(jié)點。其中創(chuàng)建了一個Root文件夾,Root文件夾中添加了Test變量。
  • root.AddReference(ReferenceTypes.Organizes, true, ObjectIds.ObjectsFolder)該語句將節(jié)點添加到OPC UA服務(wù)器根節(jié)點,如果不使用該語句,可在Server節(jié)點下看到添加的節(jié)點。
  • CreateFolder是自定義的方法,用于簡化創(chuàng)建文件夾節(jié)點。
  • CreateVariable是自定義的方法,用于簡化創(chuàng)建變量節(jié)點。
  • UpdateValue是用于更新變量節(jié)點值的方法。其中修改值后,需調(diào)用ClearChangeMasks方法,才能通知客戶端更新值。
  • AddFolder用于啟動服務(wù)器后添加新的文件夾。
  • AddVariable用于啟動服務(wù)器后添加新的變量。

測試服務(wù)器

比較好用的測試工具有:

  • UaExpert:Unified Automation公司提供的測試工具,需安裝,能用于連接OPC UA。

  • OpcExpert:opcti公司提供的免費測試工具,綠色版,能連接OPC和OPC UA。

以下用OpcExpert測試。

瀏覽本地計算機可發(fā)現(xiàn)OPC UA服務(wù)器,可看到添加的Root節(jié)點和Test變量,Test變量的值會每秒更新。

源碼地址:https://github.com/Yada-Yang/SampleOpcUaServer

轉(zhuǎn)自https://www.cnblogs.com/yada/p/18257593


該文章在 2025/5/17 10:09:56 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運作、調(diào)度、堆場、車隊、財務(wù)費用、相關(guān)報表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點,圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務(wù)都免費,不限功能、不限時間、不限用戶的免費OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
亚洲一区激情国产日韩 | 日本一二三区免费 | 亚洲精品网站在线观看 | 亚洲国产大片在线观看 | 三级日本成网人站 | 日韩精品欧美国产精品亚 |