using System.Net; using System.Net.Sockets; namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Browser.IntegrationTests; /// /// Reachability gate for the shared opc-plc fixture (OPCUA_SIM_ENDPOINT, default /// opc.tcp://10.100.0.35:50000). A small copy of the probe in /// Driver.OpcUaClient.IntegrationTests/OpcPlcFixture rather than a cross-project reference — /// that project drags the whole driver in. Tests call first, so a /// machine without the simulator reports Skipped instead of a connect failure. /// internal static class OpcPlcProbe { private const string EndpointEnvVar = "OPCUA_SIM_ENDPOINT"; private const string DefaultEndpoint = "opc.tcp://10.100.0.35:50000"; /// The simulator endpoint the tests should connect to. public static string Endpoint => Environment.GetEnvironmentVariable(EndpointEnvVar) is { Length: > 0 } e ? e : DefaultEndpoint; private static readonly Lazy Reason = new(Probe); /// Skips the calling test when opc-plc does not accept a TCP connection (probed once per run). public static void SkipUnlessReachable() { if (Reason.Value is { } reason) Xunit.Assert.Skip(reason); } private static string? Probe() { var body = Endpoint.StartsWith("opc.tcp://", StringComparison.OrdinalIgnoreCase) ? Endpoint["opc.tcp://".Length..] : Endpoint; var slash = body.IndexOf('/'); if (slash >= 0) body = body[..slash]; var colon = body.LastIndexOf(':'); var host = colon >= 0 ? body[..colon] : body; var port = colon >= 0 && int.TryParse(body[(colon + 1)..], out var p) ? p : 4840; try { using var client = new TcpClient(AddressFamily.InterNetwork); var addr = Dns.GetHostAddresses(host).FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? IPAddress.Loopback; if (client.ConnectAsync(addr, port).Wait(TimeSpan.FromSeconds(2)) && client.Connected) return null; return $"opc-plc simulator at {host}:{port} did not accept a TCP connection within 2s. Start it or override {EndpointEnvVar}."; } catch (Exception ex) { return $"opc-plc simulator at {host}:{port} unreachable: {ex.GetType().Name}: {ex.Message}. Start it or override {EndpointEnvVar}."; } } }