// Read-only #700 probe against a deployed OtOpcUa endpoint (lmxopcua#700). // Sends only Browse/Read/HistoryRead. Credential: env OTOPCUA_PROBE_APIKEY (otua__), never printed. // Usage: dotnet run -- using System.Globalization; using System.Text.Json; using Opc.Ua; using Opc.Ua.Client; var endpointUrl = args.Length > 0 ? args[0] : "opc.tcp://wonder-app-vd03.zmr.zimmer.com:4840/OtOpcUa"; var outPath = args.Length > 1 ? args[1] : "gate700-vd03.json"; // "focas" mode (args[2]): anonymous session; reads ServiceLevel and every Variable under the FOCAS driver's raw subtree. var focasMode = args.Length > 2 && args[2] == "focas"; var key = focasMode ? null : Environment.GetEnvironmentVariable("OTOPCUA_PROBE_APIKEY") ?? throw new InvalidOperationException("OTOPCUA_PROBE_APIKEY not set"); var ct = CancellationToken.None; var telemetry = DefaultTelemetry.Create(_ => { }); var pki = Path.Combine(Path.GetTempPath(), $"gate700-probe-pki-{Guid.NewGuid():N}"); var appConfig = new ApplicationConfiguration(telemetry) { ApplicationName = "OtOpcUa.Gate700Probe", ApplicationUri = $"urn:OtOpcUa.Gate700Probe.{Guid.NewGuid():N}", ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "own") }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "issuer") }, TrustedPeerCertificates = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "trusted") }, RejectedCertificateStore = new CertificateTrustList { StoreType = CertificateStoreType.Directory, StorePath = Path.Combine(pki, "rejected") }, AutoAcceptUntrustedCertificates = true, }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 120_000 }, }; await appConfig.ValidateAsync(ApplicationType.Client, ct); var endpoint = await CoreClientUtils.SelectEndpointAsync(appConfig, endpointUrl, false, telemetry, ct); using var session = await new DefaultSessionFactory(telemetry).CreateAsync(appConfig, new ConfiguredEndpoint(null, endpoint, EndpointConfiguration.Create(appConfig)), false, false, "Gate700Probe", 120_000, key is null ? new UserIdentity() : new UserIdentity("apikey", System.Text.Encoding.UTF8.GetBytes(key)), default, ct); if (focasMode) { var ns = (ushort)session.NamespaceUris.GetIndex("https://zb.com/otopcua/raw"); var slv = await session.ReadAsync(null, 0, TimestampsToReturn.Neither, new[] { new ReadValueId { NodeId = VariableIds.Server_ServiceLevel, AttributeId = Attributes.Value } }, ct); Console.WriteLine($"ServiceLevel={Fmt(Clr(slv.Results.ToList()[0].WrappedValue))}"); var vars = new List(); var queue = new Queue(new[] { new NodeId("focas-z-34184", ns) }); while (queue.Count > 0) { var b = await session.BrowseAsync(null, null, 0, new[] { new BrowseDescription { NodeId = queue.Dequeue(), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } }, ct); foreach (var r in b.Results.ToList()[0].References.ToList()) { var id = ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris); if (r.NodeClass == NodeClass.Variable) vars.Add(id); else if (r.NodeClass == NodeClass.Object) queue.Enqueue(id); } } var rv = await session.ReadAsync(null, 0, TimestampsToReturn.Both, vars.Select(v => new ReadValueId { NodeId = v, AttributeId = Attributes.Value }).ToArray(), ct); var res = rv.Results.ToList(); var byStatus = res.GroupBy(r => SName(r.StatusCode)).Select(g => $"{g.Key}={g.Count()}"); Console.WriteLine($"FOCAS raw variables={vars.Count}: {string.Join(", ", byStatus)}"); for (var i = 0; i < vars.Count; i++) if (res[i].StatusCode.Code != 0) Console.WriteLine($" {vars[i].Identifier} {SName(res[i].StatusCode)}"); await session.CloseAsync(ct); return 0; } var report = new Dictionary(); var cases = new List>(); report["endpoint"] = endpointUrl; report["securityMode"] = endpoint.SecurityMode.ToString(); report["runUtc"] = DateTime.UtcNow.ToString("o"); var rawNs = session.NamespaceUris.GetIndex("https://zb.com/otopcua/raw"); NodeId N(string tag) => new($"gate700-hist/Device1/{tag}", (ushort)rawNs); var wtc1 = N("wtc1-float"); var sec = N("systimesec-byte"); var pulse = N("syspulse-byte"); var missing = N("missing-double"); // ServiceLevel + server build var sl = await session.ReadAsync(null, 0, TimestampsToReturn.Neither, new[] { new ReadValueId { NodeId = VariableIds.Server_ServiceLevel, AttributeId = Attributes.Value }, new ReadValueId { NodeId = VariableIds.Server_ServerStatus_BuildInfo_SoftwareVersion, AttributeId = Attributes.Value }, new ReadValueId { NodeId = VariableIds.Server_ServerStatus_BuildInfo_BuildNumber, AttributeId = Attributes.Value } }, ct); var slr = sl.Results.ToList(); report["serviceLevel"] = Fmt(Clr(slr[0].WrappedValue)); report["softwareVersion"] = Fmt(Clr(slr[1].WrappedValue)); report["buildNumber"] = Fmt(Clr(slr[2].WrappedValue)); // Node attributes var attrs = new Dictionary(); foreach (var (name, node) in new[] { ("wtc1-float", wtc1), ("systimesec-byte", sec), ("syspulse-byte", pulse), ("missing-double", missing) }) { var ids = new (string Name, uint Id)[] { ("Historizing", Attributes.Historizing), ("AccessLevel", Attributes.AccessLevel), ("UserAccessLevel", Attributes.UserAccessLevel), ("DataType", Attributes.DataType) }; var r = await session.ReadAsync(null, 0, TimestampsToReturn.Neither, ids.Select(a => new ReadValueId { NodeId = node, AttributeId = a.Id }).ToArray(), ct); var rr = r.Results.ToList(); attrs[name] = ids.Select((a, i) => (a.Name, V: rr[i].StatusCode.Code == 0 ? Fmt(Clr(rr[i].WrappedValue)) : SName(rr[i].StatusCode))) .ToDictionary(x => x.Name, x => (object?)x.V); } report["nodeAttributes"] = attrs; // Aggregates advertised var aggBrowse = await session.BrowseAsync(null, null, 0, new[] { new BrowseDescription { NodeId = ObjectIds.HistoryServerCapabilities_AggregateFunctions, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.Organizes, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } }, ct); report["aggregateFunctions"] = string.Join(",", aggBrowse.Results.ToList()[0].References.ToList().Select(r => r.BrowseName.Name).OrderBy(n => n, StringComparer.Ordinal)); DateTime U(string s) => DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); // ---- cases await Raw("missing raw", missing, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:01:00Z"), 0); await Processed("missing Average 20s", missing, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:01:00Z"), 20_000, ObjectIds.AggregateFunction_Average); await Processed("missing TimeAverage 20s", missing, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:01:00Z"), 20_000, ObjectIds.AggregateFunction_TimeAverage); await AtTime("missing AtTime", missing, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:00:30Z")); await Raw("SysTimeSec raw 10s", sec, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:00:10Z"), 0); await AtTime("SysTimeSec AtTime stored+mid", sec, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:00:01.5Z")); foreach (var (n, a) in new[] { ("Average", ObjectIds.AggregateFunction_Average), ("Minimum", ObjectIds.AggregateFunction_Minimum), ("Maximum", ObjectIds.AggregateFunction_Maximum), ("Count", ObjectIds.AggregateFunction_Count), ("Start", ObjectIds.AggregateFunction_Start), ("End", ObjectIds.AggregateFunction_End), ("TimeAverage", ObjectIds.AggregateFunction_TimeAverage), ("Total", ObjectIds.AggregateFunction_Total), ("TimeAverage2", ObjectIds.AggregateFunction_TimeAverage2) }) await Processed($"SysTimeSec {n} 20s", sec, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:01:00Z"), 20_000, a); await Processed("SysTimeSec Average 20s reverse", sec, U("2026-11-11T14:01:00Z"), U("2026-11-11T14:00:00Z"), 20_000, ObjectIds.AggregateFunction_Average); await Modified("SysTimeSec ReadModified", sec, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:01:00Z")); await Raw("SysPulse raw 3min", pulse, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:03:00Z"), 0); await AtTime("SysPulse AtTime", pulse, U("2026-11-11T14:00:30Z"), U("2026-11-11T14:01:30Z")); await Processed("SysPulse Average 60s", pulse, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:03:00Z"), 60_000, ObjectIds.AggregateFunction_Average); await Raw("WTC1 raw 10s", wtc1, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:00:10Z"), 0); await AtTime("WTC1 AtTime", wtc1, U("2026-11-11T14:00:00Z"), U("2026-11-11T14:00:01Z")); await Processed("WTC1 Average 60s over the NULL outage", wtc1, U("2026-11-10T11:31:00Z"), U("2026-11-10T11:40:00Z"), 60_000, ObjectIds.AggregateFunction_Average); await Processed("WTC1 TimeAverage 60s", wtc1, U("2026-11-10T11:31:00Z"), U("2026-11-10T11:40:00Z"), 60_000, ObjectIds.AggregateFunction_TimeAverage); await Raw("WTC1 end-only latest 3 before 11:38 (stopped tag reverse), first page", wtc1, DateTime.MinValue, U("2026-11-10T11:38:00Z"), 3, maxPages: 1); await Raw("WTC1 end-only latest 3 before 11:38, 100 pages", wtc1, DateTime.MinValue, U("2026-11-10T11:38:00Z"), 3); await Raw("WTC1 reverse raw 11:32:40 -> 11:32:20", wtc1, U("2026-11-10T11:32:40Z"), U("2026-11-10T11:32:20Z"), 0); var now = DateTime.UtcNow; await AtTime("WTC1 future AtTime +30m/+1h/+2h", wtc1, now.AddMinutes(30), now.AddHours(1), now.AddHours(2)); await AtTime("SysTimeSec future AtTime +30m/+1h/+2h", sec, now.AddMinutes(30), now.AddHours(1), now.AddHours(2)); report["cases"] = cases; await File.WriteAllTextAsync(outPath, JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }), ct); await session.CloseAsync(ct); foreach (var c in cases) Console.WriteLine($"{c["case"],-58} {c["status"],-34} rows={c["rows"]} types={c["types"]} {c["ms"]}ms"); try { Directory.Delete(pki, true); } catch { } return 0; // ---------------------------------------------------------------- helpers async Task Raw(string name, NodeId node, DateTime start, DateTime end, uint max, int maxPages = 100) { var d = new ReadRawModifiedDetails { StartTime = start, EndTime = end, NumValuesPerNode = max, IsReadModified = false, ReturnBounds = false }; await Run(name, node, d, null, maxPages); } async Task Modified(string name, NodeId node, DateTime start, DateTime end) { var d = new ReadRawModifiedDetails { StartTime = start, EndTime = end, NumValuesPerNode = 0, IsReadModified = true }; await Run(name, node, d); } async Task Processed(string name, NodeId node, DateTime start, DateTime end, double interval, NodeId agg) { var d = new ReadProcessedDetails { StartTime = start, EndTime = end, ProcessingInterval = interval, AggregateType = new List { agg }, AggregateConfiguration = new AggregateConfiguration { UseServerCapabilitiesDefaults = true } }; await Run(name, node, d); } async Task AtTime(string name, NodeId node, params DateTime[] times) { var d = new ReadAtTimeDetails { ReqTimes = times.Select(t => (DateTimeUtc)t).ToList(), UseSimpleBounds = true }; await Run(name, node, d, times); } async Task Run(string name, NodeId node, IEncodeable details, DateTime[]? requested = null, int maxPages = 100) { var sw = System.Diagnostics.Stopwatch.StartNew(); var rows = new List>(); var types = new SortedSet(StringComparer.Ordinal); ByteString cp = default; string status; var pages = 0; do { var resp = await session.HistoryReadAsync(null, new ExtensionObject(details), TimestampsToReturn.Both, false, new HistoryReadValueId[] { new() { NodeId = node, ContinuationPoint = cp } }, ct); var res = resp.Results.ToList()[0]; status = SName(res.StatusCode); cp = res.ContinuationPoint; pages++; if (!res.HistoryData.IsNull && ExtensionObject.ToEncodeable(res.HistoryData) is HistoryData hd) foreach (var dv in hd.DataValues.ToList()) { var v = Clr(dv.WrappedValue); if (v is not null) types.Add(v.GetType().Name); rows.Add(new() { ["v"] = Fmt(v), ["t"] = v?.GetType().Name, ["s"] = $"0x{dv.StatusCode.Code:X8}", ["src"] = ((DateTime)dv.SourceTimestamp).ToString("o") }); } if (status.StartsWith("Bad", StringComparison.Ordinal)) break; } while (!cp.IsEmpty && pages < maxPages); sw.Stop(); var leftOpen = !cp.IsEmpty; if (leftOpen) // release the server-side continuation point await session.HistoryReadAsync(null, new ExtensionObject(details), TimestampsToReturn.Both, true, new HistoryReadValueId[] { new() { NodeId = node, ContinuationPoint = cp } }, ct); var c = new Dictionary { ["case"] = name, ["node"] = node.ToString(), ["status"] = status, ["pages"] = pages, ["rows"] = rows.Count, ["types"] = string.Join("|", types), ["ms"] = sw.ElapsedMilliseconds, ["continuationLeft"] = leftOpen, ["data"] = rows }; if (requested is not null) c["requested"] = requested.Select(t => t.ToString("o")).ToList(); cases.Add(c); } static object? Clr(Variant value) => value.AsBoxedObject(Variant.BoxingBehavior.Legacy) switch { ByteString b => b.IsNull ? null : b.ToArray(), DateTimeUtc t => (DateTime)t, Uuid id => (Guid)id, var o => o, }; static string? Fmt(object? v) => v switch { null => null, DateTime d => d.ToString("o"), IFormattable f => f.ToString(null, CultureInfo.InvariantCulture), _ => v.ToString() }; static string SName(StatusCode code) => code.SymbolicId is { Length: > 0 } s ? s : $"0x{code.Code:X8}";