using Microsoft.AspNetCore.Http; using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Configuration; using System.Diagnostics; using System.Text; using System.Threading; #pragma warning disable CS0618 namespace Lab505.Infrastructure.Protocols.OpcUa; public class OpcUaClient(string EndpointUrl, string configSection, ILogger logger, Lab505.Application.Services.INotificationService? notif = null) { private string _endpointUrl = EndpointUrl; private readonly ApplicationInstance appInstance = new() { ApplicationName = "OPC UA RCS Client", ApplicationType = ApplicationType.Client, ConfigSectionName = configSection, }; private Opc.Ua.Client.ISession? session; private UaNodeResolver? _resolver; public readonly IUserIdentity userIdentity = new UserIdentity(); private readonly SessionReconnectHandler sessionReconnectHandler = new(); private readonly SemaphoreSlim _opcLock = new(1, 1); private CancellationTokenSource? _clientCts; private Task? _connectLoopTask; public event Action? ConnectChanged; public int KeepAliveInterval { get; init; } = 1000; /// Tên thiết bị hiển thị trong thông báo kết nối. public string Name { get; init; } = "Dobot"; /// /// true: khi kết nối sẽ browse server và cập nhật RCSNodeIds + Generated/RCSNodeIds.g.cs (server RCS của IMR/Dobot). /// Đặt false cho server khác (vd ASRS gateway) để không ghi đè map của RCS. /// public bool PublishRcsNodeIds { get; init; } = true; public bool IsConnected => session != null && session.Connected; // ==================================================================================== // START / STOP // ==================================================================================== public async Task Start() { await appInstance.LoadApplicationConfigurationAsync(silent: false); await appInstance.CheckApplicationInstanceCertificatesAsync(silent: false); _clientCts = new CancellationTokenSource(); _connectLoopTask = Task.Run(() => ConnectLoop(_clientCts.Token)); } public async Task Stop() { _clientCts?.Cancel(); if (_connectLoopTask != null) await _connectLoopTask; if (session != null) { try { session.KeepAlive -= Session_KeepAlive; session.Close(false); } catch { } session.Dispose(); session = null; } } /// Đổi endpoint và ngắt session hiện tại — ConnectLoop sẽ tự reconnect. public async Task SwitchEndpointAsync(string newUrl) { _endpointUrl = newUrl; if (session != null) { try { session.KeepAlive -= Session_KeepAlive; session.Close(false); } catch { } session.Dispose(); session = null; } logger.LogWarning("OPC UA disconnected (endpoint switch → {Url})", _endpointUrl); ConnectChanged?.Invoke(false); notif?.Notify($"[OPC] {Name} ngắt kết nối (switch endpoint)", "warning"); } private async Task ConnectLoop(CancellationToken token) { while (!token.IsCancellationRequested) { try { if (session == null || !session.Connected) { await TryConnect(); } } catch (Exception ex) { logger.LogWarning(ex, "OPC UA ConnectLoop error"); } await Task.Delay(1000, token); } } private async Task TryConnect() { var appConfig = appInstance.ApplicationConfiguration; var epCfg = EndpointConfiguration.Create(appConfig); var epDesc = CoreClientUtils.SelectEndpoint(appConfig, _endpointUrl, false, 500); var endpoint = new ConfiguredEndpoint(null, epDesc, epCfg); var newSession = await Session.Create( appConfig, endpoint, false, false, appConfig.ApplicationName, 60 * 1000, userIdentity, null); if (newSession != null && newSession.Connected) SetConnection(newSession); } // ==================================================================================== // SESSION SETUP // ==================================================================================== private void SetConnection(Opc.Ua.Client.ISession _session) { Utils.SilentDispose(session); session = _session; session.KeepAliveInterval = KeepAliveInterval; session.DeleteSubscriptionsOnClose = false; session.TransferSubscriptionsOnReconnect = true; session.KeepAlive += Session_KeepAlive; if (PublishRcsNodeIds) { _resolver = new UaNodeResolver(session); GenerateRcsNodeIds(_resolver); foreach (var kv in _resolver.Map) RCSNodeIds.Update(kv.Key, kv.Value); } logger.LogInformation("OPC UA connected: {Url}", _endpointUrl); ConnectChanged?.Invoke(true); notif?.Notify($"[OPC] {Name} kết nối thành công", "success"); } // ==================================================================================== // KEEP ALIVE // ==================================================================================== private void Session_KeepAlive(Opc.Ua.Client.ISession _session, KeepAliveEventArgs e) { try { if (session == null || !ReferenceEquals(_session, session)) { _session.KeepAlive -= Session_KeepAlive; return; } if (ServiceResult.IsBad(e.Status) || !session.Connected) { sessionReconnectHandler.BeginReconnect(session, null, 1000, Client_ReconnectComplete); logger.LogWarning("OPC UA connection lost (KeepAlive bad status: {Status})", e.Status); ConnectChanged?.Invoke(false); notif?.Notify($"[OPC] {Name} mất kết nối !", "error"); } } catch (Exception ex) { logger.LogWarning(ex, "OPC UA KeepAlive error"); } } private readonly object _reconnectLock = new(); private void Client_ReconnectComplete(object? sender, EventArgs e) { lock (_reconnectLock) { if (sessionReconnectHandler.Session != null && !ReferenceEquals(session, sessionReconnectHandler.Session)) { SetConnection(sessionReconnectHandler.Session); } } } // ==================================================================================== // SAFE READ (with semaphore) // ==================================================================================== public async Task ReadAsync(NodeId variableId) { if (session == null || !session.Connected) return null; await _opcLock.WaitAsync(); try { return session.ReadValue(variableId).Value; } catch (Exception ex) { logger.LogDebug(ex, "OPC Read failed for {NodeId}", variableId); return null; } finally { _opcLock.Release(); } } public object? Read(NodeId variableId) => ReadAsync(variableId).GetAwaiter().GetResult(); /// /// Batch read multiple nodes in a single OPC UA round-trip. /// Returns null for each node that failed or session is disconnected. /// public async Task ReadManyAsync(NodeId[] nodeIds) { if (session == null || !session.Connected) return new object?[nodeIds.Length]; var readValueIds = new ReadValueIdCollection(nodeIds.Select(id => new ReadValueId { NodeId = id, AttributeId = Attributes.Value })); await _opcLock.WaitAsync(); try { session.Read(null, 0, TimestampsToReturn.Neither, readValueIds, out DataValueCollection results, out DiagnosticInfoCollection _); return results.Select(r => StatusCode.IsGood(r.StatusCode) ? r.Value : null).ToArray(); } catch { return new object?[nodeIds.Length]; } finally { _opcLock.Release(); } } // ==================================================================================== // SAFE CALL (with semaphore) // ==================================================================================== public async Task> CallAsync(NodeId objectId, NodeId methodId, params object[] args) { if (session == null || !session.Connected) return Array.Empty(); await _opcLock.WaitAsync(); try { return session.Call(objectId, methodId, args); } catch (Exception ex) { logger.LogDebug(ex, "OPC Call failed for {MethodId}", methodId); return Array.Empty(); } finally { _opcLock.Release(); } } public IList Call(NodeId objectId, NodeId methodId, params object[] args) => CallAsync(objectId, methodId, args).GetAwaiter().GetResult(); /// /// Giống CallAsync nhưng không nuốt lỗi: ném InvalidOperationException khi chưa kết nối, /// ServiceResultException khi server từ chối — caller biết chắc lệnh có tới server hay không. /// Không giữ _opcLock: method có thể chạy nhiều phút (ASRS chờ PLC xong), Read/poll vẫn phải chạy song song. /// public async Task> CallCheckedAsync(NodeId objectId, NodeId methodId, object[] args, CancellationToken ct = default) { var s = session; if (s == null || !s.Connected) throw new InvalidOperationException($"OPC UA {Name} chưa kết nối"); return await s.CallAsync(objectId, methodId, ct, args); } /// /// Tìm NodeId theo đường dẫn BrowseName (TranslateBrowsePathsToNodeIds) — không phụ thuộc NodeId server tự đặt. /// Mỗi bước đi theo HierarchicalReferences (gồm Organizes, HasComponent, ...). /// Phần tử kết quả = null nếu đường dẫn không tồn tại. /// public async Task TranslateBrowsePathsAsync(NodeId startNode, IReadOnlyList paths, CancellationToken ct = default) { var s = session; if (s == null || !s.Connected) throw new InvalidOperationException($"OPC UA {Name} chưa kết nối"); var browsePaths = new BrowsePathCollection(paths.Select(path => new BrowsePath { StartingNode = startNode, RelativePath = new RelativePath { Elements = new RelativePathElementCollection(path.Select(name => new RelativePathElement { ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, IsInverse = false, TargetName = name })) } })); var response = await s.TranslateBrowsePathsToNodeIdsAsync(null, browsePaths, ct); return response.Results .Select(r => StatusCode.IsGood(r.StatusCode) && r.Targets.Count > 0 ? ExpandedNodeId.ToNodeId(r.Targets[0].TargetId, s.NamespaceUris) : null) .ToArray(); } /// Namespace index của trên server hiện tại, -1 nếu chưa kết nối hoặc không có. public int GetNamespaceIndex(string uri) { var s = session; return s != null && s.Connected ? s.NamespaceUris.GetIndex(uri) : -1; } // ==================================================================================== // AUTO GENERATE RCSNodeIds.g.cs // ==================================================================================== private void GenerateRcsNodeIds(UaNodeResolver resolver) { string folder = Path.Combine(Directory.GetCurrentDirectory(), "Generated"); Directory.CreateDirectory(folder); string filePath = Path.Combine(folder, "RCSNodeIds.g.cs"); var sb = new StringBuilder(); sb.AppendLine("using Opc.Ua;"); sb.AppendLine("namespace Lab505.Infrastructure.Protocols.OpcUa;"); sb.AppendLine(); sb.AppendLine("public static partial class RCSNodeIds"); sb.AppendLine("{"); var used = new HashSet(); foreach (var kv in resolver.Map.OrderBy(k => k.Key)) { string name = kv.Key; string unique = name; int i = 2; while (used.Contains(unique)) unique = $"{name}_{i++}"; used.Add(unique); NodeId id = kv.Value; string ctor = id.IdType switch { IdType.Numeric => $"new NodeId({id.Identifier}, {id.NamespaceIndex})", IdType.String => $"new NodeId(\"{id.Identifier}\", {id.NamespaceIndex})", _ => $"new NodeId(\"{id}\")" }; sb.AppendLine($" public static NodeId {unique} => {ctor};"); } sb.AppendLine("}"); string newContent = sb.ToString(); if (!File.Exists(filePath) || File.ReadAllText(filePath, Encoding.UTF8) != newContent) File.WriteAllText(filePath, newContent, Encoding.UTF8); } }