//====================================================================== // CreateSubscription /// <summary> /// Creates a new subscription. /// </summary> /// <param name="state">The initial state of the subscription.</param> /// <returns>The new subscription object.</returns> public ISubscription CreateSubscription(Opc.Da.SubscriptionState state) { if (state == null) { throw new ArgumentNullException("state"); } lock (this) { Opc.Da.SubscriptionState copy = (Opc.Da.SubscriptionState)state.Clone(); // assign unique handle. copy.ServerHandle = m_nextHandle++; // assign name. if (copy.Name == null || copy.Name.Length == 0) { copy.Name = String.Format("Subscription{0,2:00}", copy.ServerHandle); } // create subscription. Subscription subscription = new Subscription(m_cache, this, copy); // save reference. m_subscriptions[copy.ServerHandle] = subscription; // return new subscription. return(subscription); } }
public OpcGroup AddGroup(string groupName) { OpcGroup _group = new OpcGroup { IsActive = true, Name = groupName, UpdateRate = new TimeSpan(0, 0, 0, 0, _options.DefaultMonitorInterval) }; var subItem = new OpcDa.SubscriptionState { Name = (++_sub).ToString(CultureInfo.InvariantCulture), Active = true, UpdateRate = DefaultMonitorInterval }; var sub = _server.CreateSubscription(subItem); Action unsubscribe = () => new Thread(o => _server.CancelSubscription(sub)).Start(); dic.Add(groupName, sub); sub.DataChanged += (subscriptionHandle, requestHandle, values) => { List <OpcItemValue> items = new List <OpcItemValue>(); foreach (OpcDa.ItemValueResult value in values) { OpcItemValue item = new OpcItemValue { GroupName = groupName, Value = value.Value, ItemId = value.ItemName, Quality = value.Quality.ToString(), Timestamp = value.Timestamp }; items.Add(item); } _group.SendValue(items); }; return(_group); }
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); } }
/// <summary> /// Add items (according to "itemList" parameter) into OPC.Subscription /// </summary> /// <param name="itemList"></param> /// <param name="updateRate"></param> /// <returns></returns> public bool AddItems(Opc.Da.Item[] itemList, int updateRate = 0) { var state = new Opc.Da.SubscriptionState(); try { // Remove items if (Items != null) { Subscription.RemoveItems(Items); } state.Active = false; Subscription.ModifyState((int)Opc.Da.StateMask.Active, state); state.UpdateRate = updateRate > 0 ? updateRate : 1000; Subscription.ModifyState((int)Opc.Da.StateMask.UpdateRate, state); foreach (var item in itemList) { item.ClientHandle = Guid.NewGuid().ToString(); } Items = Subscription.AddItems(itemList); Advised = false; return(true); } catch (Exception e) { //MessageBox.Show(ex.Message); throw e; } }
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); } }
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="_subscriptionname"></param> public void CreateMySubscription(string _subscriptionname) { Opc.Da.SubscriptionState subScriptionState = new Opc.Da.SubscriptionState(); subScriptionState.Active = true; // activate cyclic communication subScriptionState.ClientHandle = System.Guid.NewGuid().ToString(); subScriptionState.Deadband = 0.0F; subScriptionState.Name = _subscriptionname; subScriptionState.UpdateRate = 1000; opcServer.CreateSubscription(subScriptionState); }
/// <summary> /// Добавление тегов к подписке /// </summary> public override void AddTags(List <TagId> taglist) { TagListBackup = taglist; var subList = new List <Opc.Da.Item>(); foreach (var tag in taglist) { if (_tags.Exists(d => d.ItemName == tag.TagName)) { // TagListBackup.Add(tag); subList.Add(new Opc.Da.Item { ItemName = tag.TagName }); logger.Logged("Info", "#" + PollerId + ": добавляем тег '" + tag.TagName + "' в подписку", "OpcDaPoller", "AddTags"); } else { logger.Logged("Error", "#" + PollerId + ": тег '" + tag.TagName + "' не обнаружен на сервере", "OpcUaPoller", "AddTags"); } } if (!Activated) { return; } try { var groupState = new Opc.Da.SubscriptionState { Name = "Group", Active = true }; var @group = (Opc.Da.Subscription)server.CreateSubscription(groupState); /* * int tagCounter = 0; * var items = new Opc.Da.Item[taglist.Count()]; * foreach (TagId tag in taglist) * { * var item = new Opc.Da.Item {ItemName = tag.TagName}; * items[tagCounter] = item; * tagCounter++; * }*/ @group.AddItems(subList.ToArray()); @group.DataChanged += new Opc.Da.DataChangedEventHandler(OnNotification); logger.Logged("Info", "Добавлено {" + subList.Count() + "} тегов для контроля с OPC DA сервера #{" + PollerId + "}", "", ""); } catch (Exception ex) { logger.Logged("Error", "Не удалось добавить теги для контроля OPC DA сервером #" + PollerId + ": " + ex.Message, "", ""); } }
/// <summary> /// Connect/Disconnect to the server. /// </summary> /// <returns></returns> private bool Connect() { // Connect server var url = new Opc.URL(OpcConnectionString); // Create an unconnected server object. OpcServer = GetServerForUrl(url); if (OpcServer == null) { return(false); } // Invoke the connect server callback. try { var connectData = new Opc.ConnectData(Credential, null); OpcServer.Connect(connectData); var opcDaSrerver = OpcServer as Opc.Da.Server; if (opcDaSrerver == null) { return(false); } VendorInfo = opcDaSrerver.GetStatus().VendorInfo; VersionInfo = opcDaSrerver.GetStatus().ProductVersion; StatusInfo = opcDaSrerver.GetStatus().StatusInfo; var state = new Opc.Da.SubscriptionState { ClientHandle = Guid.NewGuid().ToString(), ServerHandle = null, //Name = "DEFAULT", Active = false, UpdateRate = 1000, KeepAlive = 0, //Deadband = 0, //Locale = null }; Subscription = (Subscription)opcDaSrerver.CreateSubscription(state); } catch (Exception e) { throw e; } return(true); }
//====================================================================== // CreateSubscription /// <summary> /// Creates a new subscription. /// </summary> /// <param name="state">The initial state of the subscription.</param> /// <returns>The new subscription object.</returns> public ISubscription CreateSubscription(Opc.Da.SubscriptionState state) { if (state == null) { throw new ArgumentNullException("state"); } if (m_proxy == null) { throw new NotConnectedException(); } lock (this) { return(new Subscription(this, m_proxy, state, m_options.Filters)); } }
public void AddSubscription(string groupName, List <string> tagList, DataChangedEventHandler onDataChange) { if (!_server.IsConnected) { Console.WriteLine("Connection to OPC server is not established"); return; } // Create group Opc.Da.Subscription group; Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = groupName; groupState.Active = true; groupState.UpdateRate = 200; // Short circuit if group already exists SubscriptionCollection existingCollection = _server.Subscriptions; if (existingCollection.Count > 0) { for (int i = 0; i < existingCollection.Count; i++) { if (existingCollection[i].Name == groupName) { Console.WriteLine(String.Format("Subscription group {0} already exists", groupName)); return; } } } group = (Opc.Da.Subscription)_server.CreateSubscription(groupState); // Create list of items to monitor Item[] opcItems = new Item[1]; int j = 0; foreach (string tag in tagList) { opcItems[j] = new Item(); opcItems[j].ItemName = tag; j++; } // Attach items and event to group group.AddItems(opcItems); //group.DataChanged += new Opc.Da.DataChangedEventHandler(OPCSubscription_DataChanged); group.DataChanged += new Opc.Da.DataChangedEventHandler(onDataChange); }
private void Subscript() { //设定组状态 state = new Opc.Da.SubscriptionState(); //组(订阅者)状态,相当于OPC规范中组的参数 state.Name = "Welding"; //组名 state.ServerHandle = null; //服务器给该组分配的句柄。 //state.ClientHandle = Guid.NewGuid().ToString();//客户端给该组分配的句柄。 state.ClientHandle = Guid.NewGuid().GetHashCode(); //使用int类型, 效率可能有提高 state.Active = true; //激活该组。 state.UpdateRate = 1000; //刷新频率为1秒。 state.Deadband = 0; // 死区值,设为0时,服务器端该组内任何数据变化都通知组。 state.Locale = null; //不设置地区值。 //添加组 subscription = (Opc.Da.Subscription)m_server.CreateSubscription(state);//创建组 subscription.AddItems(AccessAdapter.GetOPCItemList().ToArray()); ////注册回调事件 //subscription.DataChanged += new Opc.Da.DataChangedEventHandler(this.OnDataChange); }
/// <summary> /// Active/Deactive the OPC Server as the "auto" mode. /// When timer reaches, update the data from OPC server automatically. /// </summary> public void AdviseDeadvise() { if (Subscription == null) { return; } Advised = !Advised; try { var state = new Opc.Da.SubscriptionState { Active = Advised }; Subscription.ModifyState((int)Opc.Da.StateMask.Active, state); } catch (Exception e) { throw e; } }
private void User_Program_Select_Operation_Load(object sender, EventArgs e) { BrakePressID(); OPCServer = new Opc.Da.Server(OPCFactory, null); //.Url = new Opc.URL("opcda://OHN66OPC/Matrikon.OPC.AllenBradleyPLCs.1"); OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6"); //OPCServer.Url = new Opc.URL("opcda://OHN7009/Matrikon.OPC.AllenBradleyPLCs.1"); OPCServer.Connect(); OperationSelection_StateRead = new Opc.Da.SubscriptionState(); OperationSelection_StateRead.Name = "153R_Spotweld"; OperationSelection_StateRead.UpdateRate = 200; OperationSelection_StateRead.Active = true; OperationSelection_Read = (Opc.Da.Subscription)OPCServer.CreateSubscription(OperationSelection_StateRead); OperationSelection_StateWrite = new Opc.Da.SubscriptionState(); OperationSelection_StateWrite.Name = "PB_OperationSelect_WriteGroup"; OperationSelection_StateWrite.Active = false; OperationSelection_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(OperationSelection_StateWrite); }
/// <summary> /// 设定组(订阅者)状态 /// </summary> public void SetGroup() { state = new Opc.Da.SubscriptionState(); //组名 state.Name = "IOTPLC"; //服务器给该组分配的句柄。 state.ServerHandle = null; //客户端给该组分配的句柄。 state.ClientHandle = Guid.NewGuid().ToString(); //激活该组。 state.Active = true; //刷新频率为1秒。 state.UpdateRate = 100; // 死区值,设为0时,服务器端该组内任何数据变化都通知组。 state.Deadband = 0; //不设置地区值。 state.Locale = null; //添加组 subscription = (Opc.Da.Subscription)m_server.CreateSubscription(state); }
/// <summary> /// 建立订阅 /// </summary> public void CreateSubscription() { try { subsState = new SubscriptionState(); subsState.Name = "OPCNJ"; //组名 subsState.ServerHandle = null; //服务器给该组分配的句柄。 subsState.ClientHandle = Guid.NewGuid().ToString(); //客户端给该组分配的句柄 subsState.Active = true; subsState.UpdateRate = 100; //刷新频率为1秒。 subsState.Deadband = 0; // 死区值,设为0时,服务器端该组内任何数据变化都通知组。 subsState.Locale = null; //不设置地区值。 subscription = (Opc.Da.Subscription)m_Server.CreateSubscription(subsState); Item[] items = new Item[10]; for (int i = 0; i < items.Length; i++) { items[i] = new Item(); items[i].ClientHandle = Guid.NewGuid().ToString(); //客户端给该数据项分配的句柄。 items[i].ItemPath = null; //该数据项在服务器中的路径 } items[0].ItemName = IEGInterface.Properties.Settings.Default.strSendBuffer; items[1].ItemName = IEGInterface.Properties.Settings.Default.strSendFlag; items[2].ItemName = IEGInterface.Properties.Settings.Default.strReceiveBuffer; items[3].ItemName = IEGInterface.Properties.Settings.Default.strReceiveFlag; items[4].ItemName = IEGInterface.Properties.Settings.Default.strEtv1Alarms; items[5].ItemName = IEGInterface.Properties.Settings.Default.strEtv2Alarms; items[6].ItemName = IEGInterface.Properties.Settings.Default.strHall1Alarms; items[7].ItemName = IEGInterface.Properties.Settings.Default.strHall2Alarms; items[8].ItemName = IEGInterface.Properties.Settings.Default.strHall3Alarms; items[9].ItemName = IEGInterface.Properties.Settings.Default.strHall4Alarms; subscription.AddItems(items); } catch (Exception ex) { throw new Exception("OPC建立订阅(CreateSubscription)异常:" + ex.ToString()); } }
void StartMonitoring() { foreach (var item in MonitoredMeasurements) { var subItem = new OpcDa.SubscriptionState { Name = item.Name, Active = true, UpdateRate = item.MonitorResolution }; var sub = l_server.CreateSubscription(subItem); sub.DataChanged += (handle, requestHandle, values) => { var p = values[0]; MonitorData(item, p); }; sub.AddItems(new[] { new OpcDa.Item { ItemName = item.Path } }); sub.SetEnabled(true); } }
private Object getOPCValue(String ItemName, BrowseElement[] be) { // Create a group Opc.Da.Subscription group; Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = ItemName; groupState.Active = true; group = (Opc.Da.Subscription)server.CreateSubscription(groupState); //Console.WriteLine(group.); // add items to the group. Opc.Da.Item[] items = new Opc.Da.Item[1]; items[0] = new Opc.Da.Item(); items[0].ItemName = ItemName; items = group.AddItems(items); ItemValueResult[] ir = group.Read(items); return(ir[0].Value); }
/// <summary> /// Monitor the specified tag for changes /// </summary> /// <typeparam name="T">the type of tag to monitor</typeparam> /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name. /// E.g: the tag `foo.bar` monitors the tag `bar` on the folder `foo`</param> /// <param name="callback">the callback to execute when the value is changed. /// The first parameter is a MonitorEvent object which represents the data point, the second is an `unsubscribe` function to unsubscribe the callback</param> public void Monitor <T>(string tag, Action <ReadEvent <T>, Action> callback) { var subItem = new OpcDa.SubscriptionState { Name = (++_sub).ToString(CultureInfo.InvariantCulture), Active = true, UpdateRate = DefaultMonitorInterval }; var sub = _server.CreateSubscription(subItem); // I have to start a new thread here because unsubscribing // the subscription during a datachanged event causes a deadlock Action unsubscribe = () => new Thread(o => _server.CancelSubscription(sub)).Start(); sub.DataChanged += (handle, requestHandle, values) => { T casted; TryCastResult(values[0].Value, out casted); var monitorEvent = new ReadEvent <T>(); monitorEvent.Value = casted; monitorEvent.SourceTimestamp = values[0].Timestamp; monitorEvent.ServerTimestamp = values[0].Timestamp; if (values[0].Quality == OpcDa.Quality.Good) { monitorEvent.Quality = Quality.Good; } if (values[0].Quality == OpcDa.Quality.Bad) { monitorEvent.Quality = Quality.Bad; } callback(monitorEvent, unsubscribe); }; sub.AddItems(new[] { new OpcDa.Item { ItemName = tag } }); sub.SetEnabled(true); }
public override bool Initialize(string connectionString, int newPollerId) { bool result = false; ConnString = connectionString; try { PollerId = newPollerId; url = new Opc.URL(connectionString); server = null; var fact = new OpcCom.Factory(); server = new Opc.Da.Server(fact, null); server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); server.ServerShutdown += Shutdown; _tags = new List <Opc.Da.Item>(); Browse(); _groupWriteState = new Opc.Da.SubscriptionState(); _groupWriteState.Name = "GroupWrite"; _groupWriteState.Active = false; groupWrite = (Opc.Da.Subscription)server.CreateSubscription(_groupWriteState); Activated = true; logger.Logged("Info", "Состояние сервера: " + server.GetStatus().StatusInfo, "", ""); result = true; } catch (Exception ex) { logger.Logged("Error", "Не удалось подключиться к OPC DA серверу " + connectionString + ": " + ex.Message, "", ""); // logger.Logged("Warn", "Повторная попытка через 5 секунд...", "", ""); //Thread.Sleep(5000); } return(result); }
// Form Loads. // Checks Spot Weld Computer. // Connects to OPC Server private void User_Program_Reset_Weld_Count_Dialog_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(); ResetWeldCount_StateRead = new Opc.Da.SubscriptionState(); ResetWeldCount_StateRead.Name = "Reset_Weld_Count_Spotweld"; ResetWeldCount_StateRead.UpdateRate = 1000; ResetWeldCount_StateRead.Active = true; ResetWeldCount_Read = (Opc.Da.Subscription)OPCServer.CreateSubscription(ResetWeldCount_StateRead); ResetWeldCount_StateWrite = new Opc.Da.SubscriptionState(); ResetWeldCount_StateWrite.Name = "PB_Reset_Part_Weld_Count_On"; ResetWeldCount_StateWrite.Active = true; ResetWeldCount_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(ResetWeldCount_StateWrite); ResetWeldCount_Off_StateWrite = new Opc.Da.SubscriptionState(); ResetWeldCount_Off_StateWrite.Name = "PB_Reset_Part_Weld_Count_Off"; ResetWeldCount_Off_StateWrite.Active = true; ResetWeldCount_Off_Write = (Opc.Da.Subscription)OPCServer.CreateSubscription(ResetWeldCount_Off_StateWrite); }
public void ConnectToServer() { try { //url = new Opc.URL("opcda://MUHUMTHA/Kepware.KEPServerEX.V6"); //url = new Opc.URL("opcda://IAPENG1/RSLinx OPC Server"); //REMOTE OPC CONNECTION url = new Opc.URL("opcda://MUHUMTHA/RSLinx OPC Server.MUHUNTHANPC"); 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()); Opc.Da.Item[] items_read = groupRead.AddItems(createSomeTags()); // Create a write group //groupStateWrite = new Opc.Da.SubscriptionState(); //groupStateWrite.Name = "Group_Write"; //groupStateWrite.UpdateRate = 1000; //groupStateWrite.Active = false;//not needed to read if you want to write only //groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupStateWrite); //groupWrite.DataChanged += new Opc.Da.DataChangedEventHandler(ReadCompleted); Global.flag1 = true; } catch (Exception E) { Console.WriteLine(E.Message); } }
public override void Add(string itemName) { lock(_thisLock) { try { OpcAddress addr = Find(itemName); if (addr == null) { string[] itemIdSplited = itemName.Split(']'); string[] addressSplited; string topic = ""; //Encontra o nome do topico if (itemName.Contains(']')) { topic = itemName.Split(']')[0].Substring(1); } if (itemIdSplited.Length > 1) { addressSplited = itemIdSplited[1].Split(':'); } else { itemIdSplited = itemName.Split('.'); addressSplited = itemIdSplited[2].Split(':'); } Opc.Da.Subscription opcDaGroup = null; foreach (Opc.Da.Subscription opcDaGrp in _opcDaServer.Subscriptions) { if (opcDaGrp.Name == topic + addressSplited[0]) { opcDaGroup = opcDaGrp; } } if (opcDaGroup == null) { Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.ClientHandle = Guid.NewGuid().ToString(); groupState.Name = topic + addressSplited[0]; // groupState.UpdateRate = 250; opcDaGroup = (Opc.Da.Subscription)_opcDaServer.CreateSubscription(groupState); //opcDaGroup.DataChanged += new Opc.Da.DataChangedEventHandler(OpcDataChanged); opcDaGroup.DataChanged += delegate(object subscriptionHandle, object requestHandle, ItemValueResult[] values) { // BackgroundWorker back = new BackgroundWorker(); // back.DoWork += delegate(object sender, DoWorkEventArgs e) // { // foreach (Opc.Da.ItemValueResult ivr in values) // { // OpcAddress adr = Find(ivr.ItemName); // adr.SetValue(ivr.Value.ToString()); // OnDataChanged(new DataChangedEventArgs(ivr.ItemName, ivr.Value)); // } // }; // back.RunWorkerAsync(); foreach (Opc.Da.ItemValueResult ivr in values) { OpcAddress adr = Find(ivr.ItemName); adr.SetValue(ivr.Value.ToString()); OnDataChanged(new DataChangedEventArgs(ivr.ItemName, ivr.Value)); } }; } Opc.Da.Item opcDaItem = new Opc.Da.Item(); opcDaItem.ClientHandle = Guid.NewGuid().ToString(); opcDaItem.ItemName = itemName; opcDaItem.MaxAgeSpecified = true; opcDaItem.MaxAge = 100; opcDaItem.SamplingRateSpecified = true; opcDaItem.SamplingRate = 10; opcDaGroup.AddItems(new Opc.Da.Item[] { opcDaItem }); addr = new OpcAddress(opcDaItem, opcDaGroup); _addrList.Add(addr); } return; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } } }
public void AddSubscription(string groupName, List<string> tagList, DataChangedEventHandler onDataChange) { if (!_server.IsConnected) { Console.WriteLine("Connection to OPC server is not established"); return; } // Create group Opc.Da.Subscription group; Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState(); groupState.Name = groupName; groupState.Active = true; groupState.UpdateRate = 200; // Short circuit if group already exists SubscriptionCollection existingCollection = _server.Subscriptions; if (existingCollection.Count > 0) { for(int i = 0; i < existingCollection.Count; i++){ if (existingCollection[i].Name == groupName) { Console.WriteLine(String.Format("Subscription group {0} already exists", groupName)); return; } } } group = (Opc.Da.Subscription)_server.CreateSubscription(groupState); // Create list of items to monitor Item[] opcItems = new Item[1]; int j = 0; foreach (string tag in tagList) { opcItems[j] = new Item(); opcItems[j].ItemName = tag; j++; } // Attach items and event to group group.AddItems(opcItems); //group.DataChanged += new Opc.Da.DataChangedEventHandler(OPCSubscription_DataChanged); group.DataChanged += new Opc.Da.DataChangedEventHandler(onDataChange); }