예제 #1
0
        //private void OPCGroup_DataChange(int TransactionID, int NumItems, ref Array ClientHandles, ref Array ItemValues, ref Array Qualities, ref Array TimeStamps)
        //{
        //    try
        //    {
        //        Tag tag = new Tag();
        //        _lastrun = DateTime.Now;
        //        for (int i = 0; i < _maps.GetLength(0); i++)
        //        {
        //            tag.Timestamp = DateTime.Now;
        //            tag.Name = _maps[i, 0];
        //            tag.Value = _opcitms[i].Value;
        //            tag.Quality = (QualityType)_opcitms[i].Quality;
        //            _server.SetTag(tag);
        //            _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : " +_maps[i, 1] + "=" + tag.Value);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        _server.LogWrite(LogType.ERROR, "[" + this.Name + "]: " + e.ToString());
        //    }
        //}

        public override void Write(Tag tag)
        {
            DateTime dt1 = DateTime.Now;

            _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : Write вход - tag=" + tag.Name);
            //Создадим соединение
            if (!Connect())
            {
                throw new Exception("[" + this._name + "] : Ошибка подключения! ");
            }

            for (int i = 0; i < _maps.GetLength(0); i++)
            {
                if (_maps[i, 0] == tag.Name)
                {
                    lock (lockThis)
                    {
                        int[] arrErr;
                        _opcgrp.Write(new int[] { _opcitms[i].HandleServer }, new object[] { tag.Value }, out arrErr);
                        if (arrErr.GetLength(0) > 0 && arrErr[0] != 0)
                        {
                            string message = "[" + this._name + "] : Ошибка записи! Tag[" + tag.Name + "]=" + tag.Value + ", error: " + arrErr[0].ToString();
                            _server.LogWrite(LogType.ERROR, message);
                            throw new Exception(message);
                        }
                    }
                    break;
                }
            }
            //Отключим соединение если не требуется хранить его
            Disconnect();
            _server.LogWrite(LogType.DEBUG, "[" + this._name + "] : T(сек)=" + (DateTime.Now - dt1).Seconds + ", Write выход  - tag=" + tag.Name);
        }
예제 #2
0
        private void btnItemWrite_Click(object sender, System.EventArgs e)
        {
            try
            {
                txtItemWriteRes.Text = "";

                // convert the user text to OPC data type of item
                object[] arrVal = new Object[1];
                arrVal[0] = Convert.ChangeType(txtItemSendValue.Text, itmTypeCode);

                int[] serverhandles = new int[1] {
                    itmHandleServer
                };
                int   cancelID;
                int[] arrErr;
                theGrp.Write(serverhandles, arrVal, 9988, out cancelID, out arrErr);

                GC.Collect();                   // just for fun
            }
            catch (FormatException)
            {
                MessageBox.Show(this, "Invalid data format!", "opcItemDoWrite_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            catch (OverflowException)
            {
                MessageBox.Show(this, "Invalid data range/overflow!", "opcItemDoWrite_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            catch (COMException)
            {
                MessageBox.Show(this, "OPC Write Item error!", "opcItemDoWrite_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }
        public void WriteItems(List <string> p_ItemsId, string p_Value)
        {
            _itemAccessMutex.WaitOne();

            try
            {
                int l_ItemsToWriteCount = p_ItemsId.Count;

                int[]    l_ServerHandleArray = new int[l_ItemsToWriteCount];
                object[] l_ValueArray        = new object[l_ItemsToWriteCount];
                int[]    l_ErrorArray;

                for (int i = 0; i < l_ItemsToWriteCount; ++i)
                {
                    l_ServerHandleArray[i] = _serverModel.GetServerHandleFromItemId(p_ItemsId[i]);

                    int      l_ClientHandle = _serverModel.GetClientHandleFromServerHandle(l_ServerHandleArray[i]);
                    IOPCItem l_Item         = _serverModel.GetItemFromClientHandle(l_ClientHandle);
                    l_ValueArray[i] = OpcUtility.StringToValue(l_Item.Type, p_Value);
                }
                _group.Write(l_ServerHandleArray, l_ValueArray, out l_ErrorArray);

                // TODO Check the error
            }
            catch (Exception l_Ex)
            {
                throw l_Ex;
            }
            finally
            {
                _itemAccessMutex.ReleaseMutex();
            }
        }
예제 #4
0
        public void WriteToOpc(string value)
        {
            // convert the user text to OPC data type of item
            object[] arrVal = new Object[1];
            arrVal[0] = Convert.ChangeType(value, ItmTypeCode);

            int[] serverhandles = new int[1] {
                _itmHandleServer
            };
            int cancelId;

            int[] arrErr;
            _theGrp.Write(serverhandles, arrVal, 9988, out cancelId, out arrErr);
        }
예제 #5
0
 public void TestWrite01()
 {
     //Testing ---
     int[]    arrHSrv = new int[1];
     object[] arrVal  = new object[1];
     int[]    arrErr  = null;
     //Test Procedure Call
     bool b = group.Write(arrHSrv, arrVal, out arrErr);
 }
예제 #6
0
        private bool SetOneOPCTag(IOPCTag opcTag, VarEnum dataType)
        {
            var items = new OPCItemDef[1];

            items[0] = new OPCItemDef(opcTag.FullName, true, 0, dataType);

            OPCItemResult[] addRslt;
            int             rtc = OPCWriteGroup.AddItems(items, out addRslt);

            if (HRESULTS.Failed(rtc))
            {
                return(false);// "Error at AddItem";
            }
            var iHnd = new Int32[addRslt.Length];

            for (int i = 0; i < addRslt.Length; ++i)
            {
                iHnd[i] = addRslt[i].HandleServer;
            }
            int[] err;
            var   val = new object[addRslt.Length];

            val[0] = opcTag.ObjectValue;

            rtc = OPCWriteGroup.Write(iHnd, val, out err);

            //string errTxt = "OK";
            if (HRESULTS.Failed(rtc))
            {
                return(false);
                //errTxt = srv.GetErrorString(rtc, 0);
            }
            // succeeded
            // check item error codes
            if (err.Any(HRESULTS.Failed))
            {
                return(false);
            }

            OPCWriteGroup.RemoveItems(iHnd, out err);
            return(true);
            //            return errTxt;
        }
예제 #7
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;
             *      }	*/
        }
예제 #8
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();
        }
예제 #9
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);
        }