Single-Point Periodic Data Collection
The simplest introductory example: Use a loop while + Sleep + Read to read the server time once per second and print it. Use C# Example.
Sample Configuration
- Multiple nodes → Multi-Source Subscription Collection (Recommended; much more efficient than polling)
- Complete Process → End-to-end data collection to CSV
Complete Code
using DarraOpcUa_Client;
using System;
using System.Threading;
class Program
{
static void Main()
{
// Replace with the PLC on-site industrial PC IP; for local debugging, use `localhost`.
const string endpoint = "opc.tcp://192.168.1.100:4840";
const string nodeId = "i=2258"; // ServerStatus.CurrentTime (OPC UA Standard Node)
// 1. Create a session and connect
using var ua = new DarraOpcUa(endpoint);
ua.Connect();
Console.WriteLine($"[OK] 已连接 {endpoint}");
// 2. Periodic Reading
Console.WriteLine("按 Ctrl+C 停止...\n");
while (true)
{
try
{
using var dv = ua.Read(nodeId);
if (dv.IsGood)
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {nodeId} = {dv.Value.AsDateTime:O}");
else
Console.WriteLine($"{DateTime.Now:HH:mm:ss} {nodeId} 读取失败: {dv.Status}");
}
catch (OpcUaException ex)
{
Console.WriteLine($"通讯异常: {ex.StatusCode}, 1 秒后重试");
}
Thread.Sleep(1000);
}
}
}
Code Highlights
DataValueHold the native memory handle; you must do so, otherwiseusinga leak will occur.- Evaluate first, then use
IsGoodValue; if the business layer fails, return the result via Status instead of throwing an exception. OpcUaExceptionThis only indicates a failure at the communication layer (connection loss/timeout); you must catch the exception and retry, otherwise the entire program will crash if the connection is lost even once.
Important Notes
- Polling is the simplest but most inefficient method—100 nodes means 100 calls RPC. For real-world projects with more than 5 nodes, we recommend using Subscription Model.
- The interval must not be shorter than the network RTT; otherwise the next Read will be sent before the previous one has returned. Typical LAN RTT is 1-50ms, so be careful with intervals below 100ms.
- Be sure to add this for long-term operation
try/catch + Connect 重试; otherwise, the entire program will crash if the internet connection is lost even once.