using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Driver.Modbus.Tests; /// /// CONV-4 (Modbus leg) — Modbus keys per-host resilience per SLAVE UNIT /// (host:port/unitN). An authored raw tag carries its own unitId in its TagConfig so /// multi-unit tags key their own breaker; resolves a RawPath /// through the driver's authored RawPath → definition table. Under v3 the reference is always a /// RawPath — an unauthored RawPath falls back to the driver-level host. /// [Trait("Category", "Unit")] public sealed class ModbusUnitIdResolveHostTests { private sealed class NoopTransport : IModbusTransport { public Task ConnectAsync(CancellationToken ct) => Task.CompletedTask; public Task SendAsync(byte unitId, byte[] pdu, CancellationToken ct) => Task.FromResult(new byte[] { 0x03, 0x00 }); public ValueTask DisposeAsync() => ValueTask.CompletedTask; } private static async Task NewDriverAsync(params RawTagEntry[] rawTags) { var drv = new ModbusDriver( new ModbusDriverOptions { Host = "10.0.0.1", Port = 502, UnitId = 1, RawTags = rawTags, Probe = new ModbusProbeOptions { Enabled = false }, }, "modbus-1", _ => new NoopTransport()); await drv.InitializeAsync("{}", CancellationToken.None); return drv; } /// The mapper reads an optional unitId into the definition. [Fact] public void FromTagConfig_reads_optional_unitId() { var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","unitId":7}"""; ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/dev1/U7", out var def).ShouldBeTrue(); def.Name.ShouldBe("cell/modbus/dev1/U7"); def.UnitId.ShouldBe((byte)7); } /// An absent unitId leaves the definition on the driver-level default (null override). [Fact] public void FromTagConfig_absent_unitId_is_null() { var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16"}"""; ModbusTagDefinitionFactory.FromTagConfig(json, "cell/modbus/dev1/U0", out var def).ShouldBeTrue(); def.UnitId.ShouldBeNull(); } /// An authored RawPath carrying a unitId keys its own per-unit host name. [Fact] public async Task RawPath_WithUnitId_ResolvesPerUnitHostName() { const string rawPath = "cell/modbus/dev1/U7"; var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16","unitId":7}"""; var drv = await NewDriverAsync(new RawTagEntry(rawPath, json, false)); drv.ResolveHost(rawPath).ShouldBe("10.0.0.1:502/unit7"); } /// An authored RawPath without a unitId keys the driver-level unit host name. [Fact] public async Task RawPath_WithoutUnitId_KeysDriverDefaultUnit() { const string rawPath = "cell/modbus/dev1/U0"; var json = """{"region":"HoldingRegisters","address":0,"dataType":"Int16"}"""; var drv = await NewDriverAsync(new RawTagEntry(rawPath, json, false)); drv.ResolveHost(rawPath).ShouldBe("10.0.0.1:502/unit1"); } }