using System.Collections;
using System.Globalization;
using Opc.Ua;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
///
/// Gitea #58: converts a scalar write value to the CLR type that matches the target node's
/// OPC UA built-in DataType before wraps it in a
/// .
///
/// The runtime hands the DCL codec-encoded scalars (an attribute value of "True" or
/// "42.5"), and new Variant("42.5") is a String Variant, which a conformant
/// server rejects on a Double node with BadTypeMismatch. The OPC UA write service does
/// no implicit conversion, so the client has to send the node's own type.
///
///
/// Rules: every string parse is culture-invariant; a value that cannot be represented exactly
/// in the target type (overflow, a fractional value to an integer type, an unparseable string)
/// is an error, never a rounded or truncated value. Arrays/collections, null and target
/// types with no scalar mapping here (structures, abstract Number, BaseDataType,
/// …) pass through unchanged, so the server stays the judge of those.
///
///
internal static class OpcUaWriteCoercion
{
/// The outcome of a coercion attempt.
/// False when the value cannot be represented in the target type.
/// The value to write (the original value when nothing applied).
/// Why the conversion failed; null on success.
internal readonly record struct Result(bool Success, object? Value, string? Error)
{
internal static Result Ok(object? value) => new(true, value, null);
internal static Result Fail(string error) => new(false, null, error);
}
///
/// True when is a scalar this class may coerce: not null, not a
/// string-less collection. A byte[] is a ByteString scalar in OPC UA, but it is
/// never a codec scalar and is left to the SDK as-is.
///
internal static bool IsCoercibleScalar(object? value) =>
value is not null && (value is string || value is not IEnumerable);
///
/// Coerces to the CLR representation of .
///
internal static Result Coerce(object? value, BuiltInType target)
{
if (!IsCoercibleScalar(value))
return Result.Ok(value);
try
{
return target switch
{
BuiltInType.Boolean => ToBoolean(value!),
BuiltInType.SByte => ToInteger(value!, target, sbyte.MinValue, sbyte.MaxValue, d => (sbyte)d),
BuiltInType.Byte => ToInteger(value!, target, byte.MinValue, byte.MaxValue, d => (byte)d),
BuiltInType.Int16 => ToInteger(value!, target, short.MinValue, short.MaxValue, d => (short)d),
BuiltInType.UInt16 => ToInteger(value!, target, ushort.MinValue, ushort.MaxValue, d => (ushort)d),
BuiltInType.Int32 => ToInteger(value!, target, int.MinValue, int.MaxValue, d => (int)d),
// An enumeration DataType travels as Int32 on the wire (Part 6 §5.1.2).
BuiltInType.Enumeration => ToInteger(value!, BuiltInType.Int32, int.MinValue, int.MaxValue, d => (int)d),
BuiltInType.UInt32 => ToInteger(value!, target, uint.MinValue, uint.MaxValue, d => (uint)d),
BuiltInType.Int64 => ToInteger(value!, target, long.MinValue, long.MaxValue, d => (long)d),
BuiltInType.UInt64 => ToInteger(value!, target, ulong.MinValue, ulong.MaxValue, d => (ulong)d),
BuiltInType.Float => ToFloat(value!),
BuiltInType.Double => ToDouble(value!),
BuiltInType.String => Result.Ok(ToInvariantString(value!)),
BuiltInType.DateTime => ToDateTime(value!),
BuiltInType.Guid => ToGuid(value!),
_ => Result.Ok(value)
};
}
catch (Exception ex) when (ex is FormatException or OverflowException or InvalidCastException)
{
return Fail(value!, target, ex.Message);
}
}
private static Result Fail(object value, BuiltInType target, string reason) =>
Result.Fail($"Cannot convert {Describe(value)} to the node's OPC UA DataType {target}: {reason}");
private static string Describe(object value) => value is string s
? $"String \"{(s.Length > 64 ? s[..64] + "…" : s)}\""
: $"{value.GetType().Name} {ToInvariantString(value)}";
private static Result ToBoolean(object value)
{
switch (value)
{
case bool b:
return Result.Ok(b);
case string s:
var t = s.Trim();
if (bool.TryParse(t, out var parsed)) return Result.Ok(parsed);
if (t == "1") return Result.Ok(true);
if (t == "0") return Result.Ok(false);
return Fail(value, BuiltInType.Boolean, "expected true/false or 1/0.");
default:
if (TryToDecimal(value, out var d) && (d == 0m || d == 1m)) return Result.Ok(d == 1m);
return Fail(value, BuiltInType.Boolean, "only 0 or 1 map to a Boolean.");
}
}
private static Result ToInteger(object value, BuiltInType target, decimal min, decimal max, Func narrow)
{
decimal d;
switch (value)
{
case bool b:
d = b ? 1m : 0m;
break;
case string s:
var t = s.Trim();
// Integer syntax first (full Int64/UInt64 range), then a decimal literal that
// happens to be whole ("42.0") — a fractional or exponent-overflowing string fails.
if (!decimal.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out d)
&& !decimal.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out d))
return Fail(value, target, "not a number.");
break;
default:
if (value is double dbl && (double.IsNaN(dbl) || double.IsInfinity(dbl)))
return Fail(value, target, "NaN/Infinity has no integer value.");
if (value is float flt && (float.IsNaN(flt) || float.IsInfinity(flt)))
return Fail(value, target, "NaN/Infinity has no integer value.");
if (!TryToDecimal(value, out d))
return Fail(value, target, IsNumeric(value) ? "out of range." : "not a numeric value.");
break;
}
if (d != decimal.Truncate(d))
return Fail(value, target, "the value has a fractional part.");
if (d < min || d > max)
return Fail(value, target, $"out of range [{min.ToString(CultureInfo.InvariantCulture)}, {max.ToString(CultureInfo.InvariantCulture)}].");
return Result.Ok(narrow(d));
}
private static Result ToDouble(object value) =>
TryToDouble(value, out var d, out var reason) ? Result.Ok(d) : Fail(value, BuiltInType.Double, reason!);
private static Result ToFloat(object value)
{
if (value is float f) return Result.Ok(f);
if (!TryToDouble(value, out var d, out var reason)) return Fail(value, BuiltInType.Float, reason!);
if (double.IsFinite(d) && (d > float.MaxValue || d < float.MinValue))
return Fail(value, BuiltInType.Float, "out of range.");
return Result.Ok((float)d);
}
private static bool TryToDouble(object value, out double result, out string? reason)
{
reason = null;
switch (value)
{
case double d:
result = d;
return true;
case bool b:
result = b ? 1d : 0d;
return true;
case string s:
var t = s.Trim();
if (!double.TryParse(t, NumberStyles.Float, CultureInfo.InvariantCulture, out result))
{
reason = "not a number.";
return false;
}
// .NET parses an out-of-range literal ("1e999") to ±Infinity; only an explicit
// infinity literal may mean infinity.
if (double.IsInfinity(result) && !t.Contains("Infinity", StringComparison.OrdinalIgnoreCase) && !t.Contains('∞'))
{
reason = "out of range.";
return false;
}
return true;
case IConvertible c when IsNumeric(value):
result = c.ToDouble(CultureInfo.InvariantCulture);
return true;
default:
result = 0d;
reason = "not a numeric value.";
return false;
}
}
private static Result ToDateTime(object value)
{
switch (value)
{
case DateTime dt:
return Result.Ok(dt);
case DateTimeOffset dto:
return Result.Ok(dto.UtcDateTime);
case string s:
// Script/codec timestamps are UTC by convention: an offset-less string is taken
// as UTC, and an offset-bearing one is normalised to UTC.
if (!DateTime.TryParse(s.Trim(), CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var parsed))
return Fail(value, BuiltInType.DateTime, "not a recognised date/time (use ISO 8601).");
return Result.Ok(parsed);
default:
return Fail(value, BuiltInType.DateTime, "not a date/time value.");
}
}
private static Result ToGuid(object value) => value switch
{
Guid g => Result.Ok(g),
Uuid u => Result.Ok((Guid)u),
string s when Guid.TryParse(s.Trim(), out var g) => Result.Ok(g),
_ => Fail(value, BuiltInType.Guid, "not a GUID.")
};
private static string ToInvariantString(object value) => value switch
{
string s => s,
DateTime dt => dt.ToString("O", CultureInfo.InvariantCulture),
double d => d.ToString("R", CultureInfo.InvariantCulture),
float f => f.ToString("R", CultureInfo.InvariantCulture),
IFormattable fmt => fmt.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString() ?? string.Empty
};
private static bool IsNumeric(object value) => value is sbyte or byte or short or ushort or int or uint
or long or ulong or float or double or decimal;
private static bool TryToDecimal(object value, out decimal d)
{
d = 0m;
if (!IsNumeric(value)) return false;
try
{
d = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
return true;
}
catch (OverflowException)
{
// A double beyond ±7.9e28 is out of range of every integer type anyway.
return false;
}
}
}