private void ConnectionAgent() { while (!_connectionEnd.WaitOne(0) && !Connected) try { URL url = new URL(_OpcSection.Server.Name); _Server = new Opc.Da.Server(new OpcCom.Factory(), null); _Server.Connect(url, new ConnectData(new NetworkCredential())); _groupRead = (Subscription)_Server.CreateSubscription(_GroupReadState); _groupWrite = (Subscription)_Server.CreateSubscription(_GroupWriteState); for (int i = 0; i < _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags.Count; i++) { _Items[i] = new Opc.Da.Item(); //_Items[i].ItemName = String.Format("{0}{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _Items[i].ItemName = _OpcSection.Server.Channel + "." + _OpcSection.Server.Device + "." + _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name; //string itmNam = String.Format("{0}]{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _logger.LogInfo(/*Mtd*/ ": recognized element " + _Items[i].ItemName); } _Items = _groupRead.AddItems(_Items); _groupRead.DataChanged += new DataChangedEventHandler(Group_DataChanged); } catch (Exception ex) { _logger.LogError(ex); } }
private Int16 GetTagCanonicalType(string itemName) { const int ItemCanonicalDataTypeProperty = 1; TreeNode rootNode = uiGroupsTab_AllFoldersTreeView.SelectedNode; while (rootNode.Parent != null) { rootNode = rootNode.Parent; } var opcServer = Settings.OpcServers.Where(os => rootNode.FullPath == os.ServerName).Single(); string urlstring = opcServer.URL; Server server = new Server(new Factory(), new URL(urlstring)); server.Connect(); ItemIdentifier [] itemIdentifiers = new ItemIdentifier[] {new ItemIdentifier(itemName)}; PropertyID[] propertyIDs = new PropertyID[] { new PropertyID(ItemCanonicalDataTypeProperty) }; var result = server.GetProperties(itemIdentifiers, propertyIDs, true); server.Disconnect(); var resultType = result[0][0].Value.GetType(); PropertyInfo nameProperty = resultType.GetProperty("Name"); string name = nameProperty.GetValue(result[0][0].Value, null) as string; switch (name.ToLower()) { case "string": case "char": return 0; case "int16": case "int32": case "int64": case "uint16": case "uint32": case "uint64": return 1; case "boolean": return 2; case "decimal": case "double": return 3; case "datetime": case "datetimeoffset": return 4; default: return 0; } }
public static void TestConnection (string connection) { URL url = new URL(connection); Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), null); server.Connect(url, new ConnectData(new NetworkCredential())); }
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); } }
public RFID ReadTagsRFID(bool identify_card) { try { Opc.Da.Server server = null; OpcCom.Factory fact = new OpcCom.Factory(); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); // Opc.Da.Subscription group; Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = "RFID"; groupState.Active = true; group = (Opc.Da.Subscription)server.CreateSubscription(groupState); //добавление айтемов в группу Opc.Da.Item[] items = new Opc.Da.Item[2]; items[0] = new Opc.Da.Item(); items[0].ItemName = "ZREADER.RFID_reader.part1"; items[1] = new Opc.Da.Item(); items[1].ItemName = "ZREADER.RFID_reader.part2"; items = group.AddItems(items); //List<oldRFID> result_list = new List<oldRFID>(); ItemValueResult[] res = group.Read(items); RFID rfid = new RFID(); EFazsCards ef_card = new EFazsCards(); if (res != null) { //UInt16? part1 = res[0].Value != null ? res[0].Value as UInt16? : 37; //UInt16? part2 = res[1].Value != null ? res[1].Value as UInt16? : 50907; UInt16?part1 = res[0].Value != null ? res[0].Value as UInt16? : null; UInt16?part2 = res[1].Value != null ? res[1].Value as UInt16? : null; if (part1 != null && part2 != null) { rfid.part1 = part1; rfid.part2 = part2; if (identify_card) { int code1 = int.Parse(part1.ToString()); int code2 = int.Parse(part2.ToString()); String.Format("Определим ID=карты code1={0}, code2={1}", code1, code2).SaveInformation(); azsCards card = ef_card.Get().Where(c => c.Number == (code1).ToString("00") + "," + (code2).ToString("00000")).FirstOrDefault(); if (card == null) { card = ef_card.Get().Where(c => c.Number == (code1).ToString("000") + "," + (code2).ToString("00000")).FirstOrDefault(); } rfid.card = card; } } } return(rfid); } catch (Exception e) { String.Format("Ошибка выполнения метода ReadTagsRFID(identify_card={0})", identify_card).SaveError(e); return(null); } }
static void Main(string[] args) { Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), new URL { Path = @"Matrikon.OPC.Simulation.1", Scheme = Opc.UrlScheme.DA }); server.Connect(); //Write Values int counter = 1; ItemValue item = new ItemValue("Bucket Brigade.TestWrite"); var itemList = new List <ItemValue>(); itemList.Add(item); Item item_read = new Item(); item_read.ItemName = "Bucket Brigade.TestWrite"; item_read.Active = true; List <Item> readItems = new List <Item>(); readItems.Add(item_read); while (true) { item.Value = "Testing" + counter; server.Write(itemList.ToArray()); counter++; var result = server.Read(readItems.ToArray()); foreach (var value in result) { System.Console.WriteLine(value.ItemName + " : " + value.Value.ToString()); } } }
private void RepConnectionWorkerDoWork(object sender, DoWorkEventArgs args) { if (_server != null) { if (_repConnectionWorker.CancellationPending) { return; } if (!_status) { try { _server.Connect(); DisplayPanelServerError.Text = string.Empty; args.Result = Model.ServerStatus.ServerStatusENumSwitch.ServerIsConnected; } catch { _status = false; args.Result = Model.ServerStatus.ServerStatusENumSwitch.ConnectionFailed; } } else { DisplayPanelServerError.Text = string.Empty; args.Result = Model.ServerStatus.ServerStatusENumSwitch.ConnectionFailed; } } else { args.Result = Model.ServerStatus.ServerStatusENumSwitch.ObjectPathNotExist; } }
/********************************************************************************************************************* * * Buttons End * *********************************************************************************************************************/ /********************************************************************************************************************* * * Methods * * Show Components(): * Search For Components(): * Search For Job(): * * *********************************************************************************************************************/ private void JobData_ConnectToOPCServer(object sender, EventArgs e) { try { OPCServer = new Opc.Da.Server(OPCFactory, null); OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6"); OPCServer.Connect(); Component_StateRead = new Opc.Da.SubscriptionState(); Component_StateRead.Name = "Component_Reading"; Component_StateRead.UpdateRate = 1000; Component_StateRead.Active = true; Component_Read = (Opc.Da.Subscription)OPCServer.CreateSubscription(Component_StateRead); Component_Read.DataChanged += new Opc.Da.DataChangedEventHandler(Component_Read_DataChanged); ScanNewPart_StateWrite = new Opc.Da.SubscriptionState(); ScanNewPart_StateWrite.Name = "ScanNewPart_WriteGroup"; ScanNewPart_StateWrite.Active = true; ScanNewPart_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(ScanNewPart_StateWrite); Hardware_StateWrite = new Opc.Da.SubscriptionState(); Hardware_StateWrite.Name = "Hardware_WriteGroup"; Hardware_StateWrite.Active = true; Hardware_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(Hardware_StateWrite); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
//Connect to server public override void Connect(string host, string serverName) { var url = new URL("opcda://" + host + "/" + serverName); Server = new Opc.Da.Server(new OpcCom.Factory(), url); Server.Connect(); }
/// <summary> /// OPC建立连接 /// </summary> public void mOPC_ConnToServer() { try { string hostName = IEGInterface.Properties.Settings.Default.MachineName; //查询服务器 m_Server = null; Opc.Server[] servers = m_Discovery.GetAvailableServers(Specification.COM_DA_20, hostName, null); if (servers != null) { foreach (Opc.Da.Server sr in servers) { //获取需要连接的OPC数据存取服务器 if (String.Compare(sr.Name, hostName + ".OPC.SimaticNET", true) == 0) { m_Server = sr; break; } } } if (m_Server != null) { m_Server.Connect(); } } catch (Exception ex) { throw new Exception("OPC连接函数(mOPC_ConnToServer)异常:" + ex.ToString()); } }
/// <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); }
private void ConnectionAgent() { while (!_connectionEnd.WaitOne(0) && !Connected) { try { URL url = new URL(_OpcSection.Server.Name); _Server = new Opc.Da.Server(new OpcCom.Factory(), null); _Server.Connect(url, new ConnectData(new NetworkCredential())); _groupRead = (Subscription)_Server.CreateSubscription(_GroupReadState); _groupWrite = (Subscription)_Server.CreateSubscription(_GroupWriteState); for (int i = 0; i < _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags.Count; i++) { _Items[i] = new Opc.Da.Item(); //_Items[i].ItemName = String.Format("{0}{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _Items[i].ItemName = _OpcSection.Server.Channel + "." + _OpcSection.Server.Device + "." + _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name; //string itmNam = String.Format("{0}]{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _logger.LogInfo(/*Mtd*/ ": recognized element " + _Items[i].ItemName); } _Items = _groupRead.AddItems(_Items); _groupRead.DataChanged += new DataChangedEventHandler(Group_DataChanged); } catch (Exception ex) { _logger.LogError(ex); } } }
public static void TestConnection(string connection) { URL url = new URL(connection); Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), null); server.Connect(url, new ConnectData(new NetworkCredential())); }
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); }
//*************************************************************** //* Create the Data Link Layer Instances //* if the IP Address is the same, then resuse a common instance //*************************************************************** public bool Connection() { try { if (DLL == null) { if (DLL != null && DLL.IsConnected) { DLL.Disconnect(); } DLL = new Server(fact, null) { Url = new URL(m_OPCServerPath + "/" + OPCServer) }; DLL.Connect(); if (DLL.IsConnected) { EventscadaException?.Invoke(GetType().Name, "ConnectedSuccess"); IsConnected = true; } else { EventscadaException?.Invoke(GetType().Name, "ConnectedFailed"); IsConnected = false; } } } catch (Exception) { EventscadaException?.Invoke(GetType().Name, "ConnectedFailed"); IsConnected = false; } return(IsConnected); }
public static ItemValueResult[] RsLinx_OPC_Client_Read_Array(string ItemName, int Length) { try { //Creo un istanza di OPC.server Opc.Da.Server server; //Parametro necessario alla connect OpcCom.Factory fact = new OpcCom.Factory(); //Creo un istanza di Sottoscrizione Opc.Da.Subscription groupRead; //Creo un istanza di SubscriptionState, utile per controllare lo stato della sottoscrizione Opc.Da.SubscriptionState groupState; //Creo un array di OPC.Da.Item Opc.Da.Item[] items = new Opc.Da.Item[1]; //Setto factory e url del server, come url utilizzo quello del RSLinx OPC Server server = new Opc.Da.Server(fact, null); server.Url = new Opc.URL(Url); //Connetto il server server.Connect(); //Istanzio la sottoscrizione groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group"; groupState.UpdateRate = UpdateRate; //Setto il tempo di Refresh del gruppo groupState.Active = true; //Questo valore deve essere true se voglio aver la possibilità di leggere //Creo il gruppo sul server groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState); //Istanzio l'Item items[0] = new Opc.Da.Item(); //Gli do il nome (Rockwell utilizza questa formzattazione dei nomi per gli array //[NomeTopicOPC]NomeTag,LDimensioneArray es. [MyOPCTopic]Posizione,L50) items[0].ItemName = $"{ItemName},L{Length}"; //Aggiungo l'oggetto al gruppo items = groupRead.AddItems(items); //Leggo il valore dell'item aggiunto ItemValueResult[] Ritorno = groupRead.Read(items); //Controllo che la lettura dell'array sia andata a buon fine, se non è così lancio un'eccezione if (!Ritorno[0].ResultID.Name.Name.Equals("S_OK")) { throw new System.Exception("Errore lettura OPC Tag"); } return(groupRead.Read(items)); } catch (Exception ex) { //Se viene lanciata un'eccezione ritorno un array di ItemValueResult con il primo che ha valore -1 e mostro un Messagebox con l'errore MessageBox.Show(ex.Message); ItemValueResult[] Errore = new ItemValueResult[1]; Errore[0] = new ItemValueResult(); float[] Err = { (float)-1, (float)-1 }; Errore[0].Value = Err; return(Errore); } }
/// <summary> /// 连接服务器 /// </summary> /// <param name="serverName"></param> /// <param name="host"></param> public OpcResult Connect(string serverName, string host = "127.0.0.1") { OpcResult opcResult = OpcResult.ServerNoConnect; try { this.OpcServerName = serverName; this.Host = host; if (string.IsNullOrWhiteSpace(serverName) || string.IsNullOrWhiteSpace(host)) { if (!Equals(null, OnLogHappened)) { OnLogHappened(this, new OpcLogEventArgs("未指定服务器或主机名称")); } opcResult = OpcResult.E_FAIL; return(opcResult); } if (IsConnected) { if (!Equals(null, OnLogHappened)) { OnLogHappened(this, new OpcLogEventArgs("Opc服务器已经连接,host=" + host + ",serverName=" + serverName)); } opcResult = OpcResult.S_OK; return(opcResult); } var servers = OpcClientHelper.getOpcServers(host); if (!Equals(null, servers) && servers.Any(a => a.Name == serverName)) { opcServer = (Opc.Da.Server)servers.FirstOrDefault(a => a.Name == serverName); opcServer.Connect(); //服务器断开事件 opcServer.ServerShutdown += opcServer_ServerShutdown; IsConnected = true; if (!Equals(null, OnLogHappened)) { OnLogHappened(this, new OpcLogEventArgs("连接Opc服务器成功,host=" + host + ",serverName=" + serverName)); } //连接成功后开启守护进程 daemonTimer.Enabled = true; daemonTimer.Start(); opcResult = OpcResult.S_OK; } return(opcResult); } catch (Exception ex) { IsConnected = false; if (!Equals(null, OnErrorHappened)) { OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "连接Opc服务器时出错:" + ex.Message, ex)); } opcResult = OpcResult.E_FAIL; return(opcResult); } }
/// <summary> /// Connect the client to the OPC Server /// </summary> public void Connect() { if (Status == OpcStatus.Connected) { return; } _server = new OpcDa.Server(new Factory(), _url); _server.Connect(); RootNode = new DaNode(this, string.Empty, string.Empty); AddNodeToCache(RootNode); }
public void WithConnectedOpcDaServer(string opcServerUrl, Action <OpcDaClientConnector, Opc.Da.Server> action, Action <Exception> onError = null) { var url = new URL(opcServerUrl); using (var server = new Opc.Da.Server(new OpcCom.Factory(), null)) { var connectData = new ConnectData(new System.Net.NetworkCredential()); server.Connect(url, connectData); action(this, server); } }
/// <summary> /// 打开OPC /// </summary> public void Open() { try { opcServer.Connect(); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <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 OPCServer(string serverName) { if (String.IsNullOrEmpty(serverName)) { throw new ArgumentException("Server name is invalid."); } _serverURL = new URL(serverName); _serverURL.Scheme = "opcda"; _server = new Opc.Da.Server(new OpcCom.Factory(), _serverURL); _server.Connect(); }
public void Open() { _server.Connect(_url, new ConnectData(new System.Net.NetworkCredential())); var groupState = new SubscriptionState { Name = "Groups", UpdateRate = 50, Active = true }; _group = (Subscription)_server.CreateSubscription(groupState); _group.DataChanged += _group_DataChanged; }
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); } }
private void btConnect_Click(object sender, EventArgs e) { try { //=== Create a new server _server = new Server(_factory, null) { Url = new URL(txtConnectionString.Text) }; //=== Server Connection _server.Connect(); //=== Create SubscriptionState from Subscription _subscriptionState = new SubscriptionState { Name = "ReadGroup", UpdateRate = 100, Active = true }; //=== Create a SubscriptionState to Subscription _subscriptionStateWrite = new SubscriptionState { Name = "WriteGroup", Active = false }; //=== Subscription creation _subscription = (Subscription)_server.CreateSubscription(_subscriptionState); _subscriptionWrite = (Subscription)_server.CreateSubscription(_subscriptionStateWrite); //=== Associate the DataChangedEventHandler _subscription.DataChanged += new DataChangedEventHandler(SubscriptionRead_DataChanged); btReadWrite_Click(null, null); txtVariableRead_TextChanged(null, null); toolStripStatus.ToolTipText = string.Empty; toolStripStatus.Text = @"Connected"; } catch (Exception ex) { toolStripStatus.ToolTipText = ex.Message; toolStripStatus.Text = @"Disconnected"; } }
private Connection CreateConnection(string serverUrl) { ServiceManager.LogMessage("Connecting to {0}...", serverUrl); URL url = new URL(serverUrl); Opc.Da.Server server = null; try { server = new Opc.Da.Server(new OpcCom.Factory(), url); Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); try { server.Connect(); Opc.Da.ServerStatus serverStatus = server.GetStatus(); if (serverStatus.ServerState != Opc.Da.serverState.running) { throw new Exception(String.Format("Bad server state ({0})", serverStatus.ServerState)); } Connection connection = new Connection(serverUrl, server); server = null; stopwatch.Stop(); ServiceManager.LogMessage("Successful created new connection {0}: {1} ({2} ms)", connection.GetUID(), serverUrl, stopwatch.ElapsedMilliseconds); Counter counter = counters[serverUrl]; Interlocked.Increment(ref counter.numConnections); return(connection); } catch (Exception ex) { stopwatch.Stop(); ServiceManager.LogMessage("Failed create new connection to {0}: {1} ({2} ms)", serverUrl, ex.Message, stopwatch.ElapsedMilliseconds); throw new FaultException(ex.Message, new FaultCode("E_FAIL")); } } finally { if (server != null) { if (server.IsConnected) { server.Disconnect(); } server.Dispose(); } } }
private void User_Program_Teach_Senson_Load(object sender, EventArgs e) { SpotWeldID(); // Get Computer ID and Set Tag Name // Connect to OPC Server OPCServer = new Opc.Da.Server(OPCFactory, null); OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6"); OPCServer.Connect(); Sensor_StateRead = new Opc.Da.SubscriptionState(); Sensor_StateRead.Name = "Teach_Sensor_OPC"; Sensor_StateRead.UpdateRate = 1000; Sensor_StateRead.Active = true; Sensor_Read = (Opc.Da.Subscription)OPCServer.CreateSubscription(Sensor_StateRead); Sensor_Read.DataChanged += new Opc.Da.DataChangedEventHandler(Sensor_Read_DataChanged); TeachSensor_StateWrite = new Opc.Da.SubscriptionState(); TeachSensor_StateWrite.Name = "OPCWriteGroup"; TeachSensor_StateWrite.Active = false; TeachSensor_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(TeachSensor_StateWrite); GroupStateWriteCompOne = new Opc.Da.SubscriptionState(); GroupStateWriteCompOne.Name = "OPCWriteOneGroup"; GroupStateWriteCompOne.Active = false; GroupWriteCompOne = (Opc.Da.Subscription)OPCServer.CreateSubscription(GroupStateWriteCompOne); GroupStateWriteCompTwo = new Opc.Da.SubscriptionState(); GroupStateWriteCompTwo.Name = "OPCWriteTwoGroup"; GroupStateWriteCompTwo.Active = false; GroupWriteCompTwo = (Opc.Da.Subscription)OPCServer.CreateSubscription(GroupStateWriteCompTwo); GroupStateWriteCompThree = new Opc.Da.SubscriptionState(); GroupStateWriteCompThree.Name = "OPCWriteThreeGroup"; GroupStateWriteCompThree.Active = false; GroupWriteCompThree = (Opc.Da.Subscription)OPCServer.CreateSubscription(GroupStateWriteCompThree); // Get The Component ID From the User Program Component_1_TextBox.Text = owner.Comp1_TextBox.Text; Component_2_TextBox.Text = owner.Comp2_TextBox.Text; Component_3_TextBox.Text = owner.Comp3_TextBox.Text; CheckComponentValue(); // Find the Number of Components //TargetValueSet_TextBox.Clear(); OPC_TeachSensorValue = 1; TeachSensor_OPC(); SensorRead_OPC(); WriteComponentOne_OPC(); }
private void ConnectionWorkerDoWork(object sender, DoWorkEventArgs args) { try { try { OpcServerSingleton.GetInstance(Host, OpcServer); } catch (Exception) { } _server = OpcServerSingleton.Instance; } catch (Exception) { args.Result = Model.ServerStatus.ServerStatusENumSwitch.ObjectPathNotExist; return; } if (_server != null) { if (_connectionWorker.CancellationPending) { return; } if (!_status) { try { _server.Connect(); } catch (Exception) { } args.Result = Model.ServerStatus.ServerStatusENumSwitch.ServerIsConnected; } else { args.Result = Model.ServerStatus.ServerStatusENumSwitch.ConnectionFailed; } } else { args.Result = Model.ServerStatus.ServerStatusENumSwitch.ObjectPathNotExist; } }
public void Start() { InitializeMeasurements(); Uri serverUri = new Uri(l_opcDaPluginConfig.Settings.Url); var opcServerUrl = new URL(serverUri.ToString()) { Scheme = serverUri.Scheme, HostName = serverUri.Host }; l_server = new OpcDa.Server(new Factory(), opcServerUrl); l_server.Connect(); l_metricCollection = new BlockingCollection <OpcMetric>(); StartMonitoring(); StartPolling(); }
public OPCServer(string serverName) { if (String.IsNullOrEmpty(serverName)) throw new ArgumentException("Server name is invalid."); _serverURL = new URL(serverName); _serverURL.Scheme = "opcda"; _server = new Opc.Da.Server(new OpcCom.Factory(), _serverURL); try { _server.Connect(); } catch (Opc.ConnectFailedException connectionExc) { Console.WriteLine("Connection to OPC server could not be established"); Console.WriteLine(connectionExc.ToString()); } }
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> /// 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 Connect(System.Windows.Forms.TreeNode node) { try { if (this.IsServerNode(node)) { Opc.Da.Server server = (Opc.Da.Server)node.Tag; if (!server.IsConnected) { server.Connect(this.FindConnectData(node)); } this.Browse(node); } } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
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); } }
/// <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 UpdateFolderData(TreeNode node) { if (node == null) { uiFolderTagsBindingSource.DataSource = null; return; } //Add items to folder, read from OPC Server if first time var folderTags = node.Tag as List<BrowseElement>; if (folderTags == null) { TreeNode rootNode = node; while (rootNode.Parent != null) { rootNode = rootNode.Parent; } var opcServer = Settings.OpcServers.Where(os => rootNode.FullPath == os.ServerName).Single(); string urlstring = opcServer.URL; Server server = new Server(new Factory(), new URL(urlstring)); server.Connect(); BrowsePosition position; BrowseFilters filters = new BrowseFilters() { BrowseFilter = browseFilter.all }; ItemIdentifier itemId = null; if (node.FullPath != server.Name) { itemId = new ItemIdentifier(node.Name); } BrowseElement[] elements = server.Browse(itemId, filters, out position); server.Disconnect(); var items = elements.Where(e => e.IsItem); if (items.Any()) { folderTags = items.ToList(); } else { folderTags = new List<BrowseElement>(); } var folders = elements.Where(e => e.IsItem == false); if(folders.Any()) { foreach (var element in elements.Where(e => !e.IsItem)) { node.Nodes.Add(element.Name).Name = element.ItemName; } } node.Tag = folderTags; } //Exlude elements which already are in group folderTags = folderTags.ToList(); var selectedGroup = uiGroupsTab_Groups.SelectedItem as Group; if (selectedGroup != null) { if (selectedGroup.Properties != null) { foreach (var property in selectedGroup.Properties) { folderTags.RemoveAll(t => t.ItemName == property.TagName); } } } uiFolderTagsBindingSource.DataSource = folderTags; //if (elements != null) //{ // var itemsIDs = new List<ItemIdentifier>(); // foreach (var element in elements) // { // itemsIDs.Add(new ItemIdentifier(element.ItemName)); // } // var prid = new List<PropertyID>(); // prid.Add(new PropertyID(1)); // prid.Add(new PropertyID(2)); // var tst = server.GetProperties(itemsIDs.ToArray(), prid.ToArray(), true); //} }
//private void AddNode(Server opcServer, TreeNode treeNode) //{ // ItemIdentifier itemId; // BrowsePosition position; // BrowseFilters filters = new BrowseFilters() { BrowseFilter = browseFilter.branch }; // if (treeNode.FullPath == opcServer.Name) // { // itemId = null; // } // else // { // //int serverNameLength = opcServer.Name.Length; // //string itemIdentifier = treeNode.FullPath.Substring(serverNameLength + 1); // itemId = new ItemIdentifier(treeNode.Name); // } // BrowseElement[] elements = opcServer.Browse(itemId, filters, out position); // if (elements == null) // { // return; // } // foreach (var element in elements) // { // treeNode.Nodes.Add(element.Name).Name = element.ItemName; // } // //foreach (TreeNode node in treeNode.Nodes) // //{ // // AddNode(opcServer, node); // //} //} private void UpdateFoldersTree() { uiGroupsTab_AllFoldersTreeView.Nodes.Clear(); List<OpcServer> opcServers; if (uiGroupsTab_Groups.SelectedItem == null) { opcServers = Settings.OpcServers; } else { var selectedGroup = uiGroupsTab_Groups.SelectedItem as Group; opcServers = new List<OpcServer>(); opcServers.Add(selectedGroup.OpcServer); } foreach (var opcServer in opcServers) { string urlstring = opcServer.URL; Server server = new Server(new Factory(), new URL(urlstring)); if (opcServer.RootNode == null) { var newNode = uiGroupsTab_AllFoldersTreeView.Nodes.Add(server.Name); server.Connect(); //AddNode(server, newNode); UpdateFolderData(newNode); server.Disconnect(); opcServer.RootNode = newNode; } else { uiGroupsTab_AllFoldersTreeView.Nodes.Add(opcServer.RootNode); } } if (uiGroupsTab_AllFoldersTreeView.Nodes != null) { foreach (TreeNode node in uiGroupsTab_AllFoldersTreeView.Nodes) { node.Expand(); } } UpdateFolderData(uiGroupsTab_AllFoldersTreeView.SelectedNode); }