public void Connect(string serverName) { /* When the factory creates an HDA server, it passes along 2 parameters: * SerializationInfo info * StreamingContext context * * The Factory class casts the COM object (pointing to the HDA server) to the IServer interface. * All calls to the interface or proxied to the COM object. */ Opc.URL url = new Opc.URL(String.Format("opchda://localhost/{0}", serverName)); OpcCom.Factory fact = new OpcCom.Factory(); _hdaServer = new Opc.Hda.Server(fact, url); try { _hdaServer.Connect(); Console.WriteLine(String.Format("Connect to server {0}", serverName)); } catch(Opc.ConnectFailedException opcConnExc) { Console.WriteLine(String.Format("Could not connect to server {0}", serverName)); Console.WriteLine(opcConnExc.ToString()); } Console.WriteLine("Are we connected? " + _hdaServer.IsConnected); }
/// <summary> /// Tries to connect to the server. /// </summary> public bool Connect(string serverurl) { if (String.IsNullOrEmpty(serverurl)) { throw new Exception(String.Format("Server url '{0}' is not valid", serverurl)); } Opc.URL url = new Opc.URL(serverurl); OpcCom.Factory fact = new OpcCom.Factory(); Server = new Opc.Da.Server(fact, null); try { Server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch (Exception ex) { _error.Append(ex.ToString()); if (ex.InnerException != null) { _error.Append(ex.InnerException.ToString()); } return(false); } return(true); }
/// <summary> /// Creates a server object for the specified URL. /// </summary> public static global::Opc.Server GetServerForURL(Opc.URL url, Opc.Specification preferedspecification) { if (url == null) { throw new ArgumentNullException("url"); } global::Opc.Server server = null; // create an unconnected server object for XML based servers. if (url.Scheme == Opc.UrlScheme.HTTP) { throw new NotImplementedException("TODO - reoved dependency on OpcXml assembly."); //server = new Server( new OpcXml.Factory(), url, preferedspecification ); } // create an unconnected server object for COM based servers. else { // DA if (url.Scheme == Opc.UrlScheme.DA) { server = new Server(new OpcCom.Factory(), url, preferedspecification); } // AE else if (url.Scheme == Opc.UrlScheme.AE) { server = new global::Opc.Ae.Server(new OpcCom.Factory(), url, preferedspecification); } // HDA else if (url.Scheme == Opc.UrlScheme.HDA) { server = new global::Opc.Hda.Server(new OpcCom.Factory(), url, preferedspecification); } // DX else if (url.Scheme == Opc.UrlScheme.DX) { server = new global::Opc.Dx.Server(new OpcCom.Factory(), url, preferedspecification); } #if (UA) // UA else if (url.Scheme == UrlScheme.UA_TCP || url.Scheme == UrlScheme.UA_HTTP) { server = new Opc.Ua.Server(new OpcXml.Factory(), url, preferedspecification); } #endif // Other specifications not supported yet. else { throw new NotSupportedException(url.Scheme); } } return(server); }
private void button2_Click(object sender, EventArgs e) { // 1st: Create a server object and connect to the RSLinx OPC Server url = new Opc.URL(Settings1.OPCConnectionString); server = new Opc.Da.Server(fact, null); listBox1.Items.Add("1st: Create a server object and connect to the RSLinx OPC Server"); //2nd: Connect to the created server server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); listBox1.Items.Add("2nd: Connect to the created server"); //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; 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 += GroupRead_DataChanged;; //listBox1.Items.Add("Add event"); items = new Opc.Da.Item[1]; items[0] = new Opc.Da.Item(); items[0].ItemName = Settings1.OPCIntVarName; items = groupRead.AddItems(items); listBox1.Items.Add("Add Items"); Opc.Da.ItemValueResult[] values = groupRead.Read(items); listBox1.Items.Add("Read(items)"); listBox1.Items.Add("========================"); listBox1.Items.Add(Convert.ToInt32(values[0].Value.ToString())); }
public void Connect(string serverName) { /* When the factory creates an HDA server, it passes along 2 parameters: * SerializationInfo info * StreamingContext context * * The Factory class casts the COM object (pointing to the HDA server) to the IServer interface. * All calls to the interface or proxied to the COM object. */ Opc.URL url = new Opc.URL(String.Format("opchda://localhost/{0}", serverName)); OpcCom.Factory fact = new OpcCom.Factory(); _hdaServer = new Opc.Hda.Server(fact, url); try { _hdaServer.Connect(); Console.WriteLine(String.Format("Connect to server {0}", serverName)); } catch (Opc.ConnectFailedException opcConnExc) { Console.WriteLine(String.Format("Could not connect to server {0}", serverName)); Console.WriteLine(opcConnExc.ToString()); } Console.WriteLine("Are we connected? " + _hdaServer.IsConnected); }
public Boolean Connect() { // Create a server object and connect to the TwinCATOpcServer Opc.URL url = new Opc.URL(opcServerEndpoint); OpcCom.Factory fact = new OpcCom.Factory(); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); // Create a group Opc.Da.Subscription group; foreach (BrowsableGroup BrowsableGroup in browsableGroups) { Opc.Da.SubscriptionState groupState = new SubscriptionState(); groupState.Name = BrowsableGroup.GroupName; groupState.Active = true; group = (Opc.Da.Subscription)server.CreateSubscription(groupState); Opc.Da.Item[] items = BrowsableGroup.produceItemsFromNodes(); items = group.AddItems(items); EnableDataChangedCallback(group); //todo: //EnableDataReadCallback(group); //todo: //EnableDataWriteCallback(group, BrowsableGroup.produceValueToWrite(items[0],34.0) ); } return(false); }
/// <summary> /// Připojení k OPC serveru. Volající musí ošetřit případnou výjimku /// </summary> /// <param name="serverUrl">Adresa OPC serveru (např "opcda://localhost/OPC.SimaticNET.DP")</param> public void pripojit(string serverUrl) { /* //Odpojení od serveru * if (server != null) * try * { * server.Disconnect(); //Zde se to v některých případech zasekne, tak jsem to raději zrušil a při opětovném připojení si OPC server inkrementuje počet připojených klientů. Možná by to šlo přes timer... * } * catch * { * }*/ //Připojení k serveru string strErr = ""; try { strErr = "Chyba při připojování na server. "; Opc.URL url; url = new Opc.URL(serverUrl); OpcCom.Factory fact = new OpcCom.Factory(); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); strErr = "Chyba při vytváření groups. "; vytvoritGroups(server); strErr = "Chyba při vytváření items. "; vytvoritItems(); } catch (Exception ex) { throw new Exception(strErr + ex.Message); } }
/// <summary> /// Server connection procedure /// </summary> /// <param name="urlString">OPC server URL in string format</param> /// <returns>isConnected</returns> public bool ConnectServer(string urlString) { isConnected = false; this.url = new Opc.URL(urlString); factory = new OpcCom.Factory(); server = new Opc.Da.Server(factory, url); try { selectedServer = selectedServer ?? new mServerItem(true); server.Connect(); if (isConnected = server.IsConnected) { OnReportMessage(0, "Server is connected"); server.ServerShutdown -= server_ServerShutdown; server.ServerShutdown += server_ServerShutdown; RefreshServerStatus(); } else { OnReportMessage("Server connection fail, unknown error"); } } catch (Exception ex) { OnReportMessage(ex.Message.ToString()); } return(isConnected); }
internal OPCSessionServer(OPCCliConfiguration.ServersRow server, OpcDa::BrowseFilters filters, OPCEnvironment node) : base(server.Name, null, node) { LastEception = null; try { m_Menu = new ContextMenuServer(this); Opc.URL url = new Opc.URL(server.URL); if (server.GetConnectDataRows().Length > 0) { m_ConnectData = server.GetConnectDataRows()[0].GetConnectData(); } m_Spcification = new Opc.Specification() { ID = server.PreferedSpecyficationID, Description = server.PreferedSpecyficationDsc }; Tag = (Server)Factory.GetServerForURL(url, m_Spcification); server.GetOptions(this); foreach (OPCCliConfiguration.SubscriptionsRow rw in server.GetSubscriptionsRows()) { new SubscriptionTreeNodeSession(rw, this); } State = state.disconnectd; } catch (Exception ex) { ReportException(ex); } }
private void InitializeOPC() { try { if (File.Exists("settings.xml")) { this.CurrentCounterOfMaterial = 0; XmlSerializer XmlSerializer1 = new XmlSerializer(typeof(Settings)); TextReader reader1 = new StreamReader("settings.xml"); Settings Settings1 = (Settings)XmlSerializer1.Deserialize(reader1); reader1.Dispose(); if (Settings1.OPCVariablesInitialized == true) { // 1st: Create a server object and connect to the RSLinx OPC Server url = new Opc.URL(Settings1.OPCConnectionString); server = new Opc.Da.Server(fact, null); //2nd: Connect to the created server server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; 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 += groupRead_DataChanged; items[0] = new Opc.Da.Item(); items[0].ItemName = Settings1.OPCCounterName; items[1] = new Opc.Da.Item(); items[1].ItemName = Settings1.OPCSpeedName; items = groupRead.AddItems(items); Opc.Da.ItemValueResult[] values = groupRead.Read(items); this.previous_value_of_counter = Convert.ToInt32(values[0].Value); this.VariablesInitialized = true; } } else { MessageBox.Show("OPC settings is empty. See Settings - > Connection..."); this.VariablesInitialized = false; } } catch { MessageBox.Show("Bad OPC connection. Review connection string"); this.VariablesInitialized = false; } }
public static Opc.Hda.Server ServerHdaConnect() { var tagsList = new Tags(); //Задаем расположение серверов foreach (var tag in tagsList.GetMassurm()) { switch (tag.Name) { case "MasterIpHda": MasterIpHda = tag.Value; break; case "SlaveIpHda": SlaveIpHda = tag.Value; break; case "OpcHdaId": OpcHdaId = tag.Value; break; } } //const string masterIpHda = "localhost"; //const string slaveIpHda = "localhost"; //const string opcHdaId = "Infinity.OPCHDAServer"; //Соединение с сервером var url = new Opc.URL("opchda://" + MasterIpHda + "/" + OpcHdaId); var serverHda = new Opc.Hda.Server(new OpcCom.Factory(), url); try { serverHda.Connect(); } catch { url = new Opc.URL("opchda://" + SlaveIpHda + "/" + OpcHdaId); serverHda = new Opc.Hda.Server(new OpcCom.Factory(), url); try { serverHda.Connect(); } catch (Exception) { MessageBox.Show(@"Отсутствует лицензия или проверьте подключения к серверу C:\Tag.ini", @"Ошибка подключения сервера", MessageBoxButton.OK, MessageBoxImage.Error); Environment.Exit(0); } } // System.Threading.Thread.Sleep(1500); return(serverHda); }
public OPC_class(String in_URL, String in_CounterName, String in_SpeedName) { try { this.VariablesInitialized = false; // 1st: Create a server object and connect Opc.URL url = new Opc.URL(in_URL); Opc.Da.Server server = new Opc.Da.Server(fact, null); //2nd: Connect to the created server //server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); try { server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch (Exception Ex) { MessageBox.Show(Ex.Message); //return false; } //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; 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 += groupRead_DataChanged; items[0] = new Opc.Da.Item(); items[0].ItemName = in_CounterName; items[1] = new Opc.Da.Item(); items[1].ItemName = in_SpeedName; items = groupRead.AddItems(items); Opc.Da.ItemValueResult[] values = groupRead.Read(items); MessageBox.Show("Counter = " + values[0].Value.ToString() + " Speed = " + values[1].Value.ToString()); //if no exeption this.URL = in_URL; this.VariablesInitialized = true; } catch { this.VariablesInitialized = false; } }
public OPC_class(String in_URL, String in_CounterName, String in_SpeedName) { try { this.VariablesInitialized = false; // 1st: Create a server object and connect Opc.URL url = new Opc.URL(in_URL); Opc.Da.Server server = new Opc.Da.Server(fact, null); //2nd: Connect to the created server //server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); try { server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch (Exception Ex) { MessageBox.Show(Ex.Message); //return false; } //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; 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 += groupRead_DataChanged; items[0] = new Opc.Da.Item(); items[0].ItemName = in_CounterName; items[1] = new Opc.Da.Item(); items[1].ItemName = in_SpeedName; items = groupRead.AddItems(items); Opc.Da.ItemValueResult[] values = groupRead.Read(items); MessageBox.Show("Counter = " + values[0].Value.ToString() + " Speed = " + values[1].Value.ToString()); //if no exeption this.URL = in_URL; this.VariablesInitialized = true; } catch { this.VariablesInitialized = false; } }
public void Connect(string url) { try { m_url = new Opc.URL(url); m_server = new Opc.Da.Server(m_factory, null); m_server.Connect(m_url, new Opc.ConnectData(new System.Net.NetworkCredential())); //Console.WriteLine("IsConnected: " + m_server.IsConnected.ToString()); } catch (Exception ee) { // aditional handling throw ee; } }
public Boolean Connect() { // Create a server object and connects to Opc.URL url = new Opc.URL(opcServerEndpoint); Factory fact = new Factory(); server = new Server(fact, null); server.Connect(url, new Opc.ConnectData(new NetworkCredential())); string root = getRootName(server); recursiveTreeFill(server, root); subscribeToNodes(root); return(false); }
/// <summary> /// 连接HDA服务器 /// </summary> /// <param name="hostName">主机名称或者IP</param> /// <param name="serverName">服务器名称</param> public bool Connect() { Opc.URL url = new Opc.URL(String.Format("opchda://" + _hostName + @"/{0}", _serverName)); OpcCom.Factory fact = new OpcCom.Factory(); _hdaServer = new Opc.Hda.Server(fact, url); try { _hdaServer.Connect(); //Console.WriteLine(String.Format("Connect to server {0}", serverName)); } catch (Opc.ConnectFailedException opcConnExc) { Console.WriteLine(String.Format("Could not connect to server {0}", _serverName)); Console.WriteLine(opcConnExc.ToString()); //return false; } return(_hdaServer.IsConnected ? true : false); //Console.WriteLine("Are we connected? " + _hdaServer.IsConnected); }
/// <summary> /// Подключение к серверу OPC. /// </summary> /// <overloads> </overloads> public void Connect(string hostIp, string serverId) { // Создание URL //string url = "opcda://localhost/opcserversim.Instance.1"; string url = "opcda://" + hostIp + "/" + serverId; var opcUrl = new Opc.URL(url); var connectData = new Opc.ConnectData(new System.Net.NetworkCredential()); try { serverHandle.Connect(opcUrl, connectData); isConnected = true; Console.WriteLine("Connected to {0}", url); } catch (Exception exception) { Console.WriteLine("Failed to connect - status {0}", exception); } }
public bool Connect(string serverUrl) { var opcServerUrl = new Opc.URL(serverUrl); Server = new Opc.Da.Server(new OpcCom.Factory(), opcServerUrl); try { //System.Net.NetworkCredential credentials = null; //System.Net.WebProxy webProxy = null; var connectData = new Opc.ConnectData(null, null); Server.Connect(connectData); var status = Server.GetStatus(); VendorInfo = status.VendorInfo; VersionInfo = status.ProductVersion; StatusInfo = status.StatusInfo; // Assign a globally unique handle to the subscription. var state = new Opc.Da.SubscriptionState() { Name = "RSLinxConnectApp", Active = false, UpdateRate = 1000, KeepAlive = 0, Deadband = 0, Locale = null, ClientHandle = Guid.NewGuid().ToString(), ServerHandle = null }; Subscription = Server.CreateSubscription(state) as Opc.Da.Subscription; return(true); } catch (Exception e) { StatusInfo = e.Message; Console.WriteLine(e.Message); } return(false); }
/// <summary> /// Tries to connect to the server. /// </summary> private void Connect() { Opc.URL url = new Opc.URL("opcda://localhost/" + _serverName); OpcCom.Factory fact = new OpcCom.Factory(); _server = new Opc.Da.Server(fact, null); try { _server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch (Exception ex) { _error.Append(ex.ToString()); if (ex.InnerException != null) { _error.Append(ex.InnerException.ToString()); } } }
/// <summary> /// Подключение к серверу OPC. Данные для подключения берутся из конфигурационного файла. /// </summary> public void Connect() { // Создание URL string url = "opcda://localhost/" + config.opcServerId; //string url = "opcda://" + config.amicumIp + "/" + config.opcServerId; var opcUrl = new Opc.URL(url); var connectData = new Opc.ConnectData(new System.Net.NetworkCredential()); try { serverHandle.Connect(opcUrl, connectData); isConnected = true; InitTagList(); Console.WriteLine("Connected to {0}", url); } catch (Exception exception) { Console.WriteLine("Failed to connect - status {0}", exception); } }
public override bool Initialize(string connectionString, int newPollerId) { bool result = false; ConnString = connectionString; try { PollerId = newPollerId; url = new Opc.URL(connectionString); server = null; var fact = new OpcCom.Factory(); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); server.ServerShutdown += Shutdown; _tags = new List <Opc.Da.Item>(); Browse(); _groupWriteState = new Opc.Da.SubscriptionState(); _groupWriteState.Name = "GroupWrite"; _groupWriteState.Active = false; groupWrite = (Opc.Da.Subscription)server.CreateSubscription(_groupWriteState); Activated = true; logger.Logged("Info", "Состояние сервера: " + server.GetStatus().StatusInfo, "", ""); result = true; } catch (Exception ex) { logger.Logged("Error", "Не удалось подключиться к OPC DA серверу " + connectionString + ": " + ex.Message, "", ""); // logger.Logged("Warn", "Повторная попытка через 5 секунд...", "", ""); //Thread.Sleep(5000); } return(result); }
private bool Connected = false; // True if connection was successful //--------------------------------------------------------------------- // Initialise Communication: public bool Init(List <OPCVar> OPCEventVarListIn, List <OPCVar> OPCWriteVarListIn, string UrlIn, string OPCTopicIn) { //Connect to the OPC server: Connected = false; OPCTopic = OPCTopicIn; //Build dictionary of event variable data: OPCEventVars = new Dictionary <string, OPCVarData>(); NumEventVars = 0; foreach (OPCVar OPCVarIn in OPCEventVarListIn) { OPCEventVars.Add(OPCVarIn.RefName, new OPCVarData()); OPCEventVars[OPCVarIn.RefName].Name = OPCVarIn.Name; OPCEventVars[OPCVarIn.RefName].VarType = OPCVarIn.VarType; OPCEventVars[OPCVarIn.RefName].NotificationReceived = false; OPCEventVars[OPCVarIn.RefName].ItemEventIndex = 0; OPCEventVars[OPCVarIn.RefName].FullName = OPCTopic + OPCVarIn.Name; NumEventVars++; } // End foreach //Build dictionary of write variable data: OPCWriteVars = new Dictionary <string, OPCVarData>(); foreach (OPCVar OPCVarIn in OPCWriteVarListIn) { OPCWriteVars.Add(OPCVarIn.RefName, new OPCVarData()); OPCWriteVars[OPCVarIn.RefName].Name = OPCVarIn.Name; OPCWriteVars[OPCVarIn.RefName].VarType = OPCVarIn.VarType; OPCWriteVars[OPCVarIn.RefName].FullName = OPCTopic + OPCVarIn.Name; } // End foreach try { // Connect to OPC server: Url = new Opc.URL(UrlIn); Server = new Opc.Da.Server(Factory, null); Server.Connect(Url, new Opc.ConnectData(new System.Net.NetworkCredential())); // 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); // Create an event group: groupStateEvents = new Opc.Da.SubscriptionState(); groupStateEvents.Name = "Group Events"; groupStateEvents.Active = true; groupEvents = (Opc.Da.Subscription)Server.CreateSubscription(groupStateEvents); // Add items to the event group: Opc.Da.Item[] itemsEvents = new Opc.Da.Item[NumEventVars]; int j = 0; foreach (OPCVar OPCVarIn in OPCEventVarListIn) { OPCEventVars[OPCVarIn.RefName].ItemEventIndex = j; itemsEvents[j] = new Opc.Da.Item(); itemsEvents[j].ItemName = OPCEventVars[OPCVarIn.RefName].FullName; j++; } itemsEvents = groupEvents.AddItems(itemsEvents); groupEvents.DataChanged += new Opc.Da.DataChangedEventHandler(OnTransactionCompleted); Connected = true; return(true); } catch { return(false); } }
public void Connect_OPC() { //Console.WriteLine("Connect_OPC"); try { servername = Pub_dtTSetting.Rows[0][2].ToString(); if (servername != "") { Opc.URL url = new Opc.URL("opcda://" + Pub_dtTSetting.Rows[0][1].ToString() + "/" + Pub_dtTSetting.Rows[0][2].ToString()); Opc.Da.Server serveropc = null; OpcCom.Factory fact = new OpcCom.Factory(); //Kepware.KEPServerEX.V6 Opc.Da.ServerStatus serverStatus = new Opc.Da.ServerStatus(); //serveropc = new Opc.Da.Server(fact, null); serveropc = new Opc.Da.Server(fact, url); System.Net.NetworkCredential mCredentials = new System.Net.NetworkCredential(); Opc.ConnectData mConnectData = new Opc.ConnectData(mCredentials); try { //2nd: Connect to the created server serveropc.Connect(url, mConnectData); #if DEBUG_ERROR #warning you must install RSLinx server OR Kepware.KEPServerEX.V6 for install important .dll then you can easy test with Kepware.KEPServerEX.V6 #endif //serveropc.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); //ไม่เปิดเซิฟเวอ จะติดตรงนี้ serverStatus = serveropc.GetStatus(); servercurrent_status = serverStatus.ServerState.ToString(); ServerStatusInTime.Text = serverStatus.ServerState.ToString(); //Append Log file if server Status running------------------------------------------------- string CompareServerstatus = "running"; if (serverStatus.ServerState.ToString() == CompareServerstatus) { if (PortStatus.Text.ToString() == "Stop") { //StartPort.Visible = true; } string timeinlog = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd HH:mm:ss= "); if (write_log == false) //First Time Write Log { using (StreamWriter sw = File.AppendText(AppendFilepath)) { sw.WriteLine(timeinlog + Pub_dtTSetting.Rows[0][2].ToString() + " DCOM security The operation completed successfully"); sw.WriteLine(timeinlog + "Connected to OPC server"); sw.WriteLine(timeinlog + "MyGroup Added group to server The operation completed successfully"); } } write_log = true; // 1 mean don't write agian use in ReadCompleteCallback } //---------------------------------------------------------------- //3rd Create a group if items Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = "group"; groupState.Active = true; group = (Opc.Da.Subscription)serveropc.CreateSubscription(groupState); // add items to the group Opc.Da.Item[] items = new Opc.Da.Item[Pub_dtTTAGMapping.Rows.Count]; //Add item by DataTable From Function Get_TagMapping for (int index_Tag = 0; index_Tag < Pub_dtTTAGMapping.Rows.Count; index_Tag++) { items[index_Tag] = new Opc.Da.Item(); //Tag_Name items[index_Tag].ItemName = Pub_dtTTAGMapping.Rows[index_Tag][2].ToString();//Pub_dtTTAGMapping.Rows[Row][Column] } items = group.AddItems(items); this.timerModbus.Interval = (Convert.ToInt32(Pub_dtTSetting.Rows[0][5]) * 100); this.timerModbus.AutoReset = false; this.timerModbus.Start(); }//end try catch (Exception) { servercurrent_status = "Stop"; //Exception Server Not Run string timeinlog = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd HH:mm:ss= "); write_log = false; // 1 mean don't write agian use in ReadCompleteCallback ServerStatusInTime.Text = "Stop"; using (StreamWriter sw = File.AppendText(AppendFilepath)) { //Pub_dtTSetting.Rows[0][2].ToString() => ServerName sw.WriteLine(timeinlog + Pub_dtTSetting.Rows[0][2].ToString() + " DCOM security The operation completed successfully"); sw.WriteLine(timeinlog + "Unable to connect to OPC server"); sw.WriteLine(timeinlog + "MyGroup Unable to add group to server Unspecified error"); sw.WriteLine(timeinlog + "Service will be Reconnect To OPC Server With in 1 minutes"); } this.timerModbus.Interval = (Convert.ToInt32(Pub_dtTSetting.Rows[0][5])) * 1000; this.timerModbus.AutoReset = false; this.timerModbus.Start(); } //end catch } //end if } catch (Exception ex) { using (StreamWriter sw = File.AppendText(indebuglogFolderPath + "\\" + filename + ".txt")) { sw.WriteLine("ERROR : " + ex); } } // 1st: Create a server object and connect to the RSLinx OPC Server }
/// <summary> /// Connects to the specified COM server server. /// </summary> public static object Connect(Opc.URL url, Opc.ConnectData connectData) { // parse path to find prog id and clsid. string progID = url.Path; string clsid = null; int index = url.Path.LastIndexOf('/'); if (index >= 0) { progID = url.Path.Substring(0, index); clsid = url.Path.Substring(index + 1); } // look up prog id if clsid not specified in the url. Guid guid; if (clsid == null) { // use OpcEnum to lookup the prog id. guid = new ServerEnumerator().CLSIDFromProgID(progID, url.HostName, connectData); // check if prog id is actually a clsid string. if (guid == Guid.Empty) { try { guid = new Guid(progID); } catch { throw new Opc.ConnectFailedException(progID); } } } // convert clsid string to a guid. else { try { guid = new Guid(clsid); } catch { throw new Opc.ConnectFailedException(clsid); } } // get the credentials. NetworkCredential credentials = (connectData != null)?connectData.GetCredential(null, null):null; // instantiate the server using CoCreateInstanceEx. if (connectData == null || connectData.LicenseKey == null) { try { return(OpcCom.Interop.CreateInstance(guid, url.HostName, credentials)); } catch (Exception e) { throw new Opc.ConnectFailedException(e); } } // instantiate the server using IClassFactory2. else { try { return(OpcCom.Interop.CreateInstanceWithLicenseKey(guid, url.HostName, credentials, connectData.LicenseKey)); } catch (Exception e) { throw new Opc.ConnectFailedException(e); } } }
//====================================================================== // IFactory /// <summary> /// Creates a new instance of the server. /// </summary> public override Opc.IServer CreateInstance(Opc.URL url, Opc.ConnectData connectData) { object comServer = Factory.Connect(url, connectData); if (comServer == null) { return(null); } OpcCom.Server server = null; System.Type interfaceType = null; try { // DA if (url.Scheme == Opc.UrlScheme.DA) { // Verify that it is a DA server. if (!typeof(OpcRcw.Da.IOPCServer).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Da.IOPCServer); throw new NotSupportedException(); } // DA 3.00 if (typeof(OpcRcw.Da.IOPCBrowse).IsInstanceOfType(comServer) && typeof(OpcRcw.Da.IOPCItemIO).IsInstanceOfType(comServer)) { server = new OpcCom.Da.Server(url, comServer); } // DA 2.XX else if (typeof(OpcRcw.Da.IOPCItemProperties).IsInstanceOfType(comServer)) { server = new OpcCom.Da20.Server(url, comServer); } else { interfaceType = typeof(OpcRcw.Da.IOPCItemProperties); throw new NotSupportedException(); } } // AE else if (url.Scheme == Opc.UrlScheme.AE) { // Verify that it is a AE server. if (!typeof(OpcRcw.Ae.IOPCEventServer).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Ae.IOPCEventServer); throw new NotSupportedException(); } server = new OpcCom.Ae.Server(url, comServer); } // HDA else if (url.Scheme == Opc.UrlScheme.HDA) { // Verify that it is a HDA server. if (!typeof(OpcRcw.Hda.IOPCHDA_Server).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Hda.IOPCHDA_Server); throw new NotSupportedException(); } server = new OpcCom.Hda.Server(url, comServer); } // DX else if (url.Scheme == Opc.UrlScheme.DX) { // Verify that it is a DX server. if (!typeof(OpcRcw.Dx.IOPCConfiguration).IsInstanceOfType(comServer)) { interfaceType = typeof(OpcRcw.Dx.IOPCConfiguration); throw new NotSupportedException(); } server = new OpcCom.Dx.Server(url, comServer); } // All other specifications not supported yet. else { throw new NotSupportedException(String.Format("The URL scheme '{0}' is not supported.", url.Scheme)); } } catch (NotSupportedException e) { OpcCom.Interop.ReleaseServer(server); server = null; if (interfaceType != null) { StringBuilder message = new StringBuilder(); message.AppendFormat("The COM server does not support the interface "); message.AppendFormat("'{0}'.", interfaceType.FullName); message.Append("\r\n\r\nThis problem could be caused by:\r\n"); message.Append("- incorrectly installed proxy/stubs.\r\n"); message.Append("- problems with the DCOM security settings.\r\n"); message.Append("- a personal firewall (sometimes activated by default).\r\n"); throw new NotSupportedException(message.ToString()); } throw e; } catch (Exception e) { OpcCom.Interop.ReleaseServer(server); server = null; throw e; } // initialize the wrapper object. if (server != null) { server.Initialize(url, connectData); } return(server); }
/// <summary> /// Tries to connect to the server. /// </summary> private void Connect() { Opc.URL url = new Opc.URL("opcda://localhost/" + _serverName); OpcCom.Factory fact = new OpcCom.Factory(); _server = new Opc.Da.Server(fact, null); try { _server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch (Exception ex) { _error.Append(ex.ToString()); if (ex.InnerException != null) _error.Append(ex.InnerException.ToString()); } }
private void InitializeOPC() { try { if (File.Exists("settings.xml")) { this.CurrentCounterOfMaterial = 0; XmlSerializer XmlSerializer1 = new XmlSerializer(typeof(Settings)); TextReader reader1 = new StreamReader("settings.xml"); Settings Settings1 = (Settings)XmlSerializer1.Deserialize(reader1); reader1.Dispose(); if (Settings1.OPCVariablesInitialized == true) { // 1st: Create a server object and connect to the RSLinx OPC Server url = new Opc.URL(Settings1.OPCConnectionString); server = new Opc.Da.Server(fact, null); //2nd: Connect to the created server server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; 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 += groupRead_DataChanged; items[0] = new Opc.Da.Item(); items[0].ItemName = Settings1.OPCCounterName; items[1] = new Opc.Da.Item(); items[1].ItemName = Settings1.OPCSpeedName; items = groupRead.AddItems(items); Opc.Da.ItemValueResult[] values = groupRead.Read(items); this.previous_value_of_counter = Convert.ToInt32(values[0].Value); this.VariablesInitialized = true; } } else { MessageBox.Show("OPC settings is empty. See Settings - > Connection..."); this.VariablesInitialized = false; } } catch { MessageBox.Show("Bad OPC connection. Review connection string"); this.VariablesInitialized = false; } }
public void OnCheckOpc() { if (_model.VerificationList != null && _model.VerificationList.Any()) { _opcServers = new Dictionary <Guid, Opc.Da.Server>(); foreach (var server in _model.VerificationList.Where(x => !string.IsNullOrEmpty(x.Connectionstring))) { // 1st: Create a server object and connect to the RSLinx OPC Server //var url = new Opc.URL("opcda://10.85.5.111/Infinity.OPCServer"); var url = new Opc.URL(server.Connectionstring); var fact = new OpcCom.Factory(); var opcServer = new Opc.Da.Server(fact, null); //2nd: Connect to the created server try { try { opcServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch { MessageBox.Show("Сервер " + url + " недостпуен.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } var id = server.Id; _opcServers.Add(id, opcServer); if (server.OpcStatements != null && server.OpcStatements.Any()) { //3rd Create a group if items var groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group of " + server.Caption; 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 var groupRead = (Opc.Da.Subscription)opcServer.CreateSubscription(groupState); groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(TagValue_DataChanged); //callback when the data are readed var items = new List <Opc.Da.Item>(); foreach (var tag in server.OpcStatements) { items.Add(new Opc.Da.Item { ItemName = tag.TagValue, ClientHandle = id }); } //// add items to the group (in Rockwell names are identified like [Name of PLC in the server]Block of word:number of word,number of consecutive readed words) ////items[0] = new Opc.Da.Item(); ////items[0].ItemName = "NPS_Berez2.DPS_1.Scr.Scr1";//this reads 2 word (short - 16 bit) ////items[1] = new Opc.Da.Item(); ////items[1].ItemName = "SIKN_592.BIK.Vmom";//this reads an array of 10 words (short[]) //items[0] = new Opc.Da.Item(); //items[0].ItemName = "AK.SIBNP.R_Uraj.NPS_Berez2.DPS_1.Scr.Scr1";//this reads 2 word (short - 16 bit) //items[0].ClientHandle = Guid.NewGuid(); ////items[1] = new Opc.Da.Item(); ////items[1].ItemName = "AK.SIBNP.R_Uraj.SERVICE.WebRouter_AK.SIBNP.R_Uraj.StatusInt.Cause";//this reads an array of 10 words (short[]) ////items[2] = new Opc.Da.Item(); ////items[2].ItemName = "AK.SIBNP.R_Uraj.Offline_14";//this read a 2 word array (but in the plc the are used as bits so you have to mask them) ////items[3] = new Opc.Da.Item(); ////items[3].ItemName = "AK.SIBNP.R_Uraj.Test_14";//this read a 2 word array (but in the plc the are used as bits so you have to mask them) groupRead.AddItems(items.ToArray()); } } catch (Exception e) { MessageBox.Show("Ошибка при чтении тега OPC с сервера " + url + ". " + e.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } }
// 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); }
public PLCFactory(string url) { opcURL = new Opc.URL(url); OpcCom.Factory fact = new OpcCom.Factory(); opcServer = new Opc.Da.Server(fact, null); }
//====================================================================== // IFactory /// <summary> /// Creates a new instance of the server. /// </summary> public override Opc.IServer CreateInstance(Opc.URL url, Opc.ConnectData connectData) { // validate requested type. if (SystemType != null) { // XML-DA 1.00 if (SystemType == typeof(OpcXml.Da.Server)) { OpcXml.Da.Server server = new OpcXml.Da.Server(); try { server.Initialize(url, connectData); } catch { throw new NotSupportedException(SystemType.FullName); } return(server); } #if (UA) // UA 1.00 if (SystemType == typeof(OpcXml.Ua.XmlServiceClient)) { OpcXml.Ua.XmlServiceClient server = new OpcXml.Ua.XmlServiceClient(); try { server.Initialize(url, connectData); } catch { throw new NotSupportedException(SystemType.FullName); } return(server); } #endif // object does not support requested interface type. throw new NotSupportedException(SystemType.FullName); } // auto-detect server type. else { // XML-DA 1.00 if (url.Scheme == Opc.UrlScheme.HTTP) { try { OpcXml.Da.Server server = new OpcXml.Da.Server(); server.Initialize(url, connectData); return(server); } catch (Exception e) { throw new Opc.ResultIDException(Opc.ResultID.E_FAIL, e.Message, e); } } #if (UA) // UA 1.00 over TCP if (url.Scheme == Opc.UrlScheme.UA_TCP) { try { OpcXml.Ua.TcpServiceClient server = new OpcXml.Ua.TcpServiceClient(); server.Initialize(url, connectData); return(server); } catch (Exception e) { throw new Opc.ResultIDException(Opc.ResultID.E_FAIL, e.Message, e); } } // UA 1.00 over HTTP if (url.Scheme == Opc.UrlScheme.UA_HTTP) { try { OpcXml.Ua.XmlServiceClient server = new OpcXml.Ua.XmlServiceClient(); server.Initialize(url, connectData); return(server); } catch (Exception e) { throw new Opc.ResultIDException(Opc.ResultID.E_FAIL, e.Message, e); } } #endif // object does not support requested url scheme. throw new NotSupportedException(url.Scheme); } }
private bool Connect(string serverUrl) { /* When the factory creates an HDA server, it passes along 2 parameters: * SerializationInfo info * StreamingContext context * * The Factory class casts the COM object (pointing to the HDA server) to the IServer interface. * All calls to the interface or proxied to the COM object. */ Opc.URL url = new Opc.URL(serverUrl); OpcCom.Factory fact = new OpcCom.Factory(); _view.daServer = new Server(fact, url); try { //_hdaServer.Connect(); try { _view.daServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch (Exception ex) { _view.ResultnMessage = ex.Message; return(false); } //Console.WriteLine(String.Format("Connect to server {0}", serverName)); //3rd Create a group if items #region Group read interlock and Machine status _view.groupStateRead = new SubscriptionState(); _view.groupStateRead.Name = "InterLockGroup"; //_view.groupStateRead.UpdateRate = 1000;// this isthe time between every reads from OPC server _view.groupStateRead.Active = false;//this must be true if you the group has to read value _view.groupRead = (Subscription)_view.daServer.CreateSubscription(_view.groupStateRead); //_view.groupRead.DataChanged += new DataChangedEventHandler(_view.group_DataChanged);//callback when the data are readed // add items to the group (in Rockwell names are identified like [Name of PLC in the server]Block of word:number of word,number of consecutive readed words) if (_view.groupRead.Items != null) { _view.groupRead.RemoveItems(_view.groupRead.Items); } _view.items = new Item[_view.plcTags.Count]; int i = 0; foreach (var tag in _view.plcTags) { _view.items[i] = new Item(); _view.items[i].ItemName = _view.tagMainBlock + tag.PlcTag; _view.items[i].Active = true; i++; } _view.items = _view.groupRead.AddItems(_view.items); #endregion #region Group write //_view.groupStateWrite = new SubscriptionState(); //_view.groupStateWrite.Name = "WriteInterLock"; //_view.groupStateWrite.Active = false;//not needed to read if you want to write only //_view.groupWrite = (Subscription)_view.daServer.CreateSubscription(_view.groupStateWrite); #endregion return(true); } catch (Opc.ConnectFailedException opcConnExc) { MessageBox.Show(String.Format("Could not connect to server {0}{1}{2}" , serverUrl , Environment.NewLine , opcConnExc.ToString()) , "Connection failed!" , MessageBoxButtons.OK , MessageBoxIcon.Error); return(false); } }
private void button1_Click(object sender, EventArgs e) { // 1st: Create a server object and connect to the RSLinx OPC Server url = new Opc.URL(Settings1.OPCConnectionString); server = new Opc.Da.Server(fact, null); listBox1.Items.Add("1st: Create a server object and connect to the RSLinx OPC Server"); //2nd: Connect to the created server server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); listBox1.Items.Add("2nd: Connect to the created server"); //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; 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 += GroupRead_DataChanged; ; //listBox1.Items.Add("Add event"); items = new Opc.Da.Item[1]; items[0] = new Opc.Da.Item(); items[0].ItemName = Settings1.OPCIntVarName; items = groupRead.AddItems(items); listBox1.Items.Add("Add Items"); Opc.Da.ItemValueResult[] values = groupRead.Read(items); listBox1.Items.Add("Read(items)"); listBox1.Items.Add("========================"); listBox1.Items.Add(Convert.ToInt32(values[0].Value.ToString())); label3.Text = values[0].Value.ToString(); }