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())); }
/// <summary> /// 저장해 놓은 Item을 넣어 준다.- re Open시 사용 /// </summary> private void Item_Add() { string ItemName = string.Empty; try { int intOpcItemCnt = 0; Opc.Da.Item[] items = new Opc.Da.Item[ItemList.Count]; foreach (object objItem in ItemList) { ItemName = objItem.ToString(); items[intOpcItemCnt] = new Opc.Da.Item(); items[intOpcItemCnt].ItemName = ItemName; intOpcItemCnt++; dtAddress_Add(ItemName); } OpcGrp.AddItems(items); } catch (System.Runtime.InteropServices.ExternalException ex) { //activex이기 때문에 에러 발생이 제대로 되지 않아 몇가지만... throw ComException(ex, ItemName); } catch (Exception ex) { throw ex; } }
private void ReloadItems() { DataSet dsConfig = LoadConfigFile(); DataRow[] drItems = dsConfig.Tables[0].Select("ServerAddress='" + _ServerAddress + "' and ServerType = 'OPC'"); Opc.Da.Item[] Items = new Opc.Da.Item[drItems.Length]; try { List <string> ItemNames = new List <string>(); foreach (DataRow drtemp in drItems) { ItemNames.Add(drtemp["ItemName"].ToString()); //bool result = false; //result = this.AddItem(drtemp["ItemName"].ToString()); //if (!result) //{ // EnqueueLog("加载点[" + drtemp["ItemName"].ToString() + "]失败"); // //LogClass.Logs.Enqueue("加载点[" + drtemp["ItemName"].ToString() + "]失败"); //} } this.AddItems(ItemNames.ToArray()); } catch (Exception ex) { EnqueueLog("重新加载点出现错误:原因为:" + ex.Message); //LogClass.Logs.Enqueue("重新加载点出现错误:原因为:" + ex.Message); return; } }
public bool AddSubscription(string code) { try { var groupstate = new Opc.Da.SubscriptionState(); //定义组(订阅者)状态,相当于OPC规范中组的参数 groupstate.Name = code; //组名 groupstate.ServerHandle = null; //服务器给该组分配的句柄。 groupstate.ClientHandle = Guid.NewGuid().ToString(); //客户端给该组分配的句柄。 groupstate.Active = true; //激活该组。 groupstate.UpdateRate = 500; //刷新频率为1秒。 groupstate.Deadband = 0; // 死区值,设为0时,服务器端该组内任何数据变化都通知组。 groupstate.Locale = null; //不设置地区值。 var group = (Opc.Da.Subscription)m_server.CreateSubscription(groupstate); //创建组 var item = new Opc.Da.Item(); item.ClientHandle = Guid.NewGuid().ToString(); //客户端给该数据项分配的句柄。 item.ItemPath = null; //该数据项在服务器中的路径。 item.ItemName = code; //该数据项在服务器中的名字。 group.AddItems(new Opc.Da.Item[] { item }); groups.Add(code, group); return(true); } catch (Exception ex) { clsSetting.loger.Error($"{code}添加订阅失败!{ex}"); return(false); } }
public void AddItems(string[] ItemNames) { Opc.Da.Item[] items = new Opc.Da.Item[ItemNames.Length]; for (int i = 0; i < ItemNames.Length; i++) { items[i] = new Opc.Da.Item(); items[i].ItemName = ItemNames[i]; } Opc.Da.ItemResult[] results = opcSub.AddItems(items); for (int i = 0; i < results.Length; i++) { if (!results[i].ResultID.Succeeded()) { EnqueueLog("添加点出现错误:点[" + results[i].ItemName + "]添加失败,原因为:" + results[i].ResultID.ToString()); //LogClass.Logs.Enqueue("批量添加点出现错误:点[" + results[i].ItemName + "]添加失败,原因为:" + results[i].ResultID.ToString()); } } Opc.Da.ItemValueResult[] values = opcserver.Read(items); object[,] Values = new object[values.Length, 5]; for (int i = 0; i < values.Length; i++) { Values[i, 0] = values[i].ItemName; Values[i, 1] = values[i].Value; Values[i, 2] = values[i].Timestamp; Values[i, 3] = values[i].Quality.ToString(); Values[i, 4] = string.Format(@"OPC://{0}/{1}", this._ServerAddress, values[i].ItemName); } EnqueueRec(Values); }
/// <summary> /// 저장해 놓은 Item을 넣어 준다.- re Open시 사용 /// </summary> private void Item_ReAdd_All() { string ItemName = string.Empty; try { int intOpcItemCnt = 0; Opc.Da.Item[] items = new Opc.Da.Item[dtAddress.Rows.Count]; foreach (DataRow r in dtAddress.Rows) { ItemName = Fnc.obj2String(r["Address"]); items[intOpcItemCnt] = new Opc.Da.Item(); items[intOpcItemCnt].ItemName = ItemName; intOpcItemCnt++; } OpcGrp.AddItems(items); } catch (Exception ex) { throw ex; } }
/// <summary> /// 添加订阅 /// </summary> /// <param name="goupname">组名称</param> /// <param name="codes">项目代码列表</param> /// <param name="updateRate">刷新频率</param> /// <returns></returns> public bool AddSubscriptions(string goupname, List <string> codes, int updateRate = 500) { try { var groupstate = new Opc.Da.SubscriptionState(); //定义组(订阅者)状态,相当于OPC规范中组的参数 groupstate.Name = goupname; //组名 groupstate.ServerHandle = null; //服务器给该组分配的句柄。 groupstate.ClientHandle = Guid.NewGuid().ToString(); //客户端给该组分配的句柄。 groupstate.Active = true; //激活该组。 groupstate.UpdateRate = updateRate; //刷新频率 单位毫秒。 groupstate.Deadband = 0; // 死区值,设为0时,服务器端该组内任何数据变化都通知组。 groupstate.Locale = null; //不设置地区值。 var group = (Opc.Da.Subscription)m_server.CreateSubscription(groupstate); //创建组 var items = new List <Opc.Da.Item>(); foreach (string tmp in codes) { var item = new Opc.Da.Item(); item.ClientHandle = Guid.NewGuid().ToString(); //客户端给该数据项分配的句柄。 item.ItemPath = null; //该数据项在服务器中的路径。 item.ItemName = tmp; //该数据项在服务器中的名字。 items.Add(item); } group.AddItems(items.ToArray()); groups.Add(goupname, group); return(true); } catch (Exception ex) { clsSetting.loger.Error($"添加订阅失败: {goupname}, {ex}"); return(false); } }
public Opc.Da.ItemValue[] produceValueToWrite(Opc.Da.Item itemToWrite, double valueToWrite) { Opc.Da.Item[] itemsToWrite = new Opc.Da.Item[] { itemToWrite }; double[] valuesToWrite = new double[] { valueToWrite }; return(produceValuesToWrite(itemsToWrite, valuesToWrite)); }
public Opc.Da.Item[] produceItemsFromNodes() { Opc.Da.Item[] items = new Opc.Da.Item[Nodes.Length]; for (int j = 0; j < Nodes.Length; j++) { items[j] = new Opc.Da.Item(); items[j].ItemName = Nodes[j]; } return(items); }
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 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; } }
private void ConfirmFaultReset_On_OPC() { Opc.Da.Item[] OPC_Fault_On = new Opc.Da.Item[1]; OPC_Fault_On[0] = new Opc.Da.Item(); OPC_Fault_On[0].ItemName = Spotweld_Tag_Name + "HMI_PB_Alarm_Reset"; OPC_Fault_On = Fault_On_Write.AddItems(OPC_Fault_On); Opc.Da.ItemValue[] OPC_ResetValue_On = new Opc.Da.ItemValue[1]; OPC_ResetValue_On[0] = new Opc.Da.ItemValue(); OPC_ResetValue_On[0].ServerHandle = Fault_On_Write.Items[0].ServerHandle; OPC_ResetValue_On[0].Value = 0; Opc.IRequest OPCRequest; Fault_On_Write.Write(OPC_ResetValue_On, 123, new Opc.Da.WriteCompleteEventHandler(WriteCompleteCallback), out OPCRequest); }
// Set the Fault Value in the PLC back to 0 private void ConfirmFaultReset_Off_OPC(object sender, EventArgs e) { Opc.Da.Item[] OPC_Fault_Off = new Opc.Da.Item[1]; OPC_Fault_Off[0] = new Opc.Da.Item(); OPC_Fault_Off[0].ItemName = Spotweld_Tag_Name + "Fault"; OPC_Fault_Off = Fault_Off_Write.AddItems(OPC_Fault_Off); Opc.Da.ItemValue[] OPC_ResetValue_Off = new Opc.Da.ItemValue[1]; OPC_ResetValue_Off[0] = new Opc.Da.ItemValue(); OPC_ResetValue_Off[0].ServerHandle = Fault_Off_Write.Items[0].ServerHandle; OPC_ResetValue_Off[0].Value = 0; Opc.IRequest OPCRequest; Fault_Off_Write.Write(OPC_ResetValue_Off, 123, new Opc.Da.WriteCompleteEventHandler(WriteCompleteCallback), out OPCRequest); }
/// <summary> /// 그룹에 Item을 추가 하여 준다. /// </summary> /// <param name="strItem"></param> private void Item_Add(string strItem) { string ItemName = string.Empty; try { int intOpcItemCnt = OpcGrp.Items.Length; Opc.Da.Item i = new Opc.Da.Item(); i.ItemName = strItem; OpcGrp.AddItems(new Opc.Da.Item[] { i }); } catch (Exception ex) { throw ex; } }
/// <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)); } }
public bool AddItem(string ItemName) { Opc.Da.Item[] items = new Opc.Da.Item[1]; items[0] = new Opc.Da.Item(); items[0].ItemName = ItemName; Opc.Da.ItemResult[] results = opcSub.AddItems(items); if (!results[0].ResultID.Succeeded()) { EnqueueLog("添加点出现错误:点[" + results[0].ItemName + "]添加失败,原因为:" + results[0].ResultID.ToString()); object[,] BadValues = new object[1, 5]; BadValues[0, 0] = ItemName; BadValues[0, 1] = null; BadValues[0, 2] = DateTime.Now; BadValues[0, 3] = "Bad"; BadValues[0, 4] = string.Format(@"OPC://{0}/{1}", this._ServerAddress, ItemName); EnqueueRec(BadValues); return(false); } Opc.Da.ItemValueResult[] values = opcserver.Read(items); object[,] Values = new object[values.Length, 5]; for (int i = 0; i < values.Length; i++) { Values[i, 0] = values[i].ItemName; Values[i, 1] = values[i].Value; Values[i, 2] = values[i].Timestamp; Values[i, 3] = values[i].Quality.ToString(); Values[i, 4] = string.Format(@"OPC://{0}/{1}", this._ServerAddress, values[i].ItemName); } EnqueueRec(Values); return(true); }
public void AddItem(string itemName) { try { Opc.Da.Item item = new Opc.Da.Item(); item.ItemName = itemName; if (m_items == null) { m_items = new Opc.Da.Item[1]; } else { Array.Resize(ref m_items, m_items.Length + 1); } m_items[m_items.Length - 1] = item; } catch (Exception ee) { // aditional handling throw ee; } }
private void SaveSetting_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Confirmation Save ?", "Confirm", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { string servername = listBox1.GetItemText(listBox1.SelectedItem); //String UpdateOPCTag = "UPDATE TTAGMapping SET OPC_TAGNAME = '" + row[1].ToString() + "', TagType = '" + row[3] + "', MB_ADDRESS = '" + row[2] + "' WHERE RegNo = " + row[0]; String q = "UPDATE TSetting SET ServerProgID = '" + servername + "', Node = '" + Node.Text.ToString() + "', UpdateRate = '" + textBoxUpdateRate.Text.ToString() + "' WHERE ID = 1 "; //Console.WriteLine(q); conTSetting.Open(); OleDbCommand cmd = new OleDbCommand(q, conTSetting); cmd.ExecuteNonQuery(); conTSetting.Close(); Opc.Da.Item[] items = new Opc.Da.Item[publicmainform.Pub_dtTTAGMapping.Rows.Count]; publicmainform.Get_TSetting(); publicmainform.Connect_OPC(); //write null output from opcserver------------------------------------------------------------------------------------- for (int rowgridview = 0; rowgridview < publicmainform.Pub_dtTTAGMapping.Rows.Count; rowgridview++) { publicmainform.dataGridView1.Rows[rowgridview].Cells["TimeStamp"].Value = ""; publicmainform.dataGridView1.Rows[rowgridview].Cells["Quality"].Value = ""; publicmainform.dataGridView1.Rows[rowgridview].Cells["Value"].Value = ""; } //--------------------------------------------------------------------------------------------------------------------- publicmainform.AddValue2Datagridview(); publicmainform.dataGridView1.Update(); this.Close(); } else if (result == DialogResult.No) { //no... } }
/// <summary> /// 그룹에 Item을 추가 하여 준다. /// </summary> /// <param name="strItem"></param> public void Item_Add(string strItem) { string ItemName = string.Empty; try { int intOpcItemCnt = OpcGrp.Items.Length; Opc.Da.Item i = new Opc.Da.Item(); i.ItemName = strItem; OpcGrp.AddItems(new Opc.Da.Item[] { i }); ItemList.Add((object)ItemName); dtAddress_Add(ItemName); } catch (System.Runtime.InteropServices.ExternalException ex) { //activex이기 때문에 에러 발생이 제대로 되지 않아 몇가지만... throw ComException(ex, ItemName); } catch (Exception ex) { throw ex; } }
// -------------------------------------------------------------------------- public bool WriteVar <T>(string RefNameIn, T Value) { if (!Connected) { return(false); } try { //Remove all existing items from the group groupWrite.RemoveItems(groupWrite.Items); //Create the item to write: Opc.Da.Item[] itemToAdd = new Opc.Da.Item[1]; itemToAdd[0] = new Opc.Da.Item(); itemToAdd[0].ItemName = OPCWriteVars[RefNameIn].FullName; //create the item that contains the value to write Opc.Da.ItemValue[] writeValues = new Opc.Da.ItemValue[1]; writeValues[0] = new Opc.Da.ItemValue(itemToAdd[0]); groupWrite.AddItems(itemToAdd); writeValues[0].ServerHandle = groupWrite.Items[groupWrite.Items.Length - 1].ServerHandle; //set the value to write switch (OPCWriteVars[RefNameIn].VarType) { case OPCVarType.BOOL: writeValues[0].Value = Convert.ToBoolean(Value); break; case OPCVarType.SINT: writeValues[0].Value = Convert.ToSByte(Value); break; case OPCVarType.INT: writeValues[0].Value = Convert.ToInt16(Value); break; case OPCVarType.DINT: writeValues[0].Value = Convert.ToInt32(Value); break; case OPCVarType.REAL: writeValues[0].Value = Convert.ToSingle(Value); break; case OPCVarType.STRING: writeValues[0].Value = Convert.ToString(Value); break; } //write groupWrite.Write(writeValues); return(true); } catch { ComError("Write to OPC variable failed"); 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 }
public OpcAddress(Opc.Da.Item opcItem, Opc.Da.Subscription subscription) { _opcItem = opcItem; _subscription = subscription; }
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 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; } }
/// <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(); }
/// <summary> /// opc연결 상태 체크 쓰레드.. /// </summary> /// <param name="obj"></param> private void tmrCheckOpcStatus(object obj) { if (bolChecking) { return; } try { bolChecking = true; if (OpcGrp == null) { if (bolOpcStatus) { return; } else { throw new Exception(string.Empty); } } if (OpcGrp.Items.Length < 1) { //if (bolOpcStatus) return; //else // throw new Exception(string.Empty); } OpcGrp.Refresh(); Opc.Da.Item item = OpcGrp.Items[0]; //값을 정상 적으로 받지 못함.. if (!item.Active) { throw new Exception(string.Empty); } if (opc.GetStatus().ServerState != Opc.Da.serverState.running && !this.bolOpcStatus) //접속 정상 { //연결 회복.. this.bolOpcStatus = true; this.ChConnection_Status(bolOpcStatus); } //쓰기명령을 처리 한다. foreach (DataRow dr in dtWriteOrder.Rows) { //dtWriteOrder.Rows[j]["Address"], dtWriteOrder.Rows[j]["Value"]); Item_Write(Fnc.obj2String(dr["Address"]), Fnc.obj2int(dr["value"])); } } catch (Exception ex) //(System.Runtime.InteropServices.ExternalException ex) { //접속이 끊겼을 경우 상태 체크도 에러 발생 하므로... Console.WriteLine(ex.ToString()); if (this.bolOpcStatus) { this.bolOpcStatus = false; this.ChConnection_Status(bolOpcStatus); } //접속재시도.. try { this.close(); this.Open(); this.Item_Add(); } catch { } } finally { bolChecking = false; } }
public static Opc.Da.Subscription FindSubcriptionThatHasItem(this Opc.Da.SubscriptionCollection source, string ItemId, out Opc.Da.Item ItemToFind) { ItemToFind = null; foreach (Opc.Da.Subscription S in source) { ItemToFind = S.Items.FirstOrDefault(I => I.ItemName == ItemId); if (ItemToFind != null) { return(S); } } return(null); }
public async Task<List<TestRepairRequirement>> InitializeRepairTester([FromBody]List<TestRepairRequirement> req, int lineId, int testerMode, int testId) { PLCWrapper plc = new PLCWrapper(opcURL); CancellationTokenSource cts = new CancellationTokenSource(); var timeout = 1000000; var requestedTest = req.Where(r => r.TestId == testId).FirstOrDefault(); if (lineId == 1) //front line { if (requestedTest != null) { //if RU OR tester mode is in RT/RU InTouch Mode if (((requestedTest.BuildCode & (int)Math.Pow(2, 17)) == Math.Pow(2, 17)) || testerMode == 2) { if (requestedTest.TestId == 3) //FAM Tester { Tester inTouchFamTester = new InTouchTester(opcRUURL, frtRepairFamTesterTopic); inTouchFamTester.ResetTester(); Tester inTouchRepairTester = new InTouchTester(opcRUURL, frtRepairTesterTopic); inTouchRepairTester.ResetTester(); await Task.Delay(2000); inTouchFamTester.InitializeTester(requestedTest.JobId, requestedTest.PalletId, requestedTest.BuildCode, requestedTest.BuildCode); var result = await inTouchFamTester.WaitForResponse(requestedTest); requestedTest = result; } else if (requestedTest.TestId == 1 || requestedTest.TestId == 2) { //check if fam is done if (req.Where(r => r.TestId == 3).Any()) { var famTest = req.Where(r => r.TestId == 3).FirstOrDefault(); if (!famTest.Repaired) throw new HttpResponseException( HttpErrorResponse.GetHttpErrorResponse( HttpStatusCode.RequestTimeout, "FAM Test Required", string.Format("FAM Test Required"))); } var drv = req.Where(r => r.TestId == 1).FirstOrDefault(); var pas = req.Where(r => r.TestId == 2).FirstOrDefault(); if (drv != null && pas != null) { Tester inTouchTester = new InTouchTester(opcRUURL, frtRepairTesterTopic); inTouchTester.ResetTester(); await Task.Delay(2000); inTouchTester.InitializeTester(requestedTest.JobId, requestedTest.PalletId, drv.BuildCode, pas.BuildCode); var result = await inTouchTester.WaitForResponse(requestedTest); if (result.Repaired) { var allfrtTest = req.Where(r => r.TestId == 1 || r.TestId == 2).ToList(); foreach (var t in allfrtTest) { t.Repaired = true; t.Dtm = DateTime.Now; t.TestResult = new TestRepairResult { TestResult = 1, TestStatus = 1, TestResultDetails = new List<TestRepairResultDetail>() }; } Tester inTouchFamTester = new InTouchTester(opcRUURL, frtRepairFamTesterTopic); inTouchFamTester.ResetTester(); } } } } else //RT LEGACY CODE { #region RT Tester Legacy Code Opc.Da.ItemValue[] writeValues2 = new Opc.Da.ItemValue[1]; writeValues2[0] = new Opc.Da.ItemValue(); writeValues2[0].ItemName = frontRepairTesterBuildCode; writeValues2[0].Value = requestedTest.BuildCode; plc.WriteTags(writeValues2); PLCFactory waitFactory = new PLCFactory(opcURL); Opc.Da.Item[] tags = new Opc.Da.Item[1]; tags[0] = new Opc.Da.Item(); tags[0].ItemName = frontRepairTesterDataReady; var task = waitFactory.WaitReadTags(tags, cts.Token); if (await Task.WhenAny(task, Task.Delay(timeout, cts.Token)) == task) { var result = await task; if (result.Status == 1) { //Read Result and Status Tags Opc.Da.Item[] readResultTags = new Opc.Da.Item[2]; readResultTags[0] = new Opc.Da.Item(); readResultTags[0].ItemName = frontRepairTesterResult; readResultTags[1] = new Opc.Da.Item(); readResultTags[1].ItemName = frontRepairTesterStatus; var results = plc.ReadTags(readResultTags); int testResult = Convert.ToInt32(results[0].Value.ToString()); int testStatus = Convert.ToInt32(results[1].Value.ToString()); //passed if (testResult == testStatus) requestedTest.Repaired = true; else requestedTest.Repaired = false; requestedTest.TestResult = new TestRepairResult { TestResult = testResult, TestStatus = testStatus, TestResultDetails = GetTestRepairResult(requestedTest, testResult, testStatus), }; //Ack PLC Opc.Da.Item[] requestIDTags = new Opc.Da.Item[1]; requestIDTags[0] = new Opc.Da.Item(); requestIDTags[0].ItemName = frontRepairTesterRequestID; var requestIDTagsResults = plc.ReadTags(requestIDTags); var requestIDTagsResult = Convert.ToInt32(requestIDTagsResults[0].Value.ToString()); Opc.Da.ItemValue[] responseIDTags = new Opc.Da.ItemValue[1]; responseIDTags[0] = new Opc.Da.ItemValue(); responseIDTags[0].ItemName = frontRepairTesterResponseID; responseIDTags[0].Value = requestIDTagsResult; plc.WriteTags(responseIDTags); return req; } else { throw new HttpResponseException( HttpErrorResponse.GetHttpErrorResponse( HttpStatusCode.BadRequest, "Error", string.Format("Error Has Occured"))); } } else { throw new HttpResponseException( HttpErrorResponse.GetHttpErrorResponse( HttpStatusCode.RequestTimeout, "Request Timeout", string.Format("Timeout Has Occured"))); } #endregion } } return req; } else { if (requestedTest != null) { //if RU OR tester mode is in RT/RU InTouch Mode if (((requestedTest.BuildCode & (int)Math.Pow(2, 14)) == Math.Pow(2, 14)) || testerMode == 2) { #region RU Tester if (requestedTest.TestId == 3 || requestedTest.TestId == 4) { Tester inTouchTester = new InTouchTester(opcRUURL, rearRepairTesterTopic); inTouchTester.ResetTester(); await Task.Delay(4000); if (requestedTest.TestId == 3) //2nd row recipe inTouchTester.InitializeTester(requestedTest.JobId, requestedTest.PalletId, requestedTest.BuildCode, 0); else if (requestedTest.TestId == 4) //3rd row recipe inTouchTester.InitializeTester(requestedTest.JobId, requestedTest.PalletId, 0, requestedTest.BuildCode); var result = await inTouchTester.WaitForResponse(requestedTest); requestedTest = result; } #endregion } else { #region RT Tester Legacy Code Opc.Da.ItemValue[] writeValues2 = new Opc.Da.ItemValue[1]; writeValues2[0] = new Opc.Da.ItemValue(); writeValues2[0].ItemName = rearRepairTesterBuildCode; writeValues2[0].Value = requestedTest.BuildCode; plc.WriteTags(writeValues2); PLCFactory waitFactory = new PLCFactory(opcURL); Opc.Da.Item[] tags = new Opc.Da.Item[1]; tags[0] = new Opc.Da.Item(); tags[0].ItemName = rearRepairTesterDataReady; var task = waitFactory.WaitReadTags(tags, cts.Token); if (await Task.WhenAny(task, Task.Delay(timeout, cts.Token)) == task) { var result = await task; if (result.Status == 1) { //Read Result and Status Tags Opc.Da.Item[] readResultTags = new Opc.Da.Item[2]; readResultTags[0] = new Opc.Da.Item(); readResultTags[0].ItemName = rearRepairTesterResult; readResultTags[1] = new Opc.Da.Item(); readResultTags[1].ItemName = rearRepairTesterStatus; var results = plc.ReadTags(readResultTags); int testResult = Convert.ToInt32(results[0].Value.ToString()); int testStatus = Convert.ToInt32(results[1].Value.ToString()); //passed if (testResult == testStatus) requestedTest.Repaired = true; else requestedTest.Repaired = false; requestedTest.TestResult = new TestRepairResult { TestId = requestedTest.TestId, TestResult = testResult, TestStatus = testStatus, TestResultDetails = GetTestRepairResult(requestedTest, testResult, testStatus), }; await Task.Delay(2000); //Ack PLC Opc.Da.Item[] requestIDTags = new Opc.Da.Item[1]; requestIDTags[0] = new Opc.Da.Item(); requestIDTags[0].ItemName = rearRepairTesterRequestID; var requestIDTagsResults = plc.ReadTags(requestIDTags); var requestIDTagsResult = Convert.ToInt32(requestIDTagsResults[0].Value.ToString()); Opc.Da.ItemValue[] responseIDTags = new Opc.Da.ItemValue[1]; responseIDTags[0] = new Opc.Da.ItemValue(); responseIDTags[0].ItemName = rearRepairTesterRespondID; responseIDTags[0].Value = requestIDTagsResult; plc.WriteTags(responseIDTags); return req; } else { throw new HttpResponseException( HttpErrorResponse.GetHttpErrorResponse( HttpStatusCode.BadRequest, "Error", string.Format("Error Has Occured"))); } } else { throw new HttpResponseException( HttpErrorResponse.GetHttpErrorResponse( HttpStatusCode.RequestTimeout, "Request Timeout", string.Format("Timeout Has Occured"))); } #endregion } } return req; } }
public async Task<PLCWaitResult> WaitPLCTag(string tag) { PLCFactory factory = new PLCFactory(opcURL); CancellationTokenSource cts = new CancellationTokenSource(); var timeout = 1000000; Opc.Da.Item[] tags = new Opc.Da.Item[1]; tags[0] = new Opc.Da.Item(); tags[0].ItemName = tag; var task = factory.WaitReadTags(tags, cts.Token); if (await Task.WhenAny(task, Task.Delay(timeout, cts.Token)) == task) { var result = await task; return result; } else { return new PLCWaitResult { Status = -1, Message = "Timeout has occured" }; } }
public PLCResult ReadPLCTag(string tag) { PLCFactory factory = new PLCFactory(opcURL); Opc.Da.Item[] tags = new Opc.Da.Item[1]; tags[0] = new Opc.Da.Item(); tags[0].ItemName = tag; var results = factory.ReadTags(tags); var result = Convert.ToInt32(results[0].Value.ToString()); return new PLCResult { Value = result }; }
public void RepairTestMESComplete(string readtag, string writetag) { PLCFactory factory = new PLCFactory(opcURL); Opc.Da.Item[] tags = new Opc.Da.Item[1]; tags[0] = new Opc.Da.Item(); tags[0].ItemName = readtag; var results = factory.ReadTags(tags); var result = Convert.ToInt32(results[0].Value.ToString()); PLCFactory factory2 = new PLCFactory(opcURL); Opc.Da.ItemValue[] writeValues = new Opc.Da.ItemValue[1]; writeValues[0] = new Opc.Da.ItemValue(); writeValues[0].ItemName = writetag; writeValues[0].Value = result; factory2.WriteTags(writeValues); }
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(); }
public override Opc.Da.Item[] GetWaitResponseTags() { Opc.Da.Item[] waitTags = new Opc.Da.Item[2]; waitTags[0] = GetItem(GetFullTagName(drvPassedTag)); waitTags[1] = GetItem(GetFullTagName(pasPassedTag)); return waitTags; }
public int Test() { PLCFactory factory = new PLCFactory(opcURL); Opc.Da.Item[] tags = new Opc.Da.Item[1]; tags[0] = new Opc.Da.Item(); tags[0].ItemName = "[FrontRepairTester]RepairTester.BuildCode"; var results = factory.ReadTags(tags); var result = Convert.ToInt32(results[0].Value.ToString()); return result; }