Пример #1
0
        private void Connect(string flow, string time)
        {
            try
            {
                this.server.Connect(this.serverId);

                RecordManager.DoSystemEventRecord(this, "Connected to CPU", RecordType.Event, true);

                this.group = this.server.AddGroup("Group1", true, 2000);

                this.OnConnect();

                this.Write(new HandleCode(1, flow), new HandleCode(2, time));
                this.connected = true;

                this.timer          = new System.Windows.Forms.Timer();
                this.timer.Interval = this.interval;
                this.timer.Tick    += this.OnDataTimer;
                this.timer.Start();
            }
            catch (Exception e)
            {
                RecordManager.DoSystemEventRecord(this, string.Format("Connect:{0}", e.Message), RecordType.Error);
            }
        }
Пример #2
0
        public void AddOPCItem(OpcGroup grp, string valueAddress, Guid guid)
        {
            if (grp == null)
            {
                return;
            }

            try
            {
                results = grp.AddItems(new [] { valueAddress }, new Guid[] { guid });

                for (int i = 0; i < results.Count(); i++)
                {
                    //ValList[i].OPCItemResult = results[i];

                    if (results[i].ResultID.Failed())
                    {
                        string message = "Failed to add item \'" + results[i].ItemName + "\'" + " Error: " + results[i].ResultID.Name;
                        Console.WriteLine(message);
                        //RadWindow.Alert(message);
                    }
                    else
                    {
                        //success
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Пример #3
0
        public override void Stop()
        {
            try
            {
                this.timer.Stop();
                this.timer = null;

                // 确保所有的Read线程都已经结束
                //System.Threading.Thread.Sleep(2 * this.interval);

                if (this.group != null)
                {
                    this.group.Remove(false);
                    this.group = null;
                }
                if (this.server != null)
                {
                    this.server.Disconnect();
                    this.server = null;
                }
                RecordManager.DoSystemEventRecord(this, string.Format("Close Device"), RecordType.Event, true);
            }
            catch (Exception e)
            {
                RecordManager.DoSystemEventRecord(this, string.Format("Close Device:{0}", e.Message), RecordType.Error);
            }
        }
Пример #4
0
        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);
        }
Пример #5
0
        public OpcGroup AddGroup(string groupName)
        {
            OpcGroup _group = new OpcGroup {
                IsActive = true, Name = groupName, UpdateRate = new TimeSpan(0, 0, 0, 0, _options.DefaultMonitorInterval)
            };
            var sub = new Subscription
            {
                PublishingInterval = _options.DefaultMonitorInterval,
                PublishingEnabled  = true,
                LifetimeCount      = _options.SubscriptionLifetimeCount,
                KeepAliveCount     = _options.SubscriptionKeepAliveCount,
                DisplayName        = groupName,
                Priority           = byte.MaxValue
            };

            _groups.Add(groupName, _group);

            dic.Add(groupName, sub);
            _session.AddSubscription(sub);



            new Thread(new ParameterizedThreadStart(GetChange)).Start(sub);
            return(_group);
        }
Пример #6
0
        // event handler: called if any item in group has changed values
        protected void theGrp_DataChange(object sender, DataChangeEventArgs e)
        {
            Trace.WriteLine("theGrp_DataChange  id=" + e.transactionID.ToString() + " me=0x" + e.masterError.ToString("X"));

            foreach (OPCItemState s in e.sts)
            {
                if (s.HandleClient != itmHandleClient)                  // only one client handle
                {
                    continue;
                }

                Trace.WriteLine("  item error=0x" + s.Error.ToString("X"));

                if (HRESULTS.Succeeded(s.Error))
                {
                    Trace.WriteLine("  val=" + s.DataValue.ToString());

                    txtItemValue.Text  = s.DataValue.ToString();                                // update screen
                    txtItemQual.Text   = OpcGroup.QualityToString(s.Quality);
                    txtItemTimeSt.Text = DateTime.FromFileTime(s.TimeStamp).ToString();
                }
                else
                {
                    txtItemValue.Text  = "ERROR 0x" + s.Error.ToString("X");
                    txtItemQual.Text   = "error";
                    txtItemTimeSt.Text = "error";
                }
            }
        }
        public ServerController(ISoftwareController softwareController,
                                AbstractViewFactory factory,
                                string machineName,
                                string serverId)
        {
            _softwareController = softwareController;

            _serverView = factory.CreateServerView(this, serverId);

            if (_serverView is ServerTabUserControl serverTabUserControl)
            {
                serverTabUserControl.OnUpdateRate += (sender, args) =>
                {
                    Console.WriteLine(@"The new update rage is {0} millisecond", args.StateUpdateRate);
                    _group.UpdateRate = args.StateUpdateRate;
                }
            }
            ;

            _serverModel = new ServerModel();
            _serverModel.ModelChanged += _serverView.ServerModelChange;


            _machineName = machineName;
            _serverId    = serverId;

            _itemAccessMutex = new Mutex();
            _server          = null;
            _group           = null;
        }
Пример #8
0
        /// <summary>
        /// Get current OPC Group.
        /// </summary>
        /// <returns></returns>
        private OpcGroup GetOPCGrp()
        {
            OpcGroup ret = null;

            lock (m_opcDataDicObj)
            {
                ret = m_OPCGroup;
            }
            return(ret);
        }
Пример #9
0
        /// <summary>
        /// 同步读
        /// </summary>
        /// <param name="dataAddress"></param>
        /// <returns></returns>
        public OperateResult <string> SyncReadData(string dataAddress)
        {
            #region 检验

            if (string.IsNullOrEmpty(dataAddress))
            {
                return(new OperateResult <string>("传入的参数都不能为空"));
            }

            if (_opcServer == null)
            {
                return(new OperateResult <string>("OPCServer未能正确初始化!"));
            }

            if (!_opcServer.IsConnected)
            {
                return(new OperateResult <string>("OPCServer连接错误!"));
            }

            #endregion

            string groupName = "AsyncWriteData";

            OpcGroup group = _opcServer.FindGroupByName(groupName);
            if (group != null)
            {
                _opcServer.RemoveGroup(group);
            }
            group = _opcServer.AddGroup(groupName, 1, false);  //1.添加组

            IRequest request;

            #region 添加Item及写入Item

            if ((dataAddress.Contains(',')) && (OPCServerName == _RSLinxOPC)) //RSLinx 数组的写入
            {
                //地址前缀,类型,起始位置,长度
            }
            else  //正常类型
            {
                Guid[]       handel      = new[] { Guid.NewGuid() };
                ItemResult[] itemResults = group.AddItems(new[] { dataAddress }, handel);  //2.添加Items

                object[] objhandel      = new object[] { handel[0] };
                object   _requestHandle = Guid.NewGuid().ToString("N");
                //group.(objhandel, _requestHandle, )
            }

            #endregion

            return(OperateResult.CreateSuccessResult("测试"));   //没有获取到结果++++++++++++++++++++++++++
        }
Пример #10
0
        public void UAGroup()
        {
            OpcClient client = new OpcClient(new Uri("opc.tcp://127.0.0.1:26543/Workstation.RobotServer"));

            if (client.Connect == OpcStatus.Connected)
            {
                string   msg;
                OpcGroup group = client.AddGroup("Test");
                client.AddItems("Test", new string[] { "Robot1.Axis1", "Robot1.Axis2" }, out msg);
                group.DataChange += Group_DataChange;
                Console.WriteLine(group);
            }
        }
Пример #11
0
        private bool CreateGroup()
        {
            try
            {
                // add our only working group
                _theGrp = _theSrv.AddGroup("OPCdotNET-Group", true, 500);

                //При создании группы тут читаем данные по всем тегам с сервера.
                OPCItemDef[] i = new OPCItemDef[12];
                i[0]  = new OPCItemDef();
                i[1]  = new OPCItemDef();
                i[2]  = new OPCItemDef();
                i[3]  = new OPCItemDef();
                i[4]  = new OPCItemDef();
                i[5]  = new OPCItemDef();
                i[6]  = new OPCItemDef();
                i[7]  = new OPCItemDef();
                i[8]  = new OPCItemDef();
                i[9]  = new OPCItemDef();
                i[10] = new OPCItemDef();
                i[11] = new OPCItemDef();


                i[0].ItemID  = OpcConsts.DispPress;
                i[1].ItemID  = OpcConsts.DlinaSopr;
                i[2].ItemID  = OpcConsts.Bits;
                i[3].ItemID  = OpcConsts.PosadkaKol;
                i[4].ItemID  = OpcConsts.SpeedPress;
                i[5].ItemID  = OpcConsts.Instrument;
                i[6].ItemID  = OpcConsts.BlinL;
                i[7].ItemID  = OpcConsts.BlinR;
                i[8].ItemID  = OpcConsts.DispPress1;
                i[9].ItemID  = OpcConsts.DispPress2;
                i[10].ItemID = OpcConsts.DispPress3;
                i[11].ItemID = OpcConsts.ShowGraph;


                OPCItemResult[] resI = new OPCItemResult[4];
                _theGrp.AddItems(i, out resI);

                // add event handler for data changes
                _theGrp.DataChanged    += theGrp_DataChange;
                _theGrp.WriteCompleted += theGrp_WriteComplete;
            }
            catch (COMException e)
            {
                throw e;
            }
            return(true);
        }
        public void CreateGroup(string groupName)
        {
            try
            {
                _group              = _server.AddGroup(groupName, true, _serverView.GetUpdateRate());
                _group.DataChanged += Group_DataChange;
            }
            catch (Exception ex)
            {
                Disconnect();

                throw ex;
            }
        }
Пример #13
0
        public void TestFixtureSetUpMe()
        {
            OPCServerComClass opcServerComObj = new OPCServerComClass();
            IOPCServer        opcServerinter  = (IOPCServer)opcServerComObj;

            group = new OpcGroup(ref opcServerinter, false, "Grp1", true, 500);
            string currentTestMethod = Dottest.Framework.Stubs.CurrentTestMethod.Name;

            if (currentTestMethod.Equals("TestErr_internalAdd02") ||
                currentTestMethod.Equals("TestErr_internalAdd01"))
            {
                return;
            }
            group.internalAdd(null, null, 0);
        }
Пример #14
0
 /// <summary>
 /// Initializes the object with a subscription and a unique id.
 /// </summary>
 public OpcRequest(
     OpcGroup group,
     object clientHandle,
     int filters,
     int requestID,
     Delegate callback)
     :
     base(group, clientHandle)
 {
     Filters        = filters;
     RequestID      = requestID;
     Callback       = callback;
     CancelID       = 0;
     InitialResults = null;
 }
Пример #15
0
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //theGrp.RemoveItems(handlesSrv, out aE);
            if (theGrp != null)
            {
                theGrp.Remove(false);
                theTargGrp.Remove(false);
                theSrv.Disconnect();
                theGrp     = null;
                theTargGrp = null;
                theSrv     = null;
            }

            stopReceive = true;
            connect.Abort();
            Process.GetCurrentProcess().Kill();
        }
Пример #16
0
        public bool connectServer()
        {
            try
            {
                theSrv = new OpcServer();
                theSrv.Connect(ServerProgID);

                TheGrp = theSrv.AddGroup("S7_200_01", false, 900);
                TheGrp.SetEnable(true);
                TheGrp.Active = true;
                return(true);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show("连接服务器出错:" + e.ToString());
                return(false);
            }
        }
Пример #17
0
        public bool CreateGroup()
        {
            try
            {
                // add our only working group
                theGrp = theSrv.AddGroup("OPCdotNET-Group", true, 500);

                // add event handler for data changes
                theGrp.DataChanged    += new DataChangeEventHandler(this.theGrp_DataChange);
                theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete);
            }
            catch (COMException)
            {
                MessageBox.Show(this, "create group error!", "Exception", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return(false);
            }
            return(true);
        }
Пример #18
0
        private bool CreateGroup()
        {
            try
            {
                // add our only working group
                _theGrp = _theSrv.AddGroup("OPCdotNET-Group", true, 500);

                //При создании группы тут читаем данные по всем тегам с сервера.
                //OPCItemDef[] i = new OPCItemDef[1];
                //i[0] = new OPCItemDef();
                //i[1] = new OPCItemDef();
                //i[2] = new OPCItemDef();
                //i[3] = new OPCItemDef();
                //i[4] = new OPCItemDef();
                //i[5] = new OPCItemDef();
                //i[6] = new OPCItemDef();
                //i[7] = new OPCItemDef();
                ////i[8] = new OPCItemDef();


                //i[0].ItemID = OpcConsts.Position;
                //i[1].ItemID = OpcConsts.PositionSP;
                //i[2].ItemID = OpcConsts.Speed;
                //i[3].ItemID = OpcConsts.SpeedSP;
                //i[4].ItemID = OpcConsts.Power;
                //i[5].ItemID = OpcConsts.PowerSP;
                //i[6].ItemID = OpcConsts.Temperature;
                //i[7].ItemID = OpcConsts.Run;



                //OPCItemResult[] resI = new OPCItemResult[1];
                //_theGrp.AddItems(i, out resI);

                // add event handler for data changes
                _theGrp.DataChanged    += theGrp_DataChange;
                _theGrp.WriteCompleted += theGrp_WriteComplete;
            }
            catch (COMException e)
            {
                throw e;
            }
            return(true);
        }
Пример #19
0
 private void cmdRemGroup_Click(object sender, EventArgs e)
 {
     if (theGroup != null)
     {
         int[] aE = new int[2];
         try
         {
             theGroup.DataChanged    -= new DataChangeEventHandler(TheGrp_DataChanged);
             theGroup.ReadCompleted  -= new ReadCompleteEventHandler(TheGrp_ReadCompleted);
             theGroup.WriteCompleted -= new WriteCompleteEventHandler(TheGrp_WriteCompleted);
             theGroup.Remove(false);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         theGroup = null;
     }
 }
Пример #20
0
 private void cmdAddGroup_Click(object sender, EventArgs e)
 {
     theGroup = theServer.AddGroup(txtGroup.Text, false, 900);
     if (CheckGroupActive.Checked)
     {
         theGroup.SetEnable(true);
         theGroup.Active = true;
     }
     else
     {
         theGroup.SetEnable(true);
         theGroup.Active = false;
     }
     theGroup.DataChanged    += new DataChangeEventHandler(TheGrp_DataChanged);
     theGroup.ReadCompleted  += new ReadCompleteEventHandler(TheGrp_ReadCompleted);
     theGroup.WriteCompleted += new WriteCompleteEventHandler(TheGrp_WriteCompleted);
     cmdAddGroup.Enabled      = false;
     cmdDisconnect.Enabled    = false;
     cmdRemGroup.Enabled      = true;
     cmdAddItem.Enabled       = true;
 }
Пример #21
0
        /// <summary>
        /// Release OPC resource
        /// </summary>
        /// <returns></returns>
        public void ReleaseOPC()
        {
            //release the OPC Group first then OPCServer
            lock (m_opcDataDicObj)
            {
                if (m_OPCGroup != null)
                {
                    m_OPCGroup.DataChanged -= new DataChangeEventHandler(this.OPCGrp_DataChange);
                    m_OPCGroup.Remove(false);
                    m_OPCGroup = null;
                }

                if (m_OPCServer != null)
                {
                    m_OPCServer.ShutdownRequested -= new ShutdownRequestEventHandler(this.OPCSrv_ServerShutDown);
                    m_OPCServer.Disconnect();
                    m_OPCServer = null;
                }
                m_opcSrvConnectFlag = false;
            }
        }
Пример #22
0
        private PLCCommand()
        {
            try
            {
                _opcSrv.Connect(StrSrvName);
                for (int i = 0; i < _arrGrps.Length; i++)
                {
                    string   strGrp = _arrGrps[i];
                    OpcGroup grp    = _opcSrv.AddGroup(strGrp, true, 9600);
                    grp.UpdateRate      = 100;
                    grp.Active          = true;
                    grp.PercentDeadband = 0;

                    _opcGrpsDic.Add(strGrp, grp);

                    string[] arrCurrentItems = _arrItems[i].Split(',');

                    OPCItemDef[]    opcItems   = new OPCItemDef[arrCurrentItems.Length];
                    OPCItemResult[] opcResults = new OPCItemResult[arrCurrentItems.Length];
                    for (int j = 0; j < arrCurrentItems.Length; j++)
                    {
                        string     strItemName = $"{StrItemId}.{strGrp}.{arrCurrentItems[j]}";
                        OPCItemDef item        = new OPCItemDef(strItemName, true, opcResults.Length, System.Runtime.InteropServices.VarEnum.VT_BOOL);
                        opcItems[j] = item;
                    }
                    Dictionary <string, OPCItemResult> oDic = new Dictionary <string, OPCItemResult>();
                    grp.AddItems(opcItems, out opcResults);

                    for (int k = 0; k < opcResults.Length; k++)
                    {
                        oDic.Add(arrCurrentItems[k], opcResults[k]);
                    }
                    _opcResultsDic.Add(strGrp, oDic);
                }
            }
            catch (Exception ee)
            {
                LogImpl.Debug("错误" + ee.ToString());
            }
        }
Пример #23
0
        private string AddMyRefreshGroup1(OpcServer OpcSrv)
        {
            float deadBand = 90.0F;

            try
            {      // create group with 2 sec update rate
                oGrp = OpcSrv.AddGroup("Line1", true, UpdateRate, ref deadBand, 0, 0);
            }
            catch
            {
                DBLogging.InsertLogs("Exception: AddMyRefreshGroup1", false, "Group could not be added", _connStr);
                return("Group could not be added");
            }

            oGrp.DataChanged += new DataChangeEventHandler(DataChangedHandler);
            oGrp.AdviseIOPCDataCallback();


            //client handle as item index
            items1[0] = new OPCItemDef(TagLPG_Bay01_RFID_Puched, true, 0, VarEnum.VT_BOOL);
            items1[1] = new OPCItemDef(TagLPG_WB_RFIDPunched, true, 1, VarEnum.VT_BOOL);
            items1[2] = new OPCItemDef(TagLPG_Bay01_LPGBatchComplete, true, 2, VarEnum.VT_BOOL);

            int rtc;

            rtc = oGrp.AddItems(items1, out addRslt1);

            if (HRESULTS.Failed(rtc))
            {
                return("Error at AddItem");
            }
            for (int i = 0; i < addRslt1.Length; ++i)
            {
                ItemValues1[i] = new OPCItemState();
            }

            return("");
        }
Пример #24
0
 private void cmdExit_Click(object sender, EventArgs e)
 {
     int[] aE = new int[2];
     if (ItemDefs[0] != null || ItemDefs[1] != null)
     {
         if (theGroup != null)
         {
             theGroup.RemoveItems(HandlesServer, out aE);
         }
     }
     if (theGroup != null)
     {
         try
         {
             theGroup.DataChanged    -= new DataChangeEventHandler(TheGrp_DataChanged);
             theGroup.ReadCompleted  -= new ReadCompleteEventHandler(TheGrp_ReadCompleted);
             theGroup.WriteCompleted -= new WriteCompleteEventHandler(TheGrp_WriteCompleted);
             theGroup.Remove(false);
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
         theGroup = null;
     }
     if (theServer != null)
     {
         try
         {
             theServer.Disconnect();
         }
         catch (Exception ex)
         {
             MessageBox.Show(ex.Message);
         }
     }
     this.Close();
 }
Пример #25
0
        private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!opc_connected)
            {
                return;
            }

            if (theGrp != null)
            {
                theGrp.DataChanged    -= new DataChangeEventHandler(this.theGrp_DataChange);
                theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete);
                RemoveItem();
                theGrp.Remove(false);
                theGrp = null;
            }

            if (theSrv != null)
            {
                theSrv.Disconnect();                                    // should clean up
                theSrv = null;
            }

            opc_connected = false;
        }
Пример #26
0
        private PLCCommand2()
        {
            try
            {
                opcSrv.Connect(strSrvName);
                for (int i = 0; i < arrGrps.Length; i++)
                {
                    string   strGrp = arrGrps[i];
                    OpcGroup grp    = opcSrv.AddGroup(strGrp, true, 9600);
                    opcGrpsDic.Add(strGrp, grp);

                    string[] arrCurrentItems = arrItems[i].Split(',');

                    OPCItemDef[]    opcItems   = new OPCItemDef[arrCurrentItems.Length];
                    OPCItemResult[] opcResults = new OPCItemResult[arrCurrentItems.Length];
                    for (int j = 0; j < arrCurrentItems.Length; j++)
                    {
                        string     strItemName = string.Format("{0}.{1}.{2}", strItemID, strGrp, arrCurrentItems[j]);
                        OPCItemDef item        = new OPCItemDef(strItemName, true, opcResults.Length, System.Runtime.InteropServices.VarEnum.VT_BOOL);
                        opcItems[j] = item;
                    }
                    Dictionary <string, OPCItemResult> oDic = new Dictionary <string, OPCItemResult>();
                    grp.AddItems(opcItems, out opcResults);

                    for (int k = 0; k < opcResults.Length; k++)
                    {
                        oDic.Add(arrCurrentItems[k], opcResults[k]);
                    }
                    opcResultsDic.Add(strGrp, oDic);
                }
            }
            catch (Exception ee)
            {
                LogImpl.Error("plc初始化:" + ee.StackTrace);
            }
        }
Пример #27
0
        public void Close()
        {
            if (!OpcConnected)
            {
                return;
            }

            if (_theGrp != null)
            {
                _theGrp.DataChanged    -= new DataChangeEventHandler(this.theGrp_DataChange);
                _theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete);
                RemoveItem();
                _theGrp.Remove(false);
                _theGrp = null;
            }

            if (_theSrv != null)
            {
                _theSrv.Disconnect();                           // should clean up
                _theSrv = null;
            }

            OpcConnected = false;
        }
Пример #28
0
        public void Work()
        {
            /*	try						// disabled for debugging
             *      {	*/

            theSrv = new OpcServer();
            theSrv.Connect(serverProgID);
            Thread.Sleep(500);                                          // we are faster then some servers!

            // add our only working group
            theGrp = theSrv.AddGroup("OPCCSharp-Group", false, 900);

            // add two items and save server handles
            itemDefs[0] = new OPCItemDef(itemA, true, 1234, VarEnum.VT_EMPTY);
            itemDefs[1] = new OPCItemDef(itemB, true, 5678, VarEnum.VT_EMPTY);
            OPCItemResult[] rItm;
            theGrp.AddItems(itemDefs, out rItm);
            if (rItm == null)
            {
                return;
            }
            if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error))
            {
                Console.WriteLine("OPC Tester: AddItems - some failed"); theGrp.Remove(true); theSrv.Disconnect(); return;
            }
            ;

            handlesSrv[0] = rItm[0].HandleServer;
            handlesSrv[1] = rItm[1].HandleServer;

            // asynch read our two items
            theGrp.SetEnable(true);
            theGrp.Active         = true;
            theGrp.DataChanged   += new DataChangeEventHandler(this.theGrp_DataChange);
            theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete);
            int CancelID;

            int[] aE;
            theGrp.Read(handlesSrv, 55667788, out CancelID, out aE);

            // some delay for asynch read-complete callback (simplification)
            Thread.Sleep(500);


            // asynch write
            object[] itemValues = new object[2];
            itemValues[0]          = (int)1111111;
            itemValues[1]          = (double)2222.2222;
            theGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete);
            theGrp.Write(handlesSrv, itemValues, 99887766, out CancelID, out aE);

            // some delay for asynch write-complete callback (simplification)
            Thread.Sleep(500);


            // disconnect and close
            Console.WriteLine("************************************** hit  to close...");
            Console.ReadLine();
            theGrp.DataChanged    -= new DataChangeEventHandler(this.theGrp_DataChange);
            theGrp.ReadCompleted  -= new ReadCompleteEventHandler(this.theGrp_ReadComplete);
            theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete);
            theGrp.RemoveItems(handlesSrv, out aE);
            theGrp.Remove(false);
            theSrv.Disconnect();
            theGrp = null;
            theSrv = null;


            /*	}
             * catch( Exception e )
             *      {
             *      Console.WriteLine( "EXCEPTION : OPC Tester " + e.ToString() );
             *      return;
             *      }	*/
        }
Пример #29
0
        static void Main(string[] args)
        {
            /*create array of readable Tags*/
            var Tags = new List <OPCClientItem>();

            Tags.Add(new OPCClientItem()
            {
                Name        = ".test",
                ClientHanle = 1
            });

            OpcServer server = new OpcServer();

            try
            {
                int transactionID = new Random().Next(1024, 65535);
                int cancelID      = 0;
                int updateRate    = 1000;

                /*connect to the OPC Server and check it's state*/
                server.Connect("Matrikon.OPC.Simulation.1");
                var serverStatus = new SERVERSTATUS();
                server.GetStatus(out serverStatus);
                if (serverStatus.eServerState == OPCSERVERSTATE.OPC_STATUS_RUNNING)
                {
                    /*create group of items*/
                    OpcGroup group = server.AddGroup("Group1", true, updateRate);
                    group.ReadCompleted += group_ReadCompleted;
                    List <OPCItemDef> items = new List <OPCItemDef>();
                    Tags.ToList()
                    .ForEach(x => items.Add(new OPCItemDef(x.Name, true, x.ClientHanle, VarEnum.VT_EMPTY)));

                    /* add items and collect their attributes*/
                    OPCItemResult[] itemAddResults = null;
                    group.AddItems(items.ToArray(), out itemAddResults);
                    for (int i = 0; i < itemAddResults.Length; i++)
                    {
                        OPCItemResult itemResult = itemAddResults[i];
                        OPCClientItem tag        = Tags[i];
                        tag.ServerHandle = itemResult.HandleServer;
                        tag.AccessRight  = (itemResult.AccessRights == OPCACCESSRIGHTS.OPC_READABLE) ? OPCClientItem.EAccessRight.ReadOnly : OPCClientItem.EAccessRight.ReadAndWrite;
                    }
                    ;

                    /*Refresh items in group*/
                    // group.Refresh2(OPCDATASOURCE.OPC_DS_DEVICE, transactionID, out cancelID);

                    /*Async read data for the group items*/
                    int[] serverHandles = new int[Tags.Count];
                    for (int i = 0; i < Tags.Count; i++)
                    {
                        serverHandles[i] = Tags[i].ServerHandle;
                    }
                    ;
                    OPCItemState[] itemsStateResult = null;
                    /*sync read*/
                    group.Read(OPCDATASOURCE.OPC_DS_DEVICE, serverHandles, out itemsStateResult);
                    Console.WriteLine("Sync read:");
                    for (int i = 0; i < itemsStateResult.Length; i++)
                    {
                        OPCItemState itemResult = itemsStateResult[i];
                        Console.WriteLine(" -> item:{0}; value:{1}; timestamp{2}; qualituy:{3}", Tags[i].Name, itemResult.DataValue.ToString(), itemResult.TimeStamp, itemResult.Quality);
                    }
                    ;

                    /*sync write*/
                    object[] values       = new object[Tags.Count];
                    int[]    resultErrors = new int[Tags.Count];
                    values[0] = (object)256;
                    group.Write(serverHandles, values, out resultErrors);

                    /*async read*/
                    group.Read(serverHandles, transactionID, out cancelID, out resultErrors);

                    /*wait for a while befor remove group to process async event*/
                    System.Threading.Thread.Sleep(3000);

                    /*the group must be removed !!! */
                    group.Remove(true);
                }
                ;
            }
            finally
            {
                server.Disconnect();
                server = null;
                GC.Collect();
            };
            Console.ReadKey();
        }
Пример #30
0
        public void Work()
        {
            /*	try						// disabled for debugging
             *  {	*/

            theSrv = new OpcServer();
            theSrv.Connect(serverProgID);
            Thread.Sleep(500);              // we are faster then some servers!

            // add our only working group
            theGrp = theSrv.AddGroup("OPCCSharp-Group", false, timeref);


            if (sendtags > tags.Length)
            {
                sendtags = tags.Length;
            }

            var itemDefs = new OPCItemDef[tags.Length];

            for (var i = 0; i < tags.Length; i++)
            {
                itemDefs[i] = new OPCItemDef(tags[i], true, i, VarEnum.VT_EMPTY);
            }

            OPCItemResult[] rItm;
            theGrp.AddItems(itemDefs, out rItm);
            if (rItm == null)
            {
                return;
            }
            if (HRESULTS.Failed(rItm[0].Error) || HRESULTS.Failed(rItm[1].Error))
            {
                Console.WriteLine("OPC Tester: AddItems - some failed"); theGrp.Remove(true); theSrv.Disconnect(); return;
            }
            ;

            var handlesSrv = new int[itemDefs.Length];

            for (var i = 0; i < itemDefs.Length; i++)
            {
                handlesSrv[i] = rItm[i].HandleServer;
            }

            currentValues = new Single[itemDefs.Length];

            // asynch read our two items
            theGrp.SetEnable(true);
            theGrp.Active         = true;
            theGrp.DataChanged   += new DataChangeEventHandler(this.theGrp_DataChange);
            theGrp.ReadCompleted += new ReadCompleteEventHandler(this.theGrp_ReadComplete);

            int CancelID;

            int[] aE;
            theGrp.Read(handlesSrv, 55667788, out CancelID, out aE);

            // some delay for asynch read-complete callback (simplification)
            Thread.Sleep(500);

            while (webSend == "yes")
            {
                HttpListenerContext  context  = listener.GetContext();
                HttpListenerRequest  request  = context.Request;
                HttpListenerResponse response = context.Response;
                context.Response.AddHeader("Access-Control-Allow-Origin", "*");


                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseStringG);
                // Get a response stream and write the response to it.
                response.ContentLength64 = buffer.Length;
                System.IO.Stream output = response.OutputStream;
                output.Write(buffer, 0, buffer.Length);
                // You must close the output stream.
                output.Close();
            }
            // disconnect and close
            Console.WriteLine("************************************** hit <return> to close...");
            Console.ReadLine();
            theGrp.ReadCompleted -= new ReadCompleteEventHandler(this.theGrp_ReadComplete);
            theGrp.RemoveItems(handlesSrv, out aE);
            theGrp.Remove(false);
            theSrv.Disconnect();
            theGrp = null;
            theSrv = null;


            /*	}
             * catch( Exception e )
             *  {
             *  Console.WriteLine( "EXCEPTION : OPC Tester " + e.ToString() );
             *  return;
             *  }	*/
        }