Пример #1
0
        public void TestErr_AddGroup01()
        {
            //testing --
            OpcServer opcServer         = new OpcServer();
            Accessor  opcServerAccessor = ReflectionAccessor.Wrap(opcServer);

            //Test Procedure Call
            opcServer.AddGroup("GrpName", true, 500);
            //Post Condition Check
        }
Пример #2
0
        public void TestAddGroup01()
        {
            //testing --
            OpcServer opcServer         = new OpcServer();
            Accessor  opcServerAccessor = ReflectionAccessor.Wrap(opcServer);

            opcServerAccessor.SetField("ifServer", new OPCServerComClass());
            //Test Procedure Call
            opcServer.AddGroup("GrpName", true, 500);
            //Post Condition Check
        }
Пример #3
0
        /// <summary>
        /// Connect to opc server
        /// </summary>
        /// <param name="serverName"></param>
        /// <param name="requestedUpdateRate">In case of use of LinkMaster and Kepserver simulation, this value should match the LinkMaster value</param>
        /// <returns></returns>
        public bool Connect(string serverName, int requestedUpdateRate = 250)
        {
            srv = new OpcServer();
            int rtc = srv.Connect(serverName);

            if (HRESULTS.Failed(rtc))
            {
                srv.GetErrorString(rtc, 0);//MBR added 0 return Srv.GetErrorString( rtc);
                return(false);
            }

            float deadBand = 0.0F;

            //Get data start
            try
            {
                OPCGetData.OPCReadGroup = srv.AddGroup("Group1GetData", true, requestedUpdateRate, ref deadBand, 0, 0);
            }
            catch (Exception)
            {
                srv.Disconnect();
                return(false);
                //return ex.Message;
            }
            //Get data end

            //Set data start
            try
            {
                OPCSetData.OPCWriteGroup = srv.AddGroup("Group1SetData", true, requestedUpdateRate, ref deadBand, 0, 0);
            }
            catch (Exception)
            {
                srv.Disconnect();
                return(false);//return ex.Message;
            }

            return(true); //ok
        }
        public void CreateGroup(string groupName)
        {
            try
            {
                _group              = _server.AddGroup(groupName, true, _serverView.GetUpdateRate());
                _group.DataChanged += Group_DataChange;
            }
            catch (Exception ex)
            {
                Disconnect();

                throw ex;
            }
        }
Пример #5
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);
        }
Пример #6
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);
            }
        }
Пример #7
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);
        }
Пример #8
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);
        }
Пример #9
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;
 }
Пример #10
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());
            }
        }
Пример #11
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("");
        }
Пример #12
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);
            }
        }
Пример #13
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;
             *  }	*/
        }
Пример #14
0
        static void Main(string[] args)
        {
            string progID = args.Length > 0 ? args[0] : "Kepware.KEPServerEX.V5";

            OpcServer opcServer = new OpcServer();

            opcServer.Connect(progID);
            System.Threading.Thread.Sleep(500); // we are faster than some servers!

            OpcGroup opcGroup = opcServer.AddGroup("SampleGroup", false, 900);

            List <string> itemNames = new List <string>();

            if (args.Length > 1)
            {
                for (int i = 1; i < args.Length; i++)
                {
                    itemNames.Add(args[i]);
                }
            }
            else
            {
                itemNames.Add("Simulation Examples.Functions.Ramp1");
                itemNames.Add("Simulation Examples.Functions.Random1");
            }

            OpcItemDefinition[] opcItemDefs = new OpcItemDefinition[itemNames.Count];
            for (int i = 0; i < opcItemDefs.Length; i++)
            {
                opcItemDefs[i] = new OpcItemDefinition(itemNames[i], true, i, VarEnum.VT_EMPTY);
            }

            opcGroup.AddItems(opcItemDefs, out OpcItemResult[] opcItemResult);
            if (opcItemResult == null)
            {
                Console.WriteLine("Error add items - null value returned");
                return;
            }

            int[] serverHandles = new int[opcItemResult.Length];
            for (int i = 0; i < opcItemResult.Length; i++)
            {
                if (HRESULTS.Failed(opcItemResult[i].Error))
                {
                    Console.WriteLine("AddItems - failed {0}", itemNames[i]);
                    opcGroup.Remove(true);
                    opcServer.Disconnect();
                    return;
                }
                else
                {
                    serverHandles[i] = opcItemResult[i].HandleServer;
                }
            }

            opcGroup.DataChanged += OpcGroup_DataChanged;

            opcGroup.SetEnable(true);
            opcGroup.Active = true;

            Console.WriteLine("********** Press <Enter> to close **********");
            Console.ReadLine();

            opcGroup.DataChanged -= OpcGroup_DataChanged;
            opcGroup.Remove(true);
            opcServer.Disconnect();
        }
Пример #15
0
        /// <summary>
        /// initialize OPC server and group
        /// </summary>
        /// <param name="serverName">OPC Server Name</param>
        /// <param name="groupName">OPC Group name under the OPC server.
        /// Here groupName is trendViewer Process ID in string</param>
        ///
        public void InitializeServer(string serverName, string groupName)
        {
            string Function_Name = "InitializeServer";

            LogHelper.Trace(CLASS_NAME, Function_Name, "Function_Entered");
            lock (m_opcDataDicObj)
            {
                try
                {
                    m_OPCSrvName   = serverName;
                    m_OPCGroupName = groupName;

                    //Fix - Remove opcGroup and Disconnect server to avoid GC Fianlizer thread call these methods
                    try
                    {
                        if (m_OPCGroup != null)
                        {
                            m_OPCGroup.Remove(false);
                            m_OPCGroup = null;
                        }

                        if (m_OPCServer != null)
                        {
                            m_OPCServer.Disconnect();
                            m_OPCServer = null;
                        }
                    }
                    catch (Exception localException)
                    {
                        LogHelper.Error(CLASS_NAME, Function_Name, localException);
                    }

                    m_OPCServer = new OpcServer();

                    LogHelper.Trace(CLASS_NAME, Function_Name, "Before Connect");
                    m_OPCServer.Connect(serverName);
                    LogHelper.Trace(CLASS_NAME, Function_Name, "After Connect");

                    Thread.Sleep(200);
                    m_OPCServer.SetClientName("DirectOPC " + groupName + serverName);   // set my client name (exe+process no)

                    SERVERSTATUS sts;
                    m_OPCServer.GetStatus(out sts);
                    LogHelper.Info(CLASS_NAME, Function_Name, serverName + ": " + DateTime.FromFileTime(sts.ftStartTime).ToString());
                    LogHelper.Info(CLASS_NAME, Function_Name, serverName + ": " + sts.eServerState.ToString());

                    // add event handler for server shutdown
                    m_OPCServer.ShutdownRequested += new ShutdownRequestEventHandler(this.OPCSrv_ServerShutDown);

                    //Setup opc group
                    m_OPCGroup              = m_OPCServer.AddGroup("MFTOPC-Group-" + serverName, true, UPDATEGROUPRATE);
                    m_OPCGroup.DataChanged += new DataChangeEventHandler(this.OPCGrp_DataChange);
                    m_opcSrvConnectFlag     = true;
                }
                catch (COMException localException)
                {
                    LogHelper.Error(CLASS_NAME, Function_Name, localException);
                    LogHelper.Info(CLASS_NAME, Function_Name, "Initialize of the OPC Server is not successful");
                }
                catch (Exception localException)
                {
                    LogHelper.Error(CLASS_NAME, Function_Name, localException);
                }
            }
            LogHelper.Trace(CLASS_NAME, Function_Name, "Function_Exited");
        }
Пример #16
0
        public void Work()
        {
            theSrv = new OpcServer();
            theSrv.Connect(serverProgID);
            Thread.Sleep(500);                          // we are faster then some servers!

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

            // add two items and save server handles
            itemDefs[0] = new OPCItemDef(itemA, true, 1, VarEnum.VT_EMPTY);
            itemDefs[1] = new OPCItemDef(itemB, true, 2, VarEnum.VT_EMPTY);


            //
            itemTarget[0] = new OPCItemDef(itemC, true, 1, 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))
            {
                AddTotextBox("OPC Tester: AddItems - some failed", textBox4);
                theGrp.Remove(true);
                theSrv.Disconnect();
                return;
            }
            ;

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

            OPCItemResult[] rItmTarg;
            theTargGrp.AddItems(itemTarget, out rItmTarg);

            if (rItmTarg == null)
            {
                return;
            }

            if (HRESULTS.Failed(rItmTarg[0].Error))
            {
                AddTotextBox("OPC Tester: AddItems - some failed", textBox4);
                theGrp.Remove(true);
                theSrv.Disconnect();
                return;
            }
            ;

            handlesTargetSrv[0] = rItmTarg[0].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
            theTargGrp.SetEnable(true);
            theTargGrp.Active = true;
            object[] itemValues = new object[1];
            itemValues[0] = (int)450;

            theTargGrp.WriteCompleted += new WriteCompleteEventHandler(this.theGrp_WriteComplete);
            theTargGrp.Write(handlesTargetSrv, itemValues, 99887766, out CancelID, out aE);

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

            theGrp.DataChanged    -= new DataChangeEventHandler(this.theGrp_DataChange);
            theGrp.ReadCompleted  -= new ReadCompleteEventHandler(this.theGrp_ReadComplete);
            theGrp.WriteCompleted -= new WriteCompleteEventHandler(this.theGrp_WriteComplete);
        }
Пример #17
0
        public int Connect(string Servername)
        {
            Debug.WriteLine("Try to connect to : " + Servername);
            if (OpcSrv != null)
            {
                Debug.WriteLine("Already connected");
                return(-1);
            }

            try
            {
                OpcSrv = new OpcServer();
                OpcSrv.Connect(Servername);
                Debug.WriteLine("Connected to the server");
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error connecting to the server");
                OpcSrv = null;
                return(-2);
            }

            /* add the items here */
            Items    = new OPCItemDef[2]; // onlyone node can be selected
            Items[0] = new OPCItemDef("PLC1:PLC_PRG.doorbell", true, 0, typeof(void));
            Items[1] = new OPCItemDef("PLC1:.DO_CARDS", true, 0, typeof(void));

            Debug.WriteLine("Creating OPC group");
            ItemHandles = null;
            errors      = null;
            int updRate      = 500;
            int clientHandle = 1;
            int rtc;

            OpcGrp = OpcSrv.AddGroup("", true, updRate, clientHandle, out rtc);

            if (HRESULTS.Failed(rtc))
            {
                Debug.WriteLine("Error creating group");
                return(rtc);
            }

            OPCItemResult[] rslt;
            rtc = OpcGrp.AddItems(Items, out rslt);
            if (HRESULTS.Failed(rtc))
            {
                Debug.WriteLine("Error adding items to the OPC group");
                return(rtc);
            }

            ItemHandles = new int[rslt.Length];
            errors      = new int[Items.Length];
            Debug.WriteLine("Items added");
            for (int i = 0; i < Items.Length; ++i)
            {
                ItemHandles[i] = rslt[i].HandleServer;
                errors[i]      = rslt[i].Error;
            }

            return(0);
        }
Пример #18
0
        public void PLCWrite()
        {
            try
            {
                theSrv = new OpcServer();
                theSrv.Connect(serverProgID);
                Thread.Sleep(500);                              // we are faster then some servers!

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

                //add two items and save server handles
                itemDefs[0] = new OPCItemDef(itemA, true, 1, VarEnum.VT_EMPTY);
                itemDefs[1] = new OPCItemDef(itemB, true, 2, 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))
                {
                    AddTotextBox("OPC Tester: AddItems - some failed", textBox4);
                    theGrp.Remove(true);
                    theSrv.Disconnect();
                    return;
                }
                ;

                if (handlesSrv[0] == 0)
                {
                    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;
                Random rnd           = new Random();
                int    transactionID = rnd.Next(1, 55667788);

                theGrp.Read(handlesSrv, transactionID, out CancelID, out aE);

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

                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);
            }
            catch (Exception e)
            {
                SetText("Unexpected Error:" + e.Message);
                return;
            }
        }
Пример #19
0
        public string ServerAccessOpc(string serverName)
        {
            OpcServer Srv = new OpcServer();
            int       rtc = Srv.Connect(serverName);

            if (HRESULTS.Failed(rtc))
            {
                try
                {
                    return(Srv.GetErrorString(rtc, 0));
                }
                catch {
                    return(rtc.ToString());
                }
            }

            OpcGroup oGrp;
            float    deadBand = 0.0F;

            try
            {
                oGrp = Srv.AddGroup("Grp1", true, 500, ref deadBand, 0, 0);
            }
            catch (Exception ex)
            {
                Srv.Disconnect();
                return(ex.Message);
            }
            OPCItemDef[] items = new OPCItemDef[1];
            items[0] = new OPCItemDef("Saw-toothed Waves.Int2",
                                      true, 0, VarEnum.VT_I2);
            OPCItemResult[] addRslt = new OPCItemResult[1];
            rtc = oGrp.AddItems(items, out addRslt);
            if (HRESULTS.Failed(rtc))
            {
                Srv.Disconnect();
                return("Error at AddItem");
            }
            int[] iHnd = new Int32[1];
            iHnd[0] = addRslt[0].HandleServer;
            OPCItemState[] rslt;
            rtc = oGrp.Read(OPCDATASOURCE.OPC_DS_CACHE,
                            iHnd, out rslt);
            string retVal;

            if (HRESULTS.Failed(rtc))
            {
                retVal = "Read error";
            }
            else
            if (HRESULTS.Failed(rslt[0].Error))
            {
                retVal = "Item Read error";
            }
            else
            {
                retVal = "data=" + rslt[0].DataValue.ToString();
            }
            oGrp.Remove(true);
            Srv.Disconnect();
            return(retVal);
        }
Пример #20
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();
        }
Пример #21
0
        //[MethodImplAttribute(MethodImplOptions.Synchronized)]//Синхронизировать метод
        private bool Connect()
        {
            lock (lockConn)
            {
                DateTime dt1 = DateTime.Now;
                try
                {
                    bool result;
                    //создадим соединение с БД
                    SERVERSTATUS status;
                    _opcsrv.GetStatus(out status);
                    if (_cntconn == 0 || status == null || status.eServerState != OPCSERVERSTATE.OPC_STATUS_RUNNING)
                    {
                        _opcsrv.Connect(_progid, _host);
                        _opcsrv.GetStatus(out status);
                        if (status != null && status.eServerState == OPCSERVERSTATE.OPC_STATUS_RUNNING)
                        {
                            try
                            {
                                _opcgrp = _opcsrv.AddGroup(_grpname, false, _interval);
                                _opcgrp.HandleClient = 0;
                                int _cnt = _maps.GetLength(0);
                                _serverhandles = new int[_cnt];
                                _vals          = new object[_cnt];
                                _errs          = new object[_cnt];
                                OPCItemDef[] _opcitmsdef = new OPCItemDef[_cnt];

                                for (int i = 0; i < _cnt; i++)
                                {
                                    _opcitmsdef[i] = new OPCItemDef(_maps[i, 1], true, i, VarEnum.VT_EMPTY);
                                }
                                _opcgrp.AddItems(_opcitmsdef, out _opcitms);
                                for (int i = 0; i < _cnt; i++)
                                {
                                    _serverhandles[i] = _opcitms[i].HandleServer;
                                }
                                _opcgrp.SetEnable(true);
                                _opcgrp.Active = true;
                                _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : T(сек)=" + (DateTime.Now - dt1).Seconds + ", нап. груп. - " + _maps.GetLength(0));
                                _cntconn++;     //Увеличим счётчик активных соединений
                                _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : Connect - Активных соединений: " + _cntconn);
                                result = true;
                            }
                            catch (Exception e)
                            {
                                _server.LogWrite(LogType.ERROR, e.Message);
                                result = false;
                            }
                        }
                        else
                        {
                            result = false;
                        }
                    }
                    else
                    {
                        _cntconn++;     //Увеличим счётчик активных соединений
                        result = true;
                    }
                    return(result);
                }
                finally
                {
                    _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : T(сек)=" + (DateTime.Now - dt1).Seconds + ", время на откытие соединения");
                }
            }
        }
Пример #22
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;
             *      }	*/
        }
Пример #23
0
        static void Main(string[] args)
        {
            string progID = args.Length > 0 ? args[0] : "Kepware.KEPServerEX.V5";

            OpcServer opcServer = new OpcServer();

            opcServer.Connect(progID);
            System.Threading.Thread.Sleep(500); // we are faster than some servers!

            OpcGroup opcGroup = opcServer.AddGroup("SampleGroup", false, 900);

            List <string> itemNames = new List <string>();

            if (args.Length > 1)
            {
                for (int i = 1; i < args.Length; i++)
                {
                    itemNames.Add(args[i]);
                }
            }
            else
            {
                itemNames.Add("Simulation Examples.Functions.Ramp1");
                itemNames.Add("Simulation Examples.Functions.Random1");
            }

            OpcItemDefinition[] opcItemDefs = new OpcItemDefinition[itemNames.Count];
            for (int i = 0; i < opcItemDefs.Length; i++)
            {
                opcItemDefs[i] = new OpcItemDefinition(itemNames[i], true, i, VarEnum.VT_EMPTY);
            }

            opcGroup.AddItems(opcItemDefs, out OpcItemResult[] opcItemResult);
            if (opcItemResult == null)
            {
                Console.WriteLine("Error add items - null value returned");
                return;
            }

            int[] serverHandles = new int[opcItemResult.Length];
            for (int i = 0; i < opcItemResult.Length; i++)
            {
                if (HRESULTS.Failed(opcItemResult[i].Error))
                {
                    Console.WriteLine("AddItems - failed {0}", itemNames[i]);
                    opcGroup.Remove(true);
                    opcServer.Disconnect();
                    return;
                }
                else
                {
                    serverHandles[i] = opcItemResult[i].HandleServer;
                }
            }

            opcGroup.SetEnable(true);
            opcGroup.Active = true;

            bool result = opcGroup.Read(OPCDATASOURCE.OPC_DS_CACHE, serverHandles, out OpcItemState[] states);

            foreach (OpcItemState s in states)
            {
                if (HRESULTS.Succeeded(s.Error))
                {
                    Console.WriteLine(" {0}: {1} (Q:{2} T:{3})", s.HandleClient, s.DataValue, s.Quality, DateTime.FromFileTime(s.TimeStamp));
                }
                else
                {
                    Console.WriteLine(" {0}: ERROR = 0x{1:x} !", s.HandleClient, s.Error);
                }
            }

            opcGroup.Remove(true);
            opcServer.Disconnect();
        }
Пример #24
0
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="serverPKID"></param>
        /// <param name="address"></param>
        /// <param name="updateRate"></param>
        /// <param name="deviceTagParams"></param>
        /// <param name="callback"></param>
        private void Initial(Int64 serverPKID, string address, int updateRate,
                             List <DeviceTagParam> deviceTagParams, DataChangeEventHandler callback)
        {
            pkid = serverPKID;

            #region 初始化参数

            string ip         = (address == "") ? CBaseData.LocalIP : address;
            string serverName = address;

            string[] addes = address.Split('|', ';');  //分号隔开,前面是IP地址,后面是OPCServer名称
            if (addes.Length > 1)
            {
                ip = addes[0];
                if ((ip.ToLower() == "local") || (ip.ToLower() == "localhost") || (ip.ToLower() == "."))
                {
                    ip = CBaseData.LocalIP; //本机IP
                }
                serverName = addes[1];
            }
            else  //默认为本机
            {
                ip = CBaseData.LocalIP;
            }

            IPAddress remote;
            IPAddress.TryParse(ip, out remote);

            ServerIP      = remote;
            OPCServerName = serverName;
            Callback      = callback; //设置回调函数

            #endregion

            DeviceTags = deviceTagParams;  //标签

            #region 自定义协议

            CustomProtocol   = (addes.Length >= 3) ? addes[2] : ""; //自定义协议
            ProtocolVariable = (addes.Length >= 4) ? addes[3] : ""; //自定义协议

            #endregion

            #region OPC 设定

            string error = String.Empty;

            _opcServer = OpcServers.FirstOrDefault(c => c.PKID == serverPKID);

            if ((_opcServer == null) || (!_opcServer.IsConnected))
            {
                _opcServer = OPCConnector.ConnectOPCServer(serverPKID, ip, serverName, ref error);
            }
            else
            {
                EventLogger.Log($"【{serverPKID}】OPC服务器已连接");
            }

            if (_opcServer != null && _opcServer.IsConnected)
            {
                List <Guid>   subHandels = new List <Guid>();                                           //Handel
                List <string> subItemIds = new List <string>();                                         //标签地址

                List <Guid>   normalHandels = new List <Guid>();                                        //Handel
                List <string> normalItemIds = new List <string>();                                      //标签地址

                if (subHandels.Count > 0)                                                               //添加订阅
                {
                    OpcGroup subGroup = _opcServer.AddGroup("GP" + serverPKID + "S", updateRate, true); //订阅的Group

                    subGroup.AddItems(subItemIds.ToArray(), subHandels.ToArray());

                    subGroup.DataChanged -= OPCDataChanged;
                    subGroup.DataChanged += OPCDataChanged;
                }

                if (normalHandels.Count > 0)                                                                //添加正常
                {
                    OpcGroup normalGroup = _opcServer.AddGroup("GP" + serverPKID + "N", updateRate, false); //正常的Group

                    normalGroup.AddItems(normalItemIds.ToArray(), normalHandels.ToArray());
                }

                EventLogger.Log($"【{serverPKID}】OPC服务器连接成功。");
            }
            else
            {
                error = $"【{serverPKID}】OPC服务器连接失败,具体为:" + error;
                EventLogger.Log(error);
            }

            OpcServers.Add(_opcServer);  //将OPCServer添加到系统中

            #endregion
        }
Пример #25
0
        private void button2_Click_1(object sender, EventArgs e)
        {
            lerTag = false;
            rtc    = 0;
            oGrp   = null;
            OpcServer srv2 = new OpcServer();

            srv.Connect("Localhost", servidorOpc);

            //Cadastra os subcampos da lista na tela com as variáveis do array de resultados
            itensValor = new string[tags.Count];
            for (int i = 0; i < tags.Count; i++)
            {
                itensValor[i] = i.ToString();
                lv_tagList.Items[i].SubItems.Add(itensValor[i]);
            }



            if (servidorOpc == "")
            {
                MessageBox.Show("Nenhum servidor OPC cadastrado");
                return;
            }
            float deadBand = 0.0F;

            try
            {
                //Adicionar um grupo (pasta em que o tag será lido):
                oGrp = srv.AddGroup("Grp1", true, 500, ref deadBand, 0, 0);
            }
            catch
            {
                MessageBox.Show("Erro ao tentar adicionar grupo OPC.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            //Configurar item para leitura (array)
            items = new OPCItemDef[tags.Count];
            //string tagsArray[55] = tags.ToArray;
            for (int i = 0; i < tags.Count; i++)
            {
                items[i] = new OPCItemDef(tags[i], true, 0, System.Runtime.InteropServices.VarEnum.VT_BSTR);
            }
            addRslt = new OPCItemResult[tags.Count];
            //Adicionar este(s) ite(ns) ao grupo criado anteriormente:
            rtc = oGrp.AddItems(items, out addRslt);
            if (rtc != 0)
            {
                //Se desse erro, o valor de RTC será diferente de 0, aqui dentro poderia ter algum tratamento
            }



            iHnd = new Int32[tags.Count];

            for (int i = 0; i < tags.Count; i++)
            {
                iHnd[i] = addRslt[i].HandleServer;
            }

            //Esse aqui é o evento em paralelo a execução do botão, que faz a leitura contínua do tag:]
            //O seu código está no método logo abaixo, chamado bwLer_DoWork
            lerTag = true;

            if (bwLer.IsBusy == false)
            {
                bwLer.RunWorkerAsync();
            }
            else
            {
                bwLer.CancelAsync();
                bwLer.RunWorkerAsync();
            }
        }