C#實現訪問OPC UA服務器
OPC UA服務器支持三種認證方式,分別是匿名認證、用戶認證和證書認證。其中匿名認證安全等級最低,訪問不做任何校驗。用戶認證訪問時,OPC UA客戶端需要提供用戶名及密碼認證,只有用戶名和密碼正確才允許訪問。
而證書認證,首先需要將客戶端公鑰證書提供給OPC UA服務器。然後客戶端使用其公鑰和私鑰證書認證,認證成功後才能訪問。
C#訪問OPC UA服務器步驟如下:
1.  下載安裝OPC UA服務器
OPC UA服務器下載及說明:EasyOPC
2.  連接OPC UA服務器
首先通過NuGet引入最新版OpcUaHelper。
匿名認證:
“ OpcUaClient opcUaClient = new OpcUaHelper.OpcUaClient();
opcUaClient.ConnectServer(“opc.tcp://127.0.0.1:4840”).Wait();“
用戶認證:
```
            OpcUaClient opcUaClient = new OpcUaHelper.OpcUaClient();
                //用戶及密碼驗證
                 opcUaClient.UserIdentity = new UserIdentity("test", "123456");
                opcUaClient.ConnectServer("opc.tcp://127.0.0.1:4840").Wait();
```
   證書認證:
   
   讀取私鑰證書
  ![讀取私鑰.PNG][1]
   
  ![證書認證.PNG][2]
3. 讀取OPC UA節點
```
 //讀節點值
 Double Temp = opcUaClient.ReadNode<Double>("ns=2;s=factory_1/line1/Temp");
```
4. 寫OPC UA節點
```
//寫節點值
opcUaClient.WriteNode<Double>("ns=2;s=factory_1/line1/Temp", 10.20);
```
5. 訂閱OPC UA節點
訂閱節點值發生改變,就會執行訂閱事件
```
 //訂閱節點,ns=2;s=factory_1/line1/Temp 節點值發生改變執行事件
 opcUaClient.AddSubscription("temp_subscription", "ns=2;s=factory_1/line1/Temp", 
          (string key, MonitoredItem item, MonitoredItemNotificationEventArgs eventArgs) =>
          {
                var itemNotification = (MonitoredItemNotification)eventArgs.NotificationValue;
                            Console.WriteLine((double)itemNotification.Value.Value);
           });
```


