Skip to main content

End-to-end data collection to CSV

Combine "Connect → Auto-discovery of nodes → Subscribe → Write data to disk" into a complete program. Use ConcurrentQueue buffering and asynchronous writing via a background thread CSVto avoid blocking the Publish callback. Use C# Example.

Sample Configuration

Complete Code​

using DarraOpcUa_Client;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

class Program
{
static async Task Main()
{
// Replace with the on-site PLC industrial PC's IP
const string endpoint = "opc.tcp://192.168.1.100:4840";
const string browseRoot = "ns=2;s=Boiler1"; // Replace with the actual object node in your project
const string csvPath = "data.csv";

// 1. Connect
using var ua = new DarraOpcUa(endpoint);
ua.Connect();
Console.WriteLine($"[OK] 已连接 {endpoint}");

// 2. Browse to auto-discover Variable nodes
var children = ua.Browse(browseRoot, filter: NodeClass.Variable);
Console.WriteLine($"\n在 {browseRoot} 下发现 {children.Count} 个变量:");
foreach (var c in children)
Console.WriteLine($" {c.DisplayName,-20} {c.NodeId}");

// 3. Background CSV writer thread (Producer / Consumer)
var queue = new ConcurrentQueue<string>();
using var cts = new CancellationTokenSource();
var writerTask = Task.Run(() =>
{
using var sw = new StreamWriter(csvPath, append: false);
sw.WriteLine("timestamp,node_id,value,status");
while (!cts.IsCancellationRequested || !queue.IsEmpty)
{
if (queue.TryDequeue(out var line)) sw.WriteLine(line);
else Thread.Sleep(50);
}
sw.Flush();
});

// 4. Subscribe to all discovered nodes
using var sub = ua.CreateSubscription(500);
sub.DataChanged += (s, e) =>
{
var ts = (e.SourceTimestamp ?? DateTime.UtcNow).ToString("O");
queue.Enqueue($"{ts},{e.NodeId},{e.ValueString},{e.Status}");
};

var nodeIds = children.Select(c => c.NodeId).ToList();
sub.AddMany(nodeIds);
Console.WriteLine($"\n开始写入 {csvPath}, 按 Ctrl+C 停止...\n");

// 5. Graceful shutdown (Ctrl+C)
Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel(); };
await Task.Delay(Timeout.Infinite, cts.Token).ContinueWith(_ => { });

// 6. Wait for the queue to drain before exiting
await writerTask;
Console.WriteLine($"已停止, 数据保存到 {csvPath}");
}
}

Code Highlights​

  • Browse(filter: NodeClass.Variable) List only variable nodes and skip Object/Method nodes; this is more flexible NodeId than hard-coding.
  • Avoid writing directly to files in callbacks—IO writing at the disk level can ms slow down publishing and cause a backlog in the server's NotificationQueue; instead ConcurrentQueue, use background tasks for asynchronous writing.
  • When exiting, cts.Cancel() you must await writerTask wait until the queue is empty; otherwise, data at the end of the queue will be lost.
  • SourceTimestamp Save the file using the ISO-8601 ("O" format) to ensure that time calculations remain accurate across time zones.

Important Notes​

  • CSV is separated by ,; if NodeId or ValueString contains commas, they must be escaped (enclosed in quotes), but this has been omitted here for brevity.
  • For long-term operation, we recommend using rotate(data-2026-04-25.csv) daily along with asynchronous gzip compression; otherwise, individual files will grow indefinitely.
  • High-frequency (>100Hz) data should be stored directly in SQLite or TimescaleDB; CSV is not suitable for a large number of random queries.