Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Shared/Drivers/DriverConfigMs.cs
T

40 lines
1.6 KiB
C#

using System.Text.Json;
using System.Text.Json.Nodes;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers;
/// <summary>
/// Shared millisecond helpers for the AB forms (#576): the driver factories bind <c>*Ms</c> integers
/// while the forms edit whole seconds, so a sub-second stored value must survive an edit of an
/// unrelated field.
/// </summary>
internal static class DriverConfigMs
{
/// <summary>Reads an integer-millisecond key at <paramref name="path"/> from <paramref name="json"/>, or null.</summary>
public static int? Read(string? json, string path)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
JsonNode? cur = JsonNode.Parse(json);
foreach (var seg in path.Split('.'))
{
if (cur is not JsonObject o) return null;
cur = o.FirstOrDefault(kv => string.Equals(kv.Key, seg, StringComparison.OrdinalIgnoreCase)).Value;
}
return cur is JsonValue v && v.TryGetValue<int>(out var ms) ? ms : null;
}
catch (JsonException) { return null; }
}
/// <summary>Whole seconds for display (truncating, like the pre-#576 forms).</summary>
public static int ToSeconds(TimeSpan t) => (int)t.TotalSeconds;
/// <summary>
/// The duration to save: the loaded value when the operator left the seconds field unchanged
/// (keeps 500 ms from collapsing to 0 s), else the edited whole seconds.
/// </summary>
public static TimeSpan Save(int seconds, TimeSpan? loaded)
=> loaded is { } l && ToSeconds(l) == seconds ? l : TimeSpan.FromSeconds(seconds);
}