public void ConnectToServer() { try { //LOCAL OPC CONNECTION kepware //url = new Opc.URL("opcda://PCNAME/Kepware.KEPServerEX.V6"); //LOCAL OPC CONNECTION RSLinx //url = new Opc.URL("opcda://PCNAME/RSLinx OPC Server"); //REMOTE OPC CONNECTION WHEN USING opcexpert tunneling url = new Opc.URL("opcda://PCNAME/RSLinx Remote OPC Server.REMOTEPCNAME"); //REMOTE RSLinx OPC //this requires DCOM setup //url = new Opc.URL("opcda://PCNAME/RSLinx Remote OPC Server"); server = new Opc.Da.Server(fact, url); System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(); Opc.ConnectData connecteddata = new Opc.ConnectData(networkCredential); server.Connect(url, connecteddata); groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group"; groupState.UpdateRate = 1; // this isthe time between every reads from OPC server groupState.Active = true; //this must be true if you the group has to read value groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState); groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(UpdateTagData); //callback when the data are readed Opc.Da.Item[] items_read = groupRead.AddItems(createSomeTags()); } catch (Exception E) { Console.WriteLine(E.Message); } }
/// <summary> /// Initializes object with the specified ItemResult object. /// </summary> public ItemUrl(ItemUrl item) : base(item) { if (item != null) { Url = item.Url; } }
/// <summary> /// Create the server(Using the specified URL) /// </summary> /// <param name="url"></param> /// <returns></returns> private static Opc.Server GetServerForUrl(Opc.URL url) { if (url == null) { throw new ArgumentNullException("url"); } return(url.Scheme == Opc.UrlScheme.DA ? new Opc.Da.Server(new OpcCom.Factory(), url) : null); }
public void ConnectToServer() { try { url = new Opc.URL("opcda://IAPENG1/RSLinx OPC Server"); //server = new Opc.Da.Server(fact, null); server = new Opc.Da.Server(fact, url); System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(); Opc.ConnectData connecteddata = new Opc.ConnectData(networkCredential); server.Connect(url, connecteddata); groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group"; groupState.UpdateRate = 1000; // this isthe time between every reads from OPC server groupState.Active = true; //this must be true if you the group has to read value groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState); groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(UpdateTagData); //callback when the data are readed if (items[0] == null) { items[0] = new Opc.Da.Item(); items[1] = new Opc.Da.Item(); items[2] = new Opc.Da.Item(); items[3] = new Opc.Da.Item(); items[4] = new Opc.Da.Item(); items[5] = new Opc.Da.Item(); items[6] = new Opc.Da.Item(); items[7] = new Opc.Da.Item(); } items[0].ItemName = "[PLC2]LocalDateTime[0]"; items[1].ItemName = "[PLC2]LocalDateTime[1]"; items[2].ItemName = "[PLC2]LocalDateTime[2]"; items[3].ItemName = "[PLC2]LocalDateTime[3]"; items[4].ItemName = "[PLC2]LocalDateTime[4]"; items[5].ItemName = "[PLC2]LocalDateTime[5]"; items[6].ItemName = "[PLC2]LocalDateTime[6]"; items[7].ItemName = "[PLC2]LocalDateTime"; items = groupRead.AddItems(items); // Create a write group groupStateWrite = new Opc.Da.SubscriptionState(); groupStateWrite.Name = "Group Write"; groupStateWrite.Active = false;//not needed to read if you want to write only groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupStateWrite); } catch (Exception E) { Console.WriteLine(E.Message); } }
/// <summary> /// Connect/Disconnect to the server. /// </summary> /// <returns></returns> private bool Connect() { // Connect server var url = new Opc.URL(OpcConnectionString); // Create an unconnected server object. OpcServer = GetServerForUrl(url); if (OpcServer == null) { return(false); } // Invoke the connect server callback. try { var connectData = new Opc.ConnectData(Credential, null); OpcServer.Connect(connectData); var opcDaSrerver = OpcServer as Opc.Da.Server; if (opcDaSrerver == null) { return(false); } VendorInfo = opcDaSrerver.GetStatus().VendorInfo; VersionInfo = opcDaSrerver.GetStatus().ProductVersion; StatusInfo = opcDaSrerver.GetStatus().StatusInfo; var state = new Opc.Da.SubscriptionState { ClientHandle = Guid.NewGuid().ToString(), ServerHandle = null, //Name = "DEFAULT", Active = false, UpdateRate = 1000, KeepAlive = 0, //Deadband = 0, //Locale = null }; Subscription = (Subscription)opcDaSrerver.CreateSubscription(state); } catch (Exception e) { throw e; } return(true); }
public Form1() { InitializeComponent(); OpcCom.ServerEnumerator se = new ServerEnumerator(); Opc.Server[] Servers; String sErrFunc = ""; Opc.ConnectData cd = new Opc.ConnectData(new System.Net.NetworkCredential()); sErrFunc = "GetAvailableServers"; Servers = se.GetAvailableServers(Opc.Specification.COM_DA_20, "localhost", cd); Console.WriteLine(Servers[1].Name.ToString()); Opc.URL url = new Opc.URL("opcda://localhost/" + Servers[0].Name); OpcCom.Factory fact = new OpcCom.Factory(); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); }
public void Connect() { try { XmlElement docRoot = _xmlDocument.DocumentElement; foreach (XmlNode driverNode in docRoot.ChildNodes) { if (driverNode.Attributes["Id"].Value.Equals("6A1B8105-BD9A-4658-870F-D35D4029C928")) { OpcCom.Factory fact = new OpcCom.Factory(); _opcDaServer = new Opc.Da.Server(fact, null); Opc.URL url = new Opc.URL(driverNode.Attributes["OpcServerUrl"].Value); _opcDaServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void ConnectToServer() { try { //url = new Opc.URL("opcda://MUHUMTHA/Kepware.KEPServerEX.V6"); //url = new Opc.URL("opcda://IAPENG1/RSLinx OPC Server"); //REMOTE OPC CONNECTION url = new Opc.URL("opcda://MUHUMTHA/RSLinx OPC Server.MUHUNTHANPC"); server = new Opc.Da.Server(fact, url); System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(); Opc.ConnectData connecteddata = new Opc.ConnectData(networkCredential); server.Connect(url, connecteddata); groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group"; groupState.UpdateRate = 1; // this isthe time between every reads from OPC server groupState.Active = true; //this must be true if you the group has to read value groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState); groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(UpdateTagData); //callback when the data are readed //Opc.Da.Item[] items_read = groupRead.AddItems(createSomeTags()); Opc.Da.Item[] items_read = groupRead.AddItems(createSomeTags()); // Create a write group //groupStateWrite = new Opc.Da.SubscriptionState(); //groupStateWrite.Name = "Group_Write"; //groupStateWrite.UpdateRate = 1000; //groupStateWrite.Active = false;//not needed to read if you want to write only //groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupStateWrite); //groupWrite.DataChanged += new Opc.Da.DataChangedEventHandler(ReadCompleted); Global.flag1 = true; } catch (Exception E) { Console.WriteLine(E.Message); } }
/// <summary> /// Connects to the OPC Server /// </summary> /// <param name="OPCURL"> /// The OPC URL should be in the following form (Examples): /// - opcae://localhost/Matrikon.OPC.Simulation /// - opcda://192.168.1.2/Matrikon.OPC.Simulation /// </param> /// <param name="credentials"></param> public Opc.Da.Server ConnectToOPCServer(string OPCURL, NetworkCredential credentials = null) { Opc.Da.Server OPCDAServerToConnectTo = null; try { URL URL = new Opc.URL(OPCURL); OPCDAServerToConnectTo = _OPCDAServers.FirstOrDefault(S => S.Url.ToString() == OPCURL); if (OPCDAServerToConnectTo == null) { _OPCDAServers.Add(OPCDAServerToConnectTo = new Opc.Da.Server(new OpcCom.Factory(), null)); } if (!OPCDAServerToConnectTo.IsConnected) { OPCDAServerToConnectTo.Connect(URL, new ConnectData(credentials)); } return(OPCDAServerToConnectTo); } catch (Exception ex) { OPCDAServerToConnectTo?.Disconnect(); OPCDAServerToConnectTo?.Dispose(); throw ex; } }
public void Work() { int i = 5; if (i == 1) { url = new Opc.URL("opcda://192.168.0.4/OPC.PHDServerDA.1"); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); Opc.Da.Item[] itemCollection = new Opc.Da.Item[1]; itemCollection[0] = new Opc.Da.Item { ItemName = "RTOS.TEST.PV", MaxAge = -1 }; Opc.Da.ItemValueResult[] result = server.Read(itemCollection); Console.WriteLine(result[0].Value); server.Disconnect(); } else if (i == 2) { url = new Opc.URL("opcda://192.168.0.4/OPC.PHDServerDA.1"); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group"; groupState.ServerHandle = null; groupState.ClientHandle = Guid.NewGuid().ToString(); groupState.Active = true; groupState.UpdateRate = 1000; groupState.Deadband = 0; groupState.Locale = null; groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState); string[] itemName = { "RTOS.TEST.PV", "RTOR.TI1237.DACA.PV" }; Opc.Da.Item[] items = new Opc.Da.Item[2]; for (int j = 0; j < items.Length; j++) { items[j] = new Opc.Da.Item(); items[j].ClientHandle = Guid.NewGuid().ToString(); items[j].ItemPath = null; items[j].ItemName = itemName[j]; } groupRead.AddItems(items); //groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(group_DataChanged); Opc.Da.ItemValueResult[] results = groupRead.Read(groupRead.Items); foreach (ItemValueResult result in results) { Console.WriteLine("{0},{1},{2},{3}", result.ItemName, result.Value, result.Quality, result.Timestamp); } //groupRead.DataChanged -= new Opc.Da.DataChangedEventHandler(group_DataChanged); groupRead.RemoveItems(groupRead.Items); server.CancelSubscription(groupRead); groupRead.Dispose(); server.Disconnect(); } else if (i == 3) { url = new Opc.URL("opcda://192.168.0.4/OPC.PHDServerDA.1"); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group"; groupState.ServerHandle = null; groupState.ClientHandle = Guid.NewGuid().ToString(); groupState.Active = true; groupState.UpdateRate = 1000; groupState.Deadband = 0; groupState.Locale = null; groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupState); string[] itemName = { "RTOS.TEST.PV", "RTOS.TEST2.PV" }; Opc.Da.Item[] items = new Opc.Da.Item[2]; for (int j = 0; j < items.Length; j++) { items[j] = new Opc.Da.Item(); items[j].ClientHandle = Guid.NewGuid().ToString(); items[j].ItemPath = null; items[j].ItemName = itemName[j]; } groupWrite.AddItems(items); //groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(group_DataChanged); Opc.Da.ItemValue[] writeValues = new Opc.Da.ItemValue[groupWrite.Items.Length]; for (int k = 0; k < groupWrite.Items.Length; k++) { writeValues[k] = new Opc.Da.ItemValue((ItemIdentifier)groupWrite.Items[k]); } writeValues[0].Value = 5; writeValues[1].Value = 6; groupWrite.Write(writeValues); Console.WriteLine("Press any key to close..."); Console.ReadLine(); //groupRead.DataChanged -= new Opc.Da.DataChangedEventHandler(group_DataChanged); groupWrite.RemoveItems(groupWrite.Items); server.CancelSubscription(groupWrite); groupWrite.Dispose(); server.Disconnect(); } else if (i == 4) { url = new Opc.URL("opchda://192.168.0.4/OPC.PHDServerHDA.1"); serverHda = new Opc.Hda.Server(fact, null); serverHda.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); try { } catch (Opc.ConnectFailedException opcConnEx) { Console.WriteLine(string.Format("Could not connect to server {0}", "OPC.PHDServerHDA.1")); Console.WriteLine(opcConnEx.ToString()); } Console.WriteLine("Are we connected? " + serverHda.IsConnected); string[] itemName = { "RTOS.TEST.PV", "RTOS.TEST2.PV" }; Opc.Hda.Trend groupHda = new Trend(serverHda); groupHda.Name = "HDA"; groupHda.AggregateID = AggregateID.NOAGGREGATE; DateTime startTime = DateTime.Now.AddHours(-1); DateTime endTime = DateTime.Now; groupHda.StartTime = new Opc.Hda.Time(startTime); groupHda.EndTime = new Opc.Hda.Time(endTime); groupHda.MaxValues = 0; groupHda.IncludeBounds = false; serverHda.Trends.Add(groupHda); Opc.Hda.Item[] items = new Opc.Hda.Item[2]; for (int m = 0; m < 2; m++) { items[m] = new Opc.Hda.Item(); items[m].ItemName = itemName[m]; items[m].ItemPath = null; items[m].ClientHandle = Guid.NewGuid().ToString(); } IdentifiedResult[] identifiedResult = serverHda.CreateItems(items); if (identifiedResult != null) { foreach (IdentifiedResult item in identifiedResult) { if (item.ResultID.Succeeded()) { groupHda.Items.Add(new Opc.Hda.Item(item)); } } } Opc.Hda.ItemValueCollection[] results = groupHda.ReadRaw(); Opc.Hda.ItemValueCollection result1 = results[0]; foreach (Opc.Hda.ItemValue result in result1) { Console.WriteLine("{0},{1},{2}", result.Value, result.Quality, result.Timestamp); } serverHda.Disconnect(); } else if (i == 5) { url = new Opc.URL("opchda://192.168.0.4/OPC.PHDServerHDA.1"); serverHda = new Opc.Hda.Server(fact, null); serverHda.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); try { } catch (Opc.ConnectFailedException opcConnEx) { Console.WriteLine(string.Format("Could not connect to server {0}", "OPC.PHDServerHDA.1")); Console.WriteLine(opcConnEx.ToString()); } Console.WriteLine("Are we connected? " + serverHda.IsConnected); string[] itemName = { "RTOR.TI1237.DACA.PV", "RTOS.TEST2.PV" }; Opc.Hda.Trend groupHda = new Trend(serverHda); groupHda.Name = "HDA"; groupHda.AggregateID = AggregateID.AVERAGE; DateTime startTime = DateTime.Now.AddHours(-1); DateTime endTime = DateTime.Now; //TimeSpan span = endTime.Subtract(startTime); //int calcInterval = ((int)span.TotalSeconds); //groupHda.ResampleInterval = (decimal)calcInterval; //DateTime startTime = new DateTime(2020, 6, 12, 9, 0, 0, 0); //DateTime endTime = new DateTime(2020, 6, 12, 10, 0, 0, 0); int calcInterval = 300; groupHda.ResampleInterval = (decimal)calcInterval; groupHda.StartTime = new Opc.Hda.Time(startTime); groupHda.EndTime = new Opc.Hda.Time(endTime); groupHda.MaxValues = 0; groupHda.IncludeBounds = false; serverHda.Trends.Add(groupHda); Opc.Hda.Item[] items = new Opc.Hda.Item[2]; for (int m = 0; m < 2; m++) { items[m] = new Opc.Hda.Item(); items[m].ItemName = itemName[m]; items[m].ItemPath = null; items[m].ClientHandle = Guid.NewGuid().ToString(); } IdentifiedResult[] identifiedResult = serverHda.CreateItems(items); if (identifiedResult != null) { foreach (IdentifiedResult item in identifiedResult) { if (item.ResultID.Succeeded()) { groupHda.Items.Add(new Opc.Hda.Item(item)); } } } Opc.Hda.ItemValueCollection[] results = groupHda.ReadProcessed(); Opc.Hda.ItemValueCollection result1 = results[0]; foreach (Opc.Hda.ItemValue result in result1) { Console.WriteLine("{0},{1},{2}", result.Value, result.Quality, result.Timestamp); } serverHda.Disconnect(); } }
// Connect to OPC HDA server public bool Connect(string HostName, string ServerName) { var url = new Opc.URL(); url.Scheme = Opc.UrlScheme.HDA; url.HostName = HostName; url.Path = ServerName; try { var fact = new OpcCom.Factory(); if ((_OPCServer != null) && (!_OPCServer.IsConnected)) { _trace.TraceEvent(TraceEventType.Verbose, 0, "_OPCServer is disconnected, disposing object"); //Unfortunately, in case of lost connection simply calling .Connect() doesn't work :( //Let's try to recreate the object from scratch _OPCServer.Dispose(); _OPCServer = null; } if (_OPCServer == null) { _trace.TraceEvent(TraceEventType.Verbose, 0, "_OPCServer is null, creating new object"); _OPCServer = new Opc.Hda.Server(fact, null); } if (!_OPCServer.IsConnected) { _trace.TraceEvent(TraceEventType.Verbose, 0, "OPC server is disconnected, trying to connect"); _OPCServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential(), null)); if (!_OPCServer.IsConnected) { _trace.TraceEvent(TraceEventType.Error, 0, "Connection failed without exception: {0}", url.ToString()); return(false); } _trace.TraceEvent(TraceEventType.Verbose, 0, "Succesfully connected to {0}, obj: {1}", url.ToString(), _OPCServer.GetHashCode().ToString()); } try { Status = _OPCServer.GetStatus(); _trace.TraceEvent(TraceEventType.Verbose, 0, "OPC server status:\n" + "\tCurrentTime: {0}\n" + "\tMaxReturnValues: {1}\n" + "\tProductVersion: {2}\n" + "\tServerState: {3}\n" + "\tStartTime: {4}\n" + "\tStatusInfo: {5}\n" + "\tVendorInfo: {6}\n", Status.CurrentTime, Status.MaxReturnValues, Status.ProductVersion, Status.ServerState, Status.StartTime, Status.StatusInfo, Status.VendorInfo); } catch (Exception e) { _trace.TraceEvent(TraceEventType.Warning, 0, "Can't get server status: {0}, {1}", url.ToString(), e.Message); } try { _trace.TraceEvent(TraceEventType.Verbose, 0, "SupportedAggregates:"); SupportedAggregates = _OPCServer.GetAggregates(); foreach (Opc.Hda.Aggregate agg in SupportedAggregates) { _trace.TraceEvent(TraceEventType.Verbose, 0, "{0}\t{1}\t{2}", agg.ID, agg.Name, agg.Description); } } catch (Exception e) { _trace.TraceEvent(TraceEventType.Warning, 0, "Can't get server supported aggregates: {0}, {1}", url.ToString(), e.Message); } } catch (Exception e) { _trace.TraceEvent(TraceEventType.Error, 0, "Connection failed: {0}, {1}", url.ToString(), e.Message); return(false); } return(true); }
/// <summary> /// Opc와 연결을 합니다. /// </summary> /// <returns></returns> public override bool Open() { string strMsg = string.Format("(Node:{0} / ProgID : {1} )", strIp, ProgId); try { if (opc != null) { close(); } string add; //주소를 만들어 준다. if (strIp.Equals(string.Empty)) { add = $"opcda://localhost/{ProgId}"; } else { add = $"opcda://{strIp}/{ProgId}"; } opc = new Opc.Da.Server(fact, null); url = new Opc.URL(add); //서버에 연결 opc.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); //연결 후 - 테스트 할것 //opc.ServerShutdown //그룹생성 OpcGrp_State = new Opc.Da.SubscriptionState(); OpcGrp_State.Name = strGrpName; OpcGrp_State.UpdateRate = intUpdateRate; OpcGrp_State.Active = true; OpcGrp = (Opc.Da.Subscription)opc.CreateSubscription(OpcGrp_State); OpcGrp.DataChanged += OpcGrp_DataChanged; //opc 연결상태 체크 Timer를 시작한다. if (this.tmrOpcCheck != null) { tmrOpcCheck.Dispose(); tmrOpcCheck = null; } // this.bolOpcStatus = true; // this.ChConnection_Status(bolOpcStatus); tmrOpcCheck = new Timer(new TimerCallback(tmrCheckOpcStatus), null, 0, intUpdateRate); //this.ChConnection_Status(true); strMsg = "Open 성공" + strMsg; return(true); } catch (System.Runtime.InteropServices.ExternalException ex) { //activex이기 때문에 에러 발생이 제대로 되지 않아 몇가지만... strMsg = "Open 실패 :" + ex.Message + strMsg + "\r\n" + ex.ToString(); throw ComException(ex, string.Empty); } catch (Exception ex) { strMsg = "Open 실패 :" + ex.Message + strMsg + "\r\n" + ex.ToString(); throw ex; } finally { PLCModule.clsPLCModule.LogWrite("Open", strMsg); } }
/// <summary> /// Initializes the object with an ItemIdentifier object and url. /// </summary> public ItemUrl(ItemIdentifier item, Opc.URL url) : base(item) { Url = url; }
public ClientTRK() { url = new Opc.URL("opcda://localhost/Kepware.KEPServerEX.V6"); }