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())); }
protected override bool close() { try { if (OpcGrp != null) { OpcGrp = null; } if (opc != null) { if (opc.IsConnected) { opc.Disconnect(); } opc.Dispose(); opc = null; } if (bolOpcStatus) { bolOpcStatus = false; this.ChConnection_Status(bolOpcStatus); } this.dtAddress.Clear(); } catch (Exception ex) //opc 클라이언트가 종료 되면.. 에러 발생.. { throw ex; } return(true); }
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; } }
// Form Loads. // Checks Spot Weld Computer. // Connects to OPC Server private void User_Program_Part_Not_Completed_Load(object sender, EventArgs e) { SpotWeldID(); OPCServer = new Opc.Da.Server(OPCFactory, null); OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6"); OPCServer.Connect(); Fault_Off_StateWrite = new Opc.Da.SubscriptionState(); Fault_Off_StateWrite.Name = "PB_Reset_Off_Fault"; Fault_Off_StateWrite.Active = true; Fault_Off_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(Fault_Off_StateWrite); Fault_On_StateWrite = new Opc.Da.SubscriptionState(); Fault_On_StateWrite.Name = "PB_Reset_On_Fault"; Fault_On_StateWrite.Active = true; Fault_On_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(Fault_On_StateWrite); }
public exOPCserver() { listServers = new ObservableCollection <mServerItem>(); monitoredTags = new ObservableCollection <mTag>(); restoredTagList = new List <mTag>(); messageLog = new List <string>(); logMessage("Message log started"); isConnected = false; opcSubscription = null; selectedServer = new mServerItem(true); selectedServer.ReconnectInterval = 5000; configureWatchDog(); error = new gErrorEntity(0, "Initialized"); }
public void CreateGroup(string groupName, int updateRate) { try { m_groupState = new Opc.Da.SubscriptionState(); m_groupState.Name = groupName; m_groupState.UpdateRate = updateRate; m_groupState.Active = true; m_groupRead = (Opc.Da.Subscription)m_server.CreateSubscription(m_groupState); // callback when data are readed // seems not supported m_groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(group_DataChanged); } catch (Exception ee) { // aditional handling throw ee; } }
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> /// Vytvoří items pro zápis v zadané group dle zadané hashtabulky /// </summary> /// <param name="group"></param> /// <param name="table"></param> protected void naplnitGroupZapis(Opc.Da.Subscription group, Dictionary <string, ItemW> table) { int i = 0; Opc.Da.Item[] items = new Opc.Da.Item[table.Count]; foreach (KeyValuePair <string, ItemW> item in table) { items[i] = new Opc.Da.Item(); items[i].ItemName = item.Key.ToString(); i++; } items = group.AddItems(items); if (table.Count != group.Items.Length) //Kontrola, zda bylo přidání items ve všech případech úspěšné { throw new Exception(String.Format("Některé Items pro zápis se nepodařilo přidat do group \"{0}\".\n(přidáno {1} z {2}, bližší informace viz log OPC serveru)", group.Name, group.Items.Length, table.Count)); } if (table.Count == 0) { throw new Exception(String.Format("Group \"{0}\" nemá žádné items.", group.Name)); } }
/// <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); } }
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 OpcAddress(Opc.Da.Item opcItem, Opc.Da.Subscription subscription) { _opcItem = opcItem; _subscription = subscription; }
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> /// OPC subsription procedure /// </summary> /// <param name="Tags">List of manitored tags</param> public void SubscribeTags(List <mTag> Tags) { if (server.IsConnected) { List <Opc.Da.Item> opcItems = new List <Opc.Da.Item>(); bool needToAddItems = false; foreach (mTag tag in Tags) { var contain = monitoredTags.Any(t => t.Name == tag.Name); if (!contain) { // Repeat this next part for all the items you need to subscribe Opc.Da.Item item = new Opc.Da.Item(); item.ItemName = tag.Name; //item.ClientHandle = "handle"; // handle is up to you, but i use a logical name for it item.Active = true; item.ActiveSpecified = true; opcItems.Add(item); monitoredTags.Add(tag); needToAddItems = true; } } if (needToAddItems) { try { Opc.Da.SubscriptionState subscriptionState = new Opc.Da.SubscriptionState(); subscriptionState.Active = true; subscriptionState.UpdateRate = 40; subscriptionState.Deadband = 0; if (opcSubscription != null) { } opcSubscription = (Opc.Da.Subscription) this.server.CreateSubscription(subscriptionState); Opc.Da.ItemResult[] result = opcSubscription.AddItems(opcItems.ToArray()); for (int i = 0; i < result.Length; i++) { opcItems[i].ServerHandle = result[i].ServerHandle; } opcSubscription.DataChanged += opcSubscription_DataChanged; OnReportMessage("OPC tags subscription created successfully"); } catch (Exception ex) { OnReportMessage("OPC tags subscription failed"); OnReportMessage(ex.Message.ToString()); } } } else { OnReportMessage("Connect server first"); } RefreshServerStatus(); }
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); } }
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(); }
/// <summary> /// Vytvoření skupin pro čtení a zápis dat /// </summary> /// <param name="server"></param> private void vytvoritGroups(Opc.Da.Server server) { if (server == null) { throw new ArgumentNullException("Parametr server není inicializovaný"); } if (!server.IsConnected) { throw new Exception("Nelze vytvořit groups, když není připojení k serveru"); } // Vytvoření groups pro čtení a zápis Opc.Da.SubscriptionState groupState; groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Cteni"; groupState.Active = false; //groupState.UpdateRate = 1000; groupCteni = (Opc.Da.Subscription)server.CreateSubscription(groupState); groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Zapis"; groupState.Active = false; //groupState.UpdateRate = 1000; groupZapis = (Opc.Da.Subscription)server.CreateSubscription(groupState); }