57 lines
2.3 KiB
C#
57 lines
2.3 KiB
C#
using Opc.Ua;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Client.CLI.Helpers;
|
|
|
|
/// <summary>
|
|
/// Parses node ID strings into OPC UA <see cref="NodeId" /> objects.
|
|
/// Supports standard OPC UA format (e.g., "ns=2;s=MyNode", "i=85") and bare numeric IDs.
|
|
/// </summary>
|
|
public static class NodeIdParser
|
|
{
|
|
/// <summary>
|
|
/// Parses a string into a <see cref="NodeId" />. Returns <c>null</c> if the input is null or empty.
|
|
/// </summary>
|
|
/// <param name="nodeIdString">The node ID string to parse.</param>
|
|
/// <returns>A parsed <see cref="NodeId" />, or <c>null</c> if input is null/empty.</returns>
|
|
/// <exception cref="FormatException">Thrown when the string cannot be parsed as a valid NodeId.</exception>
|
|
public static NodeId? Parse(string? nodeIdString)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(nodeIdString))
|
|
return null;
|
|
|
|
var trimmed = nodeIdString.Trim();
|
|
|
|
// Standard OPC UA format: ns=X;s=..., ns=X;i=..., ns=X;g=..., ns=X;b=...
|
|
// Also: s=..., i=..., g=..., b=... (namespace 0 implied)
|
|
if (trimmed.Contains('='))
|
|
try
|
|
{
|
|
return NodeId.Parse(trimmed);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new FormatException($"Invalid node ID format: '{nodeIdString}'", ex);
|
|
}
|
|
|
|
// Bare numeric: treat as namespace 0, numeric identifier
|
|
if (uint.TryParse(trimmed, out var numericId)) return new NodeId(numericId);
|
|
|
|
throw new FormatException(
|
|
$"Invalid node ID format: '{nodeIdString}'. Expected format like 'ns=2;s=MyNode', 'i=85', or a numeric ID.");
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parses a string into a <see cref="NodeId" />, throwing if the input is null or empty.
|
|
/// </summary>
|
|
/// <param name="nodeIdString">The node ID string to parse.</param>
|
|
/// <returns>A parsed <see cref="NodeId" />.</returns>
|
|
/// <exception cref="ArgumentException">Thrown when the input is null or empty.</exception>
|
|
/// <exception cref="FormatException">Thrown when the string cannot be parsed as a valid NodeId.</exception>
|
|
public static NodeId ParseRequired(string? nodeIdString)
|
|
{
|
|
var result = Parse(nodeIdString);
|
|
if (result == null)
|
|
throw new ArgumentException("Node ID is required but was not provided.");
|
|
return result.Value;
|
|
}
|
|
} |