/// <summary>
        /// opc 그룹 모두 지우기
        /// </summary>
        /// <param name="reset">command 그룹 삭제 여부</param>
        public void RemoveAllGroup(bool reset)
        {
            try
            {
                for (int j = this.Server.Subscriptions.Count - 1; j >= 0; j--)
                {
                    Opc.Da.Subscription sub = this.Server.Subscriptions[j];

                    if (reset == false)
                    {
                        if (sub.Name == "cmd")
                        {
                            continue;
                        }
                    }


                    this.Server.CancelSubscription(sub);
                }

                if (reset)
                {
                    this.CommandSubscription = null;
                }

                this.WriteSubscriptions.Clear();
                this.ReadSubscriptions.Clear();
            }
            catch (Exception ex)
            {
                CommonController.Instance.PrintLog("RemoveAllGroup , " + ex.GetType().Name);
                CommonController.Instance.PrintLog(ex.StackTrace);
            }
        }
Beispiel #2
0
        /// <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;
            }
        }
 private void EnableDataWriteCallback(Subscription group, ItemValue[] writeValues)
 {
     Opc.IRequest req;
     group.Write(writeValues, 44.0, new WriteCompleteEventHandler(WriteCompleteCallback), out req);
     group.State.Active = true;
     Console.WriteLine();
 }
        private void EnableDataChangedCallback(Subscription group)
        {
            DataChangedEventHandler handler = new DataChangedEventHandler(DataChangedCallback);

            group.DataChanged += new DataChangedEventHandler(DataChangedCallback);
            group.State.Active = true;
        }
        /*********************************************************************************************************************
        *
        * Buttons End
        *
        *********************************************************************************************************************/

        /*********************************************************************************************************************
        *
        *  Methods
        *
        *  Show Components():
        *  Search For Components():
        *  Search For Job():
        *
        *
        *********************************************************************************************************************/

        private void JobData_ConnectToOPCServer(object sender, EventArgs e)
        {
            try
            {
                OPCServer     = new Opc.Da.Server(OPCFactory, null);
                OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6");
                OPCServer.Connect();

                Component_StateRead            = new Opc.Da.SubscriptionState();
                Component_StateRead.Name       = "Component_Reading";
                Component_StateRead.UpdateRate = 1000;
                Component_StateRead.Active     = true;
                Component_Read              = (Opc.Da.Subscription)OPCServer.CreateSubscription(Component_StateRead);
                Component_Read.DataChanged += new Opc.Da.DataChangedEventHandler(Component_Read_DataChanged);

                ScanNewPart_StateWrite        = new Opc.Da.SubscriptionState();
                ScanNewPart_StateWrite.Name   = "ScanNewPart_WriteGroup";
                ScanNewPart_StateWrite.Active = true;
                ScanNewPart_Write             = (Opc.Da.Subscription)OPCServer.CreateSubscription(ScanNewPart_StateWrite);

                Hardware_StateWrite        = new Opc.Da.SubscriptionState();
                Hardware_StateWrite.Name   = "Hardware_WriteGroup";
                Hardware_StateWrite.Active = true;
                Hardware_Write             = (Opc.Da.Subscription)OPCServer.CreateSubscription(Hardware_StateWrite);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 private void EnableDataReadCallback(Subscription group)
 {
     Opc.IRequest req;
     group.Read(group.Items, 44.0, new ReadCompleteEventHandler(ReadCompleteCallback), out req);
     Console.WriteLine();
     group.State.Active = true;
 }
Beispiel #7
0
        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>
        /// 写数据
        /// </summary>
        /// <param name="opcDataItem"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public OpcResult Write(OpcDataItem opcDataItem, object value)
        {
            OpcResult opcResult = OpcResult.Unknow;

            //如果未连接那么返回
            if (!this.IsConnected)
            {
                if (!Equals(null, OnErrorHappened))
                {
                    OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "Opc服务器未连接,请先连接再写数据项", null));
                }
                return(opcResult);
            }
            try
            {
                if (Equals(null, opcDataItem))
                {
                    throw new ArgumentNullException("opcDataItem参数不能为空。");
                }

                Opc.Da.Subscription tmpSubscription =
                    this.opcServer.Subscriptions.Cast <Opc.Da.Subscription>().FirstOrDefault(a => a.State.UpdateRate == opcDataItem.UpdateRate);
                var itemValue =
                    new ItemValue((ItemIdentifier)tmpSubscription.Items.FirstOrDefault(a => a.ItemName == opcDataItem.Name));
                //itemValue.Value = opcDataItem.NewValue;
                itemValue.Value = value;
                var results = tmpSubscription.Write(new ItemValue[] { itemValue });
                //写多次
                //for (int i = 0; i < 20; i++)
                //{
                results = tmpSubscription.Write(new ItemValue[] { itemValue });
                //}
                if (results.Count() < 1 && !Equals(null, OnErrorHappened))
                {
                    opcResult = OpcResult.E_UNKNOWN_ITEM_NAME;
                    OnErrorHappened(this, new OpcErrorEventArgs(opcResult, "写入数据项时发生错误,未找到数据项:" + opcDataItem.Name, null));
                    opcDataItem.Quality = OpcResult.Unknow;
                    return(opcResult);
                }
                foreach (var v in results)
                {
                    Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                    if (v.ResultID != Opc.ResultID.S_OK && !Equals(null, OnErrorHappened))
                    {
                        Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                        OnErrorHappened(this, new OpcErrorEventArgs(opcResult, "写入数据项时发生错误:" + v.ResultID.Name, null));
                    }
                }//end foreach
                return(opcResult);
            }
            catch (Exception ex)
            {
                if (!Equals(null, OnErrorHappened))
                {
                    OnErrorHappened(this, new OpcHelper.OpcErrorEventArgs(OpcResult.E_FAIL, "写入数据时错误。", ex));
                }
                return(opcResult);
            }
        }
        /// <summary>
        /// 读数据
        /// </summary>
        /// <param name="opcDataItem"></param>
        /// <returns></returns>
        public OpcDataItem Read(OpcDataItem opcDataItem)
        {
            OpcDataItem opcDataItemResult = null;

            //如果未连接那么返回
            if (!this.IsConnected)
            {
                if (!Equals(null, OnErrorHappened))
                {
                    OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "Opc服务器未连接,请先连接再读取数据项", null));
                }
                return(opcDataItemResult);
            }
            try
            {
                if (Equals(null, opcDataItem))
                {
                    throw new ArgumentNullException("opcDataItem参数不能为空。");
                }
                Opc.Da.Subscription tmpSubscription =
                    this.opcServer.Subscriptions.Cast <Opc.Da.Subscription>().FirstOrDefault(a => a.State.UpdateRate == opcDataItem.UpdateRate);
                var       item    = tmpSubscription.Items.Where(a => a.ItemName == opcDataItem.Name);
                var       results = tmpSubscription.Read(item.ToArray());
                OpcResult opcResult;
                if (results.Count() < 1 && !Equals(null, OnErrorHappened))
                {
                    opcResult = OpcResult.E_UNKNOWN_ITEM_NAME;
                    OnErrorHappened(this, new OpcErrorEventArgs(opcResult, "读取数据项时发生错误,未找到数据项:" + opcDataItem.Name, null));
                    opcDataItem.Quality = OpcResult.E_UNKNOWN_ITEM_NAME;
                    return(opcDataItem);
                }
                foreach (var v in results)
                {
                    Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                    opcDataItemResult          = this.OpcDataItems.FirstOrDefault(a => a.Name == opcDataItem.Name);
                    opcDataItemResult.Quality  = opcResult;
                    opcDataItemResult.OldValue = opcDataItemResult.NewValue;
                    opcDataItemResult.NewValue = v.Value;
                    if (v.ResultID != Opc.ResultID.S_OK && !Equals(null, OnErrorHappened))
                    {
                        Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                        OnErrorHappened(this, new OpcErrorEventArgs(opcResult, "读取数据项时发生错误:" + v.ResultID.Name, null));
                    }
                }//end foreach
                return(opcDataItemResult.Clone() as OpcDataItem);
            }
            catch (Exception ex)
            {
                if (!Equals(null, OnErrorHappened))
                {
                    OnErrorHappened(this, new OpcHelper.OpcErrorEventArgs(OpcResult.E_FAIL, "读取数据时错误。", ex));
                }
                return(opcDataItemResult);
            }
        }
Beispiel #10
0
 /// <summary>
 /// Refesh the data, only works in "auto" mode.
 /// </summary>
 public void Refresh()
 {
     try
     {
         Subscription.Refresh();
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        /// <summary>
        /// olga opc 서버용 command group 추가.
        /// </summary>
        /// <returns></returns>
        private bool SetOLGACmd()
        {
            bool result = true;

            SubscriptionState subscriptionstate = new SubscriptionState()
            {
                Active       = true,
                Deadband     = 0,
                KeepAlive    = 0,
                UpdateRate   = 1000,
                ClientHandle = Guid.NewGuid().ToString(),
                Name         = "cmd"
            };

            //현재 선택된 서버에 Group을 생성한다.
            Opc.Da.Subscription cmd = (Opc.Da.Subscription) this.Server.CreateSubscription(subscriptionstate);
            this.CommandSubscription = new OPCSubscription()
            {
                Subscription = cmd
            };



            List <Opc.Da.Item> cmdlist = new List <Opc.Da.Item>();

            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.ExternalClock", this.Controller.OLGAModelName))); //0
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.TIME", this.Controller.OLGAModelName)));          //1
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.State", this.Controller.OLGAModelName)));         //2
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.LoadSnap", this.Controller.OLGAModelName)));      //3
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.LoadSnap.File", this.Controller.OLGAModelName))); //4
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.SaveSnap", this.Controller.OLGAModelName)));      //5
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.SaveSnap.File", this.Controller.OLGAModelName))); //6
            cmdlist.Add(OPCServer.CreateOPCItem(string.Format("Sim.{0}.LastMessage", this.Controller.OLGAModelName)));   //7

            ItemResult[] ir = cmd.AddItems(cmdlist.ToArray());

            StringBuilder strb = new StringBuilder();

            for (int i = 0; i < ir.Length; i++)
            {
                if (ir[i].ResultID.Failed())
                {
                    result = false;
                    strb.AppendFormat("{0}\n", ir[i].ItemName);
                }
            }
            if (result == false)
            {
                strb.Insert(0, "Check OLGA OPC Server configuration, can't find the tag\n");
                CommonController.Instance.PrintLog(strb.ToString());
            }

            return(result);
        }
Beispiel #12
0
        public void ConnectToServer()
        {
            try
            {
                url = new Opc.URL("opcda://IAPENG1/RSLinx OPC Server");
                //server = new Opc.Da.Server(fact, null);
                server = new Opc.Da.Server(fact, url);
                System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential();
                Opc.ConnectData connecteddata = new Opc.ConnectData(networkCredential);
                server.Connect(url, connecteddata);
                groupState             = new Opc.Da.SubscriptionState();
                groupState.Name        = "Group";
                groupState.UpdateRate  = 1000;                                              // this isthe time between every reads from OPC server
                groupState.Active      = true;                                              //this must be true if you the group has to read value
                groupRead              = (Opc.Da.Subscription)server.CreateSubscription(groupState);
                groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(UpdateTagData); //callback when the data are readed

                if (items[0] == null)
                {
                    items[0] = new Opc.Da.Item();
                    items[1] = new Opc.Da.Item();
                    items[2] = new Opc.Da.Item();
                    items[3] = new Opc.Da.Item();
                    items[4] = new Opc.Da.Item();
                    items[5] = new Opc.Da.Item();
                    items[6] = new Opc.Da.Item();
                    items[7] = new Opc.Da.Item();
                }

                items[0].ItemName = "[PLC2]LocalDateTime[0]";
                items[1].ItemName = "[PLC2]LocalDateTime[1]";
                items[2].ItemName = "[PLC2]LocalDateTime[2]";
                items[3].ItemName = "[PLC2]LocalDateTime[3]";
                items[4].ItemName = "[PLC2]LocalDateTime[4]";
                items[5].ItemName = "[PLC2]LocalDateTime[5]";
                items[6].ItemName = "[PLC2]LocalDateTime[6]";
                items[7].ItemName = "[PLC2]LocalDateTime";

                items = groupRead.AddItems(items);

                // Create a write group
                groupStateWrite        = new Opc.Da.SubscriptionState();
                groupStateWrite.Name   = "Group Write";
                groupStateWrite.Active = false;//not needed to read if you want to write only
                groupWrite             = (Opc.Da.Subscription)server.CreateSubscription(groupStateWrite);
            }
            catch (Exception E)
            {
                Console.WriteLine(E.Message);
            }
        }
Beispiel #13
0
        private void User_Program_Teach_Senson_Load(object sender, EventArgs e)
        {
            SpotWeldID(); // Get Computer ID and Set Tag Name

            // Connect to OPC Server
            OPCServer     = new Opc.Da.Server(OPCFactory, null);
            OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6");
            OPCServer.Connect();

            Sensor_StateRead            = new Opc.Da.SubscriptionState();
            Sensor_StateRead.Name       = "Teach_Sensor_OPC";
            Sensor_StateRead.UpdateRate = 1000;
            Sensor_StateRead.Active     = true;
            Sensor_Read              = (Opc.Da.Subscription)OPCServer.CreateSubscription(Sensor_StateRead);
            Sensor_Read.DataChanged += new Opc.Da.DataChangedEventHandler(Sensor_Read_DataChanged);

            TeachSensor_StateWrite        = new Opc.Da.SubscriptionState();
            TeachSensor_StateWrite.Name   = "OPCWriteGroup";
            TeachSensor_StateWrite.Active = false;
            TeachSensor_Write             = (Opc.Da.Subscription)OPCServer.CreateSubscription(TeachSensor_StateWrite);

            GroupStateWriteCompOne        = new Opc.Da.SubscriptionState();
            GroupStateWriteCompOne.Name   = "OPCWriteOneGroup";
            GroupStateWriteCompOne.Active = false;
            GroupWriteCompOne             = (Opc.Da.Subscription)OPCServer.CreateSubscription(GroupStateWriteCompOne);

            GroupStateWriteCompTwo        = new Opc.Da.SubscriptionState();
            GroupStateWriteCompTwo.Name   = "OPCWriteTwoGroup";
            GroupStateWriteCompTwo.Active = false;
            GroupWriteCompTwo             = (Opc.Da.Subscription)OPCServer.CreateSubscription(GroupStateWriteCompTwo);

            GroupStateWriteCompThree        = new Opc.Da.SubscriptionState();
            GroupStateWriteCompThree.Name   = "OPCWriteThreeGroup";
            GroupStateWriteCompThree.Active = false;
            GroupWriteCompThree             = (Opc.Da.Subscription)OPCServer.CreateSubscription(GroupStateWriteCompThree);

            // Get The Component ID From the User Program
            Component_1_TextBox.Text = owner.Comp1_TextBox.Text;
            Component_2_TextBox.Text = owner.Comp2_TextBox.Text;
            Component_3_TextBox.Text = owner.Comp3_TextBox.Text;

            CheckComponentValue(); // Find the Number of Components
            //TargetValueSet_TextBox.Clear();
            OPC_TeachSensorValue = 1;
            TeachSensor_OPC();
            SensorRead_OPC();
            WriteComponentOne_OPC();
        }
Beispiel #14
0
        /// <summary>
        /// Synchronize read from the OPC Server
        /// </summary>
        /// <param name="results"></param>
        /// <returns></returns>
        public bool SyncRead(ref Opc.Da.ItemValueResult[] results)
        {
            if (Subscription == null)
            {
                return(false);
            }

            try
            {
                results = Subscription.Read(Subscription.Items);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(results != null && results.Length != 0);
        }
Beispiel #15
0
 /// <summary>
 /// Synchronize write to the OPC Server
 /// </summary>
 public bool SyncWrite(ref ItemValue[] items)
 {
     if (Subscription == null)
     {
         return(false);
     }
     try
     {
         var results = Subscription.Write(items);
         return(true);
     }
     catch (Exception e)
     {
         //MessageBox.Show(e.Message);
         throw e;
     }
 }
        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);
        }
Beispiel #17
0
        /// <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;
            }
        }
Beispiel #18
0
        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);
        }
Beispiel #19
0
        /// <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);
        }
Beispiel #20
0
        /// <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());
            }
        }
Beispiel #21
0
        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);
        }
Beispiel #23
0
        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);
            }
        }
        /// <summary>
        /// 그룹추가.
        /// </summary>
        /// <param name="name">group name</param>
        /// <param name="type">read 0, write 1</param>
        /// <returns>추가 성공한 group</returns>
        public OPCSubscription AddGroup(string name, int type)
        {
            bool            duplicated = false;
            OPCSubscription result     = null;

            if (type == 0)
            {
                for (int i = 0; i < this.ReadSubscriptions.Count; i++)
                {
                    if (this.ReadSubscriptions[i].Name.Equals(name))
                    {
                        duplicated = true;
                        result     = this.ReadSubscriptions[i];
                        break;
                    }
                }
            }
            else if (type == 1)
            {
                for (int i = 0; i < this.WriteSubscriptions.Count; i++)
                {
                    if (this.WriteSubscriptions[i].Name.Equals(name))
                    {
                        duplicated = true;
                        result     = this.WriteSubscriptions[i];
                        break;
                    }
                }
            }

            //중복이 아니라면
            if (duplicated == false)
            {
                SubscriptionState subscriptionstate = new SubscriptionState()
                {
                    Active       = true,
                    Deadband     = 0,
                    KeepAlive    = 0,
                    UpdateRate   = 1000,
                    ClientHandle = Guid.NewGuid().ToString(),
                    Name         = name
                };

                //현재 선택된 서버에 Group을 생성한다.
                Opc.Da.Subscription subscription = (Opc.Da.Subscription)Server.CreateSubscription(subscriptionstate);


                OPCSubscription newgroup = new OPCSubscription()
                {
                    Subscription = subscription
                };

                if (type == 0)
                {
                    this.ReadSubscriptions.Add(newgroup);
                }
                else if (type == 1)
                {
                    this.WriteSubscriptions.Add(newgroup);
                }

                result = newgroup;
            }
            return(result);
        }
Beispiel #25
0
        public void Work()
        {
            int i = 5;

            if (i == 1)
            {
                url    = new Opc.URL("opcda://192.168.0.4/OPC.PHDServerDA.1");
                server = new Opc.Da.Server(fact, null);
                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                Opc.Da.Item[] itemCollection = new Opc.Da.Item[1];
                itemCollection[0] = new Opc.Da.Item {
                    ItemName = "RTOS.TEST.PV", MaxAge = -1
                };
                Opc.Da.ItemValueResult[] result = server.Read(itemCollection);

                Console.WriteLine(result[0].Value);
                server.Disconnect();
            }
            else if (i == 2)
            {
                url    = new Opc.URL("opcda://192.168.0.4/OPC.PHDServerDA.1");
                server = new Opc.Da.Server(fact, null);
                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                groupState              = new Opc.Da.SubscriptionState();
                groupState.Name         = "Group";
                groupState.ServerHandle = null;
                groupState.ClientHandle = Guid.NewGuid().ToString();
                groupState.Active       = true;
                groupState.UpdateRate   = 1000;
                groupState.Deadband     = 0;
                groupState.Locale       = null;

                groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState);


                string[] itemName = { "RTOS.TEST.PV", "RTOR.TI1237.DACA.PV" };

                Opc.Da.Item[] items = new Opc.Da.Item[2];

                for (int j = 0; j < items.Length; j++)
                {
                    items[j] = new Opc.Da.Item();
                    items[j].ClientHandle = Guid.NewGuid().ToString();
                    items[j].ItemPath     = null;
                    items[j].ItemName     = itemName[j];
                }

                groupRead.AddItems(items);
                //groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(group_DataChanged);

                Opc.Da.ItemValueResult[] results = groupRead.Read(groupRead.Items);
                foreach (ItemValueResult result in results)
                {
                    Console.WriteLine("{0},{1},{2},{3}", result.ItemName, result.Value, result.Quality, result.Timestamp);
                }
                //groupRead.DataChanged -= new Opc.Da.DataChangedEventHandler(group_DataChanged);

                groupRead.RemoveItems(groupRead.Items);
                server.CancelSubscription(groupRead);
                groupRead.Dispose();
                server.Disconnect();
            }
            else if (i == 3)
            {
                url    = new Opc.URL("opcda://192.168.0.4/OPC.PHDServerDA.1");
                server = new Opc.Da.Server(fact, null);
                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                groupState              = new Opc.Da.SubscriptionState();
                groupState.Name         = "Group";
                groupState.ServerHandle = null;
                groupState.ClientHandle = Guid.NewGuid().ToString();
                groupState.Active       = true;
                groupState.UpdateRate   = 1000;
                groupState.Deadband     = 0;
                groupState.Locale       = null;

                groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupState);

                string[] itemName = { "RTOS.TEST.PV", "RTOS.TEST2.PV" };

                Opc.Da.Item[] items = new Opc.Da.Item[2];

                for (int j = 0; j < items.Length; j++)
                {
                    items[j] = new Opc.Da.Item();
                    items[j].ClientHandle = Guid.NewGuid().ToString();
                    items[j].ItemPath     = null;
                    items[j].ItemName     = itemName[j];
                }

                groupWrite.AddItems(items);

                //groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(group_DataChanged);

                Opc.Da.ItemValue[] writeValues = new Opc.Da.ItemValue[groupWrite.Items.Length];
                for (int k = 0; k < groupWrite.Items.Length; k++)
                {
                    writeValues[k] = new Opc.Da.ItemValue((ItemIdentifier)groupWrite.Items[k]);
                }

                writeValues[0].Value = 5;
                writeValues[1].Value = 6;

                groupWrite.Write(writeValues);

                Console.WriteLine("Press any key to close...");
                Console.ReadLine();

                //groupRead.DataChanged -= new Opc.Da.DataChangedEventHandler(group_DataChanged);

                groupWrite.RemoveItems(groupWrite.Items);
                server.CancelSubscription(groupWrite);
                groupWrite.Dispose();
                server.Disconnect();
            }
            else if (i == 4)
            {
                url       = new Opc.URL("opchda://192.168.0.4/OPC.PHDServerHDA.1");
                serverHda = new Opc.Hda.Server(fact, null);
                serverHda.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                try
                {
                }
                catch (Opc.ConnectFailedException opcConnEx)
                {
                    Console.WriteLine(string.Format("Could not connect to server {0}", "OPC.PHDServerHDA.1"));
                    Console.WriteLine(opcConnEx.ToString());
                }

                Console.WriteLine("Are we connected? " + serverHda.IsConnected);

                string[] itemName = { "RTOS.TEST.PV", "RTOS.TEST2.PV" };

                Opc.Hda.Trend groupHda = new Trend(serverHda);

                groupHda.Name        = "HDA";
                groupHda.AggregateID = AggregateID.NOAGGREGATE;
                DateTime startTime = DateTime.Now.AddHours(-1);
                DateTime endTime   = DateTime.Now;
                groupHda.StartTime     = new Opc.Hda.Time(startTime);
                groupHda.EndTime       = new Opc.Hda.Time(endTime);
                groupHda.MaxValues     = 0;
                groupHda.IncludeBounds = false;

                serverHda.Trends.Add(groupHda);

                Opc.Hda.Item[] items = new Opc.Hda.Item[2];
                for (int m = 0; m < 2; m++)
                {
                    items[m]              = new Opc.Hda.Item();
                    items[m].ItemName     = itemName[m];
                    items[m].ItemPath     = null;
                    items[m].ClientHandle = Guid.NewGuid().ToString();
                }

                IdentifiedResult[] identifiedResult = serverHda.CreateItems(items);

                if (identifiedResult != null)
                {
                    foreach (IdentifiedResult item in identifiedResult)
                    {
                        if (item.ResultID.Succeeded())
                        {
                            groupHda.Items.Add(new Opc.Hda.Item(item));
                        }
                    }
                }

                Opc.Hda.ItemValueCollection[] results = groupHda.ReadRaw();

                Opc.Hda.ItemValueCollection result1 = results[0];

                foreach (Opc.Hda.ItemValue result in result1)
                {
                    Console.WriteLine("{0},{1},{2}", result.Value, result.Quality, result.Timestamp);
                }

                serverHda.Disconnect();
            }
            else if (i == 5)
            {
                url       = new Opc.URL("opchda://192.168.0.4/OPC.PHDServerHDA.1");
                serverHda = new Opc.Hda.Server(fact, null);
                serverHda.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                try
                {
                }
                catch (Opc.ConnectFailedException opcConnEx)
                {
                    Console.WriteLine(string.Format("Could not connect to server {0}", "OPC.PHDServerHDA.1"));
                    Console.WriteLine(opcConnEx.ToString());
                }

                Console.WriteLine("Are we connected? " + serverHda.IsConnected);

                string[] itemName = { "RTOR.TI1237.DACA.PV", "RTOS.TEST2.PV" };

                Opc.Hda.Trend groupHda = new Trend(serverHda);

                groupHda.Name        = "HDA";
                groupHda.AggregateID = AggregateID.AVERAGE;

                DateTime startTime = DateTime.Now.AddHours(-1);
                DateTime endTime   = DateTime.Now;
                //TimeSpan span = endTime.Subtract(startTime);
                //int calcInterval = ((int)span.TotalSeconds);
                //groupHda.ResampleInterval = (decimal)calcInterval;

                //DateTime startTime = new DateTime(2020, 6, 12, 9, 0, 0, 0);
                //DateTime endTime = new DateTime(2020, 6, 12, 10, 0, 0, 0);
                int calcInterval = 300;
                groupHda.ResampleInterval = (decimal)calcInterval;


                groupHda.StartTime     = new Opc.Hda.Time(startTime);
                groupHda.EndTime       = new Opc.Hda.Time(endTime);
                groupHda.MaxValues     = 0;
                groupHda.IncludeBounds = false;

                serverHda.Trends.Add(groupHda);

                Opc.Hda.Item[] items = new Opc.Hda.Item[2];
                for (int m = 0; m < 2; m++)
                {
                    items[m]              = new Opc.Hda.Item();
                    items[m].ItemName     = itemName[m];
                    items[m].ItemPath     = null;
                    items[m].ClientHandle = Guid.NewGuid().ToString();
                }

                IdentifiedResult[] identifiedResult = serverHda.CreateItems(items);

                if (identifiedResult != null)
                {
                    foreach (IdentifiedResult item in identifiedResult)
                    {
                        if (item.ResultID.Succeeded())
                        {
                            groupHda.Items.Add(new Opc.Hda.Item(item));
                        }
                    }
                }

                Opc.Hda.ItemValueCollection[] results = groupHda.ReadProcessed();

                Opc.Hda.ItemValueCollection result1 = results[0];

                foreach (Opc.Hda.ItemValue result in result1)
                {
                    Console.WriteLine("{0},{1},{2}", result.Value, result.Quality, result.Timestamp);
                }

                serverHda.Disconnect();
            }
        }
Beispiel #26
0
        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;
                }
            }
        }
        /// <summary>
        /// 创建订阅,并添加Items
        /// </summary>
        private void CreatSubscription(List <string> lstConnect)
        {
            try
            {
                if (null == lstConnect)// || null != m_subscription)
                {
                    return;
                }

                if (null != m_subscription)
                {
                    if (0 < m_subscription.Items.Count() && lstConnect.Contains(m_subscription.Items.First().ItemName))
                    {
                        return;
                    }

                    #region 添加items
                    Item[]   itemNames1 = new Item[lstConnect.Count];
                    string[] fConnects1 = lstConnect.ToArray();
                    for (int i = 0; i < itemNames1.Length; i++)
                    {
                        itemNames1[i] = new Item();                             // 创建一个项Item对象。
                        itemNames1[i].ClientHandle = Guid.NewGuid().ToString(); // 客户端给该数据项分配的句柄。
                        itemNames1[i].ItemPath     = null;                      // 该数据项在服务器中的路径。
                        itemNames1[i].ItemName     = fConnects1[i];             // 该数据项在服务器中定义的名字
                        ItemValueResult itemValue = new ItemValueResult();
                        itemValue.ItemName = fConnects1[i];                     // 该数据项在服务器中定义的名字
                        m_lstItemValueResult.Add(itemValue);
                    }
                    #endregion

                    m_subscription.AddItems(itemNames1);
                    return;
                }

                m_sendState              = new SubscriptionState();
                m_sendState.Name         = m_groupName;               // 组名
                m_sendState.ServerHandle = null;                      // 服务器给该组分配的句柄。
                m_sendState.ClientHandle = Guid.NewGuid().ToString(); // 客户端给该组分配的句柄。
                m_sendState.Active       = true;                      // 激活该组。
                m_sendState.UpdateRate   = m_updateRate;              // 刷新频率
                m_sendState.Deadband     = 0;                         // 死区值,设为0时,服务器端该组内任何数据变化都通知组。
                m_sendState.Locale       = null;                      // 不设置地区值。
                m_subscription           = (Opc.Da.Subscription)m_server.CreateSubscription(m_sendState);

                #region 添加items
                Item[]   itemNames = new Item[lstConnect.Count];
                string[] fConnects = lstConnect.ToArray();
                for (int i = 0; i < itemNames.Length; i++)
                {
                    itemNames[i] = new Item();                             // 创建一个项Item对象。
                    itemNames[i].ClientHandle = Guid.NewGuid().ToString(); // 客户端给该数据项分配的句柄。
                    itemNames[i].ItemPath     = null;                      // 该数据项在服务器中的路径。
                    itemNames[i].ItemName     = fConnects[i];              // 该数据项在服务器中定义的名字
                    ItemValueResult itemValue = new ItemValueResult();
                    itemValue.ItemName = fConnects[i];                     // 该数据项在服务器中定义的名字
                    m_lstItemValueResult.Add(itemValue);
                }
                #endregion

                m_subscription.AddItems(itemNames);
            }
            catch (Exception ex)
            {
                CLOGException.Trace("函数CommunicationLib.COPCAccessTimer.CreatSubscription 异常", CBaseMethods.MyBase.GetExceptionInfo(ex));
            }
        }
        /// <summary>
        /// 注册Opc数据项集合
        /// </summary>
        /// <param name="opcDataItems"></param>
        private void registerOpcDataItems(IList <OpcDataItem> opcDataItems)
        {
            this.OpcDataItems   = opcDataItems;
            daemonTimer.Enabled = false;
            daemonTimer.Stop();

            //如果未连接那么返回
            if (!this.IsConnected)
            {
                if (!Equals(null, OnErrorHappened))
                {
                    OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "Opc服务器未连接,请先连接在订阅数据项", null));
                }
                return;
            }
            #region 没有数据项那么清空所有订阅

            //如果订阅的DataItem没有,那么清空现在所有订阅
            if (Equals(null, opcDataItems) || opcDataItems.Count() < 1)
            {
                if (!Equals(this.opcServer.Subscriptions, null) && this.opcServer.Subscriptions.Count > 0)
                {
                    foreach (Opc.Da.Subscription thisSubscription in this.opcServer.Subscriptions)
                    {
                        thisSubscription.RemoveItems(thisSubscription.Items);
                        thisSubscription.DataChanged -= ThisSubscription_DataChanged;
                        this.opcServer.CancelSubscription(thisSubscription);
                        thisSubscription.Dispose();
                    }
                    this.opcServer.Subscriptions.Clear();

                    //订阅项取消后通知外部程序
                    if (!Equals(null, OnLogHappened))
                    {
                        OnLogHappened(this, new OpcHelper.OpcLogEventArgs("已经取消所有订阅"));
                    }
                    return;
                }
            }

            #endregion   数据项需要更新或者删除

            //根据要订阅的新数据项,增加或者移除现在的订阅
            if (!IsConnected)
            {
                if (!Equals(null, OnLogHappened))
                {
                    OnLogHappened(this, new OpcLogEventArgs("Opc服务器已断开"));
                }
                return;
            }
            //根据更新频率分组
            var dataItemGroups = from a in opcDataItems
                                 group a by a.UpdateRate into g
                                 select new { UpdateRate = g.Key, DataItems = g };

            //循环每组订阅对象,查询是否实际订阅,有则更新,没有则新建
            foreach (var dataItemGroup in dataItemGroups)
            {
                Opc.Da.Subscription thisSubscription = this.opcServer.Subscriptions.Cast <Opc.Da.Subscription>().FirstOrDefault(a => a.State.UpdateRate == dataItemGroup.UpdateRate);
                //未找到已经订阅的组,那么新建组并添加订阅项
                if (Equals(null, thisSubscription))
                {
                    if (!IsConnected)
                    {
                        if (!Equals(null, OnLogHappened))
                        {
                            OnLogHappened(this, new OpcLogEventArgs("Opc服务器已断开"));
                        }
                        return;
                    }
                    #region 增加订阅

                    //创建订阅组。订阅组状态的名称是更新频率
                    Opc.Da.Subscription newSubscription = this.opcServer.CreateSubscription
                                                              (CreateSubscriptionState(dataItemGroup.UpdateRate.ToString(), dataItemGroup.UpdateRate))
                                                          as Opc.Da.Subscription;//创建组
                    //创建opc订阅项
                    var opcItems = ConvertItems(dataItemGroup.DataItems);
                    //添加订阅项
                    var results = newSubscription.AddItems(opcItems.ToArray());
                    newSubscription.DataChanged += ThisSubscription_DataChanged;
                    //订阅的结果通过事件通知给外部调用程序
                    foreach (var v in results)
                    {
                        if (!IsConnected)
                        {
                            if (!Equals(null, OnLogHappened))
                            {
                                OnLogHappened(this, new OpcLogEventArgs("Opc服务器已断开"));
                            }
                            return;
                        }
                        //订阅成功更新状态
                        if (v.ResultID == Opc.ResultID.S_OK)
                        {
                            OpcResult opcResult = OpcResult.Unknow;
                            Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                            OpcDataItems.FirstOrDefault(a => a.Name == v.ItemName).Quality = opcResult;
                        }
                        //未订阅成功,异常事件通知
                        else if (v.ResultID == Opc.ResultID.S_OK && !Equals(null, OnDataChanged))
                        {
                            OnDataChanged(this, new OpcDataEventArgs(OpcResult.DataItemRegistered,
                                                                     dataItemGroup.DataItems.FirstOrDefault(a => a.Name == v.ItemName)));
                        }
                        else if (v.ResultID != Opc.ResultID.S_OK && !Equals(null, OnErrorHappened))
                        {
                            OpcResult opcResult = OpcResult.Unknow;
                            Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                            this.OpcDataItems.FirstOrDefault(a => a.Name == v.ItemName).Quality = opcResult;
                            OnErrorHappened(this, new OpcErrorEventArgs(opcResult, "订阅数据项时发生错误" + v.ResultID.Name, null));
                        }
                    }//end foreach
                    #endregion
                }
                else//已经有订阅组,那么更新订阅项
                {
                    if (!IsConnected)
                    {
                        if (!Equals(null, OnLogHappened))
                        {
                            OnLogHappened(this, new OpcLogEventArgs("Opc服务器已断开"));
                        }
                        return;
                    }
                    #region 已经有订阅组,那么更新订阅项

                    //查询要新增加的点,
                    IList <OpcDataItem> newItems = new List <OpcDataItem>();
                    foreach (var v in dataItemGroup.DataItems)
                    {
                        if (!thisSubscription.Items.Any(a => a.ItemName == v.Name))
                        {
                            newItems.Add(v);
                        }
                    }
                    var opcItems = ConvertItems(newItems);
                    //添加订阅项
                    var addResults = thisSubscription.AddItems(opcItems.ToArray());

                    //订阅的结果通过事件通知给外部调用程序
                    foreach (var v in addResults)
                    {
                        if (!IsConnected)
                        {
                            if (!Equals(null, OnLogHappened))
                            {
                                OnLogHappened(this, new OpcLogEventArgs("Opc服务器已断开"));
                            }
                            return;
                        }
                        //订阅成功更新状态
                        if (v.ResultID == Opc.ResultID.S_OK)
                        {
                            OpcResult opcResult = OpcResult.Unknow;
                            Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                            OpcDataItems.FirstOrDefault(a => a.Name == v.ItemName).Quality = opcResult;
                        }
                        //未订阅成功,异常事件通知
                        else if (v.ResultID == Opc.ResultID.S_OK && !Equals(null, OnDataChanged))
                        {
                            OnDataChanged(this, new OpcDataEventArgs(OpcResult.DataItemRegistered,
                                                                     dataItemGroup.DataItems.FirstOrDefault(a => a.Name == v.ItemName)));
                        }
                        else if (v.ResultID != Opc.ResultID.S_OK && !Equals(null, OnErrorHappened))
                        {
                            OpcResult opcResult = OpcResult.Unknow;
                            Enum.TryParse <OpcResult>(v.ResultID.ToString(), out opcResult);
                            this.OpcDataItems.FirstOrDefault(a => a.Name == v.ItemName).Quality = opcResult;
                            OnErrorHappened(this, new OpcErrorEventArgs(opcResult, "订阅数据项时发生错误:" + v.ItemName + " 无效,OpcResult=" + v.ResultID.Name, null));
                        }
                    }//end foreach

                    //查询要删除的点,
                    IList <Opc.Da.Item> deleteItems = new List <Opc.Da.Item>();
                    foreach (var v in thisSubscription.Items)
                    {
                        if (!dataItemGroup.DataItems.Any(a => a.Name == v.ItemName))
                        {
                            deleteItems.Add(v);
                        }
                    }

                    //删除已经订阅点
                    var deleteResults = thisSubscription.RemoveItems(deleteItems.ToArray());
                    //订阅的结果通过事件通知给外部调用程序
                    foreach (var v in deleteResults)
                    {
                        if (!IsConnected)
                        {
                            if (!Equals(null, OnLogHappened))
                            {
                                OnLogHappened(this, new OpcLogEventArgs("Opc服务器已断开"));
                            }
                            return;
                        }
                        //未订阅成功,异常事件通知
                        if (v.ResultID == Opc.ResultID.S_OK && !Equals(null, OnDataChanged))
                        {
                            OpcDataItem tmp2 = new OpcDataItem(v.ItemName, thisSubscription.State.UpdateRate, "", "", OpcResult.DataItemUnregistered);
                            OnDataChanged(this, new OpcDataEventArgs(OpcResult.DataItemUnregistered, tmp2));
                        }
                        else if (v.ResultID != Opc.ResultID.S_OK && !Equals(null, OnErrorHappened))
                        {
                            OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "取消订阅数据项时发生错误" + v.ResultID.Name, null));
                        }
                    }//end foreach
                    //删除订阅项后没有item了,那么删除thisSubscription
                    if (thisSubscription.Items.Count() < 1)
                    {
                        thisSubscription.DataChanged -= ThisSubscription_DataChanged;
                        string name = thisSubscription.Name;
                        //this.opcServer.Subscriptions.Remove(thisSubscription);
                        this.opcServer.CancelSubscription(thisSubscription);
                        thisSubscription.Dispose();//
                        if (!Equals(null, OnLogHappened))
                        {
                            OnLogHappened(this, new OpcLogEventArgs("Subscription " + name + " 已经从订阅组中移除"));
                        }
                        name = null;
                    }
                    #endregion
                }
            }//end foreach (var dataItemGroup in dataItemGroups)
            //删除订阅项后没有item了,那么删除subscription
            foreach (var subscription in this.opcServer.Subscriptions.Cast <Opc.Da.Subscription>())
            {
                var isHave = dataItemGroups.Any(a => a.UpdateRate == subscription.State.UpdateRate);

                if (!isHave)
                {
                    subscription.DataChanged -= ThisSubscription_DataChanged;
                    string name = subscription.Name;
                    //his.opcServer.Subscriptions.Remove(thisSubscription);
                    this.opcServer.CancelSubscription(subscription);
                    subscription.Dispose();//
                    if (!Equals(null, OnLogHappened))
                    {
                        OnLogHappened(this, new OpcLogEventArgs("Subscription " + name + " 已经从订阅组中移除"));
                    }
                    name = null;
                }
            }
            if (!Equals(null, OnLogHappened))
            {
                OnLogHappened(this, new OpcLogEventArgs("OPC Subscriptions Count:" + this.opcServer.Subscriptions.Count + "."));
            }
            daemonTimer.Enabled = true;
            daemonTimer.Start();
        }
Beispiel #29
0
        /// <summary>
        /// OPC连接
        /// </summary>
        /// <param name="barcode"></param>
        public void OPC_connect()
        {
            #region 连接OPCSever
            //if (!OpcGroupClassm_server.IsConnected) { return; }
            //获取本地的IP地址
            var addr = "192.168.3.89";
            OpcServerName = addr + ".KEPware.KEPServerEx.V6";
            Opc.Server[] servers = OpcGroupClassm_discovery.GetAvailableServers(Specification.COM_DA_20, addr, null);//查询服务器
            if (servers != null)
            {
                foreach (Opc.Da.Server server in servers)
                {
                    //server即为需要连接的OPC数据存取服务器
                    if (String.Compare(server.Name, OpcServerName, true) == 0) //true表示忽略大小写
                    {
                        OpcGroupClassm_server = server;                        //建立连接
                        break;
                    }
                }
            }
            //连接服务器
            if (OpcGroupClassm_server != null)
            {
                OpcGroupClassm_server.Connect();                               //非空连接服务器
            }
            #endregion

            #region 往OPCSever中添加Group
            OpcGroupClassstate              = new Opc.Da.SubscriptionState();                                                    //组(订阅者)状态,相当于OPC规范中组的参数
            OpcGroupClassstate.Name         = "OpcGroupClasss";                                                                  //组名
            OpcGroupClassstate.ServerHandle = null;                                                                              //服务器给该组分配的句柄。
            OpcGroupClassstate.ClientHandle = Guid.NewGuid().ToString();                                                         //客户端给该组分配的句柄
            OpcGroupClassstate.Active       = true;                                                                              //激活该组
            OpcGroupClassstate.UpdateRate   = 100;                                                                               //刷新频率为1秒
            OpcGroupClassstate.Deadband     = 0;                                                                                 // 死区值,设为0时,服务器端该组内任何数据变化都通知组
            OpcGroupClassstate.Locale       = null;                                                                              //不设置地区值
            OpcGroupClasssubscription       = (Opc.Da.Subscription)OpcGroupClassm_server.CreateSubscription(OpcGroupClassstate); //添加组
                                                                                                                                 //添加监控地址
            #endregion

            #region  往Group添加 Items
            try
            {
                List <Item> items = new List <Item>();
                foreach (var adress in dicTest)
                {
                    var item = new Item()
                    {
                        ClientHandle = Guid.NewGuid().ToString(), //客户端给该数据项分配的句柄。
                        ItemName     = adress.Key                 //该数据项在服务器中的名字
                    };
                    items.Add(item);
                }
                OpcGroupClasssubscription.AddItems(items.ToArray());
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化监控地址失败:" + ex.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            OpcGroupClasssubscription.DataChanged += new DataChangedEventHandler(OnDataChange);
            //Thread.Sleep(1000);
            #endregion
        }