private void button2_Click(object sender, EventArgs e) { // 1st: Create a server object and connect to the RSLinx OPC Server url = new Opc.URL(Settings1.OPCConnectionString); server = new Opc.Da.Server(fact, null); listBox1.Items.Add("1st: Create a server object and connect to the RSLinx OPC Server"); //2nd: Connect to the created server server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); listBox1.Items.Add("2nd: Connect to the created server"); //3rd Create a group if items groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group999"; groupState.UpdateRate = 1000; // this isthe time between every reads from OPC server groupState.Active = true; //this must be true if you the group has to read value groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState); groupRead.DataChanged += GroupRead_DataChanged;; //listBox1.Items.Add("Add event"); items = new Opc.Da.Item[1]; items[0] = new Opc.Da.Item(); items[0].ItemName = Settings1.OPCIntVarName; items = groupRead.AddItems(items); listBox1.Items.Add("Add Items"); Opc.Da.ItemValueResult[] values = groupRead.Read(items); listBox1.Items.Add("Read(items)"); listBox1.Items.Add("========================"); listBox1.Items.Add(Convert.ToInt32(values[0].Value.ToString())); }
public 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); } }
/// <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); } }
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; } }
// 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); }
/// <summary> /// 连接OPC服务器 /// </summary> /// <returns></returns> public bool ConnectServer() { _ServerStatus = "Connecting"; //先PING地址 string strIP = _ServerAddress.Split('/')[0]; if (strIP.ToLower() != "127.0.0.1" && strIP.ToLower() != "localhost") { Ping ping = new Ping(); PingReply pr = ping.Send(strIP); if (pr.Status != IPStatus.Success) { EnqueueLog("网络出现错误:" + pr.Status.ToString()); //LogClass.Logs.Enqueue("网络出现错误:" + pr.Status.ToString()); return(false); } } OpcCom.Factory fac = new OpcCom.Factory(false); opcserver = new Opc.Da.Server(fac, new Opc.URL(string.Format(@"opcda://{0}", _ServerAddress))); try { opcserver.Connect(); opcserver.ServerShutdown += new Opc.ServerShutdownEventHandler(opcserver_ServerShutdown); Opc.Da.SubscriptionState ss = new Opc.Da.SubscriptionState(); ss.Active = true; opcSub = opcserver.CreateSubscription(ss); _ServerStatus = "Connected"; opcSub.DataChanged += new Opc.Da.DataChangedEventHandler(opcSub_DataChanged); return(true); } catch (Exception ex) { EnqueueLog("连接OPC服务器出现错误:" + ex.Message); //LogClass.Logs.Enqueue("连接OPC服务器出现错误:" + ex.Message); _ErrorMessage = ex.Message; _ServerStatus = "NotConnected"; return(false); } }
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); }
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); } }
/// <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> /// <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 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 void OnCheckOpc() { if (_model.VerificationList != null && _model.VerificationList.Any()) { _opcServers = new Dictionary <Guid, Opc.Da.Server>(); foreach (var server in _model.VerificationList.Where(x => !string.IsNullOrEmpty(x.Connectionstring))) { // 1st: Create a server object and connect to the RSLinx OPC Server //var url = new Opc.URL("opcda://10.85.5.111/Infinity.OPCServer"); var url = new Opc.URL(server.Connectionstring); var fact = new OpcCom.Factory(); var opcServer = new Opc.Da.Server(fact, null); //2nd: Connect to the created server try { try { opcServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); } catch { MessageBox.Show("Сервер " + url + " недостпуен.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } var id = server.Id; _opcServers.Add(id, opcServer); if (server.OpcStatements != null && server.OpcStatements.Any()) { //3rd Create a group if items var groupState = new Opc.Da.SubscriptionState(); groupState.Name = "Group of " + server.Caption; groupState.UpdateRate = 1000; // this isthe time between every reads from OPC server groupState.Active = true; //this must be true if you the group has to read value var groupRead = (Opc.Da.Subscription)opcServer.CreateSubscription(groupState); groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(TagValue_DataChanged); //callback when the data are readed var items = new List <Opc.Da.Item>(); foreach (var tag in server.OpcStatements) { items.Add(new Opc.Da.Item { ItemName = tag.TagValue, ClientHandle = id }); } //// add items to the group (in Rockwell names are identified like [Name of PLC in the server]Block of word:number of word,number of consecutive readed words) ////items[0] = new Opc.Da.Item(); ////items[0].ItemName = "NPS_Berez2.DPS_1.Scr.Scr1";//this reads 2 word (short - 16 bit) ////items[1] = new Opc.Da.Item(); ////items[1].ItemName = "SIKN_592.BIK.Vmom";//this reads an array of 10 words (short[]) //items[0] = new Opc.Da.Item(); //items[0].ItemName = "AK.SIBNP.R_Uraj.NPS_Berez2.DPS_1.Scr.Scr1";//this reads 2 word (short - 16 bit) //items[0].ClientHandle = Guid.NewGuid(); ////items[1] = new Opc.Da.Item(); ////items[1].ItemName = "AK.SIBNP.R_Uraj.SERVICE.WebRouter_AK.SIBNP.R_Uraj.StatusInt.Cause";//this reads an array of 10 words (short[]) ////items[2] = new Opc.Da.Item(); ////items[2].ItemName = "AK.SIBNP.R_Uraj.Offline_14";//this read a 2 word array (but in the plc the are used as bits so you have to mask them) ////items[3] = new Opc.Da.Item(); ////items[3].ItemName = "AK.SIBNP.R_Uraj.Test_14";//this read a 2 word array (but in the plc the are used as bits so you have to mask them) groupRead.AddItems(items.ToArray()); } } catch (Exception e) { MessageBox.Show("Ошибка при чтении тега OPC с сервера " + url + ". " + e.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } }
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); }