using Opc.Ua; using OpcUaHelper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TeamAAS_VP.Enums; using TeamAAS_VP.Interfaces; using TeamAAS_VP.Models; namespace TeamAAS_VP.Core.PLCs { public class OPCuaClientPLC : IPlc { public Guid Id{ get; private set; } public CommunicationType CommunicationType { get; private set; } public string EndpointUrl { get; private set; } public string Name { get; private set; } public OpcUaClient OpcUaClient { get; private set; } public bool IsConnected { get { return OpcUaClient.Connected; } } public event Action ConnectChangedEvent; public OPCuaClientPLC(Guid id, string name, string endpointUrl, CommunicationType communicationType) { Id = id; Name = name; EndpointUrl = endpointUrl; CommunicationType = communicationType; OpcUaClient = new OpcUaClient(); // 初始化PLC连接 OpcUaClient.UserIdentity = new UserIdentity(new AnonymousIdentityToken()); // connect to server, this is a sample try { OpcUaClient.ConnectComplete += OpcUaClient_ConnectComplete; OpcUaClient.ReconnectStarting += OpcUaClient_ReconnectStarting; OpcUaClient.ReconnectComplete += OpcUaClient_ReconnectComplete; OpcUaClient.OpcStatusChange += OpcUaClient_OpcStatusChange; } catch (Exception ex) { return; } } public OPCuaClientPLC(PlcInfo plcInfo) { Id = plcInfo.Id; Name = plcInfo.Name; EndpointUrl = plcInfo.EndpointUrl; CommunicationType = plcInfo.CommunicationType; OpcUaClient = new OpcUaClient(); // 初始化PLC连接 OpcUaClient.UserIdentity = new UserIdentity(new AnonymousIdentityToken()); // connect to server, this is a sample try { OpcUaClient.ConnectComplete += OpcUaClient_ConnectComplete; OpcUaClient.ReconnectStarting += OpcUaClient_ReconnectStarting; OpcUaClient.ReconnectComplete += OpcUaClient_ReconnectComplete; OpcUaClient.OpcStatusChange += OpcUaClient_OpcStatusChange; } catch (Exception ex) { return; } } public void Connect() { OpcUaClient.ConnectServer(EndpointUrl); } public Task ConnectAsync() { return OpcUaClient.ConnectServer(EndpointUrl); } public void Disconnect() { OpcUaClient.Disconnect(); } public void Dispose() { OpcUaClient.Disconnect(); OpcUaClient.ConnectComplete -= OpcUaClient_ConnectComplete; OpcUaClient.ReconnectStarting -= OpcUaClient_ReconnectStarting; OpcUaClient.ReconnectComplete -= OpcUaClient_ReconnectComplete; OpcUaClient.OpcStatusChange -= OpcUaClient_OpcStatusChange; } #region OPC事件 private void OpcUaClient_OpcStatusChange(object sender, OpcUaStatusEventArgs e) { //LogHelper.WriteLogInfo($"OPC状态发生改变:Error:{e.Error},Time:{e.Time},Text:{e.Text}"); } private void OpcUaClient_ReconnectComplete(object sender, EventArgs e) { ConnectChangedEvent?.Invoke(this, OpcUaClient.Connected); } private void OpcUaClient_ReconnectStarting(object sender, EventArgs e) { ConnectChangedEvent?.Invoke(this, OpcUaClient.Connected); } private void OpcUaClient_ConnectComplete(object sender, EventArgs e) { ConnectChangedEvent?.Invoke(this, OpcUaClient.Connected); } #endregion } }