private OpcDaItemResult[] CreateItemResults(IList <OpcDaItemDefinition> itemDefinitions, OPCITEMDEF[] pItemArray,
                                                    OPCITEMRESULT[] opcDaItemResults, HRESULT[] ppErrors, bool setGroup)
        {
            var results = new OpcDaItemResult[pItemArray.Length];

            for (int index = 0; index < opcDaItemResults.Length; index++)
            {
                OPCITEMRESULT       opcItemResult     = opcDaItemResults[index];
                OpcDaItemDefinition opcItemDefinition = itemDefinitions[index];
                HRESULT             error             = ppErrors[index];

                if (error.Succeeded)
                {
                    var item = new OpcDaItem(opcItemDefinition, opcItemResult, setGroup ? this : null)
                    {
                        UserData = opcItemDefinition.UserData
                    };
                    results[index] = new OpcDaItemResult(item, error);
                }
                else
                {
                    results[index] = new OpcDaItemResult(null, error);
                }
            }
            return(results);
        }
Beispiel #2
0
 internal static int[] GetItemResults(ref IntPtr pInput, int count, bool deallocate)
 {
     int[] numArray = null;
     if ((pInput != IntPtr.Zero) && (count > 0))
     {
         numArray = new int[count];
         IntPtr ptr = pInput;
         for (int i = 0; i < count; i++)
         {
             OPCITEMRESULT opcitemresult = (OPCITEMRESULT)Marshal.PtrToStructure(ptr, typeof(OPCITEMRESULT));
             numArray[i] = opcitemresult.hServer;
             if (deallocate)
             {
                 Marshal.FreeCoTaskMem(opcitemresult.pBlob);
                 opcitemresult.pBlob = IntPtr.Zero;
                 Marshal.DestroyStructure(ptr, typeof(OPCITEMRESULT));
             }
             ptr = (IntPtr)(ptr.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
         }
         if (deallocate)
         {
             Marshal.FreeCoTaskMem(pInput);
             pInput = IntPtr.Zero;
         }
     }
     return(numArray);
 }
Beispiel #3
0
        internal static int[] GetItemResults(ref IntPtr pInput, int count, bool deallocate)
        {
            int[] array = null;
            if (pInput != IntPtr.Zero && count > 0)
            {
                array = new int[count];
                IntPtr ptr = pInput;
                for (int i = 0; i < count; i++)
                {
                    OPCITEMRESULT oPCITEMRESULT = (OPCITEMRESULT)Marshal.PtrToStructure(ptr, typeof(OPCITEMRESULT));
                    array[i] = oPCITEMRESULT.hServer;
                    if (deallocate)
                    {
                        Marshal.FreeCoTaskMem(oPCITEMRESULT.pBlob);
                        oPCITEMRESULT.pBlob = IntPtr.Zero;
                        Marshal.DestroyStructure(ptr, typeof(OPCITEMRESULT));
                    }

                    ptr = (IntPtr)(ptr.ToInt64() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                }

                if (deallocate)
                {
                    Marshal.FreeCoTaskMem(pInput);
                    pInput = IntPtr.Zero;
                }
            }

            return(array);
        }
Beispiel #4
0
        /// <summary>
        /// 添加项
        /// </summary>
        /// <param name="lstOpcItem"></param>
        public void AddItems(List <OpcItem> lstOpcItem)
        {
            OPCITEMDEF[] itemArray = new OPCITEMDEF[lstOpcItem.Count];
            for (int i = 0; i < itemArray.Length; i++)
            {
                itemArray[i].szAccessPath        = lstOpcItem[i].AccessPath;
                itemArray[i].szItemID            = lstOpcItem[i].PlcAddress;
                itemArray[i].bActive             = lstOpcItem[i].IsActive;
                itemArray[i].hClient             = lstOpcItem[i].ClientItemHandle;
                itemArray[i].dwBlobSize          = lstOpcItem[i].dwBlobSize;
                itemArray[i].pBlob               = lstOpcItem[i].pBlob;
                itemArray[i].vtRequestedDataType = lstOpcItem[i].RequestedDataType;
            }
            IntPtr pAddResults = IntPtr.Zero;
            IntPtr pErrors     = IntPtr.Zero;

            try
            {
                OPCItemMgt.AddItems(itemArray.Length, itemArray, out pAddResults, out pErrors);
                //获取ServerItemrHandles
                int[] errors = new int[itemArray.Length];
                Marshal.Copy(pErrors, errors, 0, itemArray.Length);
                IntPtr pos = pAddResults;
                for (int i = 0; i < errors.Length; i++)
                {
                    if (errors[i] == 0)
                    {
                        if (i != 0)
                        {
                            pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                        }
                        OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
                        lstOpcItem[i].ServerItemHandle = result.hServer;
                        OpcItems.Add(lstOpcItem[i].ClientItemHandle, lstOpcItem[i]);
                    }
                    else
                    {
                        throw new ApplicationException($"添加组[{GroupName}]时,添加项[{itemArray[i].szItemID}]失败!");
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pAddResults != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pAddResults);
                    pAddResults = IntPtr.Zero;
                }
                if (pErrors != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pErrors);
                    pErrors = IntPtr.Zero;
                }
            }
        }
        public ConnectionGroup(string opcServer, string opcHost, List <OPCBaseChannel> channels)
        {
            Type t;

            if (opcHost.ToLowerInvariant() == "localhost")
            {
                t = Type.GetTypeFromProgID(opcServer);
            }
            else
            {
                t = Type.GetTypeFromProgID(opcServer, opcHost);
            }

            server = (IOPCServer)Activator.CreateInstance(t);
            int    groupClientId = 1;
            int    groupId;
            int    updateRate = 0;
            object group_obj;
            Guid   tmp_guid = typeof(IOPCItemMgt).GUID;

            server.AddGroup("fscdg", 1, updateRate, groupClientId, new IntPtr(), new IntPtr(), 0, out groupId, out updateRate, ref tmp_guid, out group_obj);
            group = (IOPCItemMgt)group_obj;
            IntPtr addResult = new IntPtr();
            IntPtr addErrors = new IntPtr();


            OPCITEMDEF[] items = new OPCITEMDEF[2];
            for (int i = 0; i < channels.Count; i++)
            {
                items[0].bActive  = 1;
                items[0].szItemID = channels[i].OpcChannel;
                items[0].hClient  = channels[i].GetHashCode();
                group.AddItems(1, items, out addResult, out addErrors);
            }


            for (int i = 0; i < channels.Count; i++)
            {
                IntPtr        pos = new IntPtr(addResult.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)) * i);
                OPCITEMRESULT res = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));

                bool readOnly = (res.dwAccessRights & OPC_WRITEABLE) != OPC_WRITEABLE;
                channels[i].Connect(this, res.hServer, readOnly);
            }
            Marshal.FreeCoTaskMem(addResult);
            Marshal.FreeCoTaskMem(addErrors);
            addResult = IntPtr.Zero;
            addErrors = IntPtr.Zero;

            IConnectionPointContainer cpc = (IConnectionPointContainer)group_obj;
            IConnectionPoint          cp;
            Guid dataCallbackGuid = typeof(IOPCDataCallback).GUID;

            cpc.FindConnectionPoint(ref dataCallbackGuid, out cp);

            callback = new OPCDataCallback(channels);
            cp.Advise(callback, out callbackCookie);
        }
Beispiel #6
0
        public bool AddItems(OPCITEMDEF[] items, int[] itemHandle)
        {
            IntPtr zero     = IntPtr.Zero;
            IntPtr ppErrors = IntPtr.Zero;

            if (!this.isAddGroup && !this.AddGroup())
            {
                return(false);
            }
            try
            {
                ((IOPCItemMgt)this.GroupObj).AddItems(items.Length, items, out zero, out ppErrors);
                int[] destination = new int[items.Length];
                Marshal.Copy(ppErrors, destination, 0, items.Length);
                IntPtr ptr = zero;
                for (int i = 0; i < items.Length; i++)
                {
                    if (destination[i] == 0)
                    {
                        OPCITEMRESULT opcitemresult = (OPCITEMRESULT)Marshal.PtrToStructure(ptr, typeof(OPCITEMRESULT));
                        itemHandle[i]   = opcitemresult.hServer;
                        ptr             = new IntPtr(ptr.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                        this.isAddItems = true;
                    }
                    else
                    {
                        this.isAddItems = false;
                        MessageBox.Show($"添加第{i + 1}个Item对象时出错", "添加Item对象出错", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                        goto Label_0141;
                    }
                }
            }
            catch (Exception exception)
            {
                this.isAddItems = false;
                MessageBox.Show($"添加Item对象时出错:-{exception.Message}", "添加Item对象出错", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(zero);
                    zero = IntPtr.Zero;
                }
                if (ppErrors != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ppErrors);
                    ppErrors = IntPtr.Zero;
                }
            }
Label_0141:
            return(this.isAddItems);
        }
 internal OpcDaItem(OpcDaItemDefinition itemDefinition, OPCITEMRESULT itemResult, OpcDaGroup @group)
 {
     Group             = @group;
     ClientHandle      = 0;
     ServerHandle      = itemResult.hServer;
     ItemId            = itemDefinition.ItemId;
     RequestedDataType = itemDefinition.RequestedDataType;
     CanonicalDataType = TypeConverter.FromVarEnum((VarEnum)itemResult.vtCanonicalDataType);
     Blob         = itemResult.pBlob;
     AccessPath   = itemDefinition.AccessPath;
     IsActive     = itemDefinition.IsActive;
     AccessRights = (OpcDaAccessRights)itemResult.dwAccessRights;
 }
        public static OPCITEMRESULT[] CreateOpcItemResults(OPCITEMDEF[] pItemArray, IntPtr ppAddResults)
        {
            var results = new OPCITEMRESULT[pItemArray.Length];

            for (int i = 0; i < pItemArray.Length; i++)
            {
                IntPtr current = ppAddResults + i * Marshal.SizeOf(typeof(OPCITEMRESULT));

                results[i] = (OPCITEMRESULT)Marshal.PtrToStructure(current, typeof(OPCITEMRESULT));
                Marshal.DestroyStructure(current, typeof(OPCITEMRESULT));
                Marshal.FreeCoTaskMem(pItemArray[i].pBlob); // Delete allocated blobs
            }
            return(results);
        }
Beispiel #9
0
        /// <summary>
        /// 添加一项
        /// </summary>
        /// <param name="opcItem"></param>
        public void AddItem(OpcItem opcItem)
        {
            OPCITEMDEF item = new OPCITEMDEF();

            item.szAccessPath        = opcItem.AccessPath;
            item.szItemID            = opcItem.PlcAddress;
            item.bActive             = opcItem.IsActive;
            item.hClient             = opcItem.ClientItemHandle;
            item.dwBlobSize          = opcItem.dwBlobSize;
            item.pBlob               = opcItem.pBlob;
            item.vtRequestedDataType = opcItem.RequestedDataType;
            IntPtr pAddResults = IntPtr.Zero;
            IntPtr pErrors     = IntPtr.Zero;

            try
            {
                OPCItemMgt.AddItems(1, new OPCITEMDEF[] { item }, out pAddResults, out pErrors);
                //获取ServerItemrHandles
                int[] errors = new int[1];
                Marshal.Copy(pErrors, errors, 0, 1);
                IntPtr pos = pAddResults;
                if (errors[0] == 0)
                {
                    OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
                    opcItem.ServerItemHandle = result.hServer;
                    OpcItems.Add(opcItem.ClientItemHandle, opcItem);
                }
                else
                {
                    throw new ApplicationException($"添加组[{GroupName}]时,添加项[{item.szItemID}]失败!");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (pAddResults != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pAddResults);
                    pAddResults = IntPtr.Zero;
                }
                if (pErrors != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pErrors);
                    pErrors = IntPtr.Zero;
                }
            }
        }
Beispiel #10
0
        internal int GetServerHandle(string ItemId)
        {
            int ret;

            if (!m_mapServerHandles.TryGetValue(ItemId, out ret))
            {
                OPCITEMDEF[] ItemIds = new OPCITEMDEF[1];
                ItemIds[0] = new OPCITEMDEF()
                {
                    bActive  = 0,
                    szItemID = ItemId
                };
                IntPtr pAddResults;
                IntPtr pErrors;
                m_itemManagement.AddItems(1, ItemIds, out pAddResults, out pErrors);
                if (pAddResults == IntPtr.Zero)
                {
                    throw new Exception("GetServerHandle failed. No Results.");
                }
                if (pErrors == IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pAddResults);
                    throw new Exception("GetServerHandle failed. No ErrorCodes.");
                }
                int[] errors = new int[1];
                Marshal.Copy(pErrors, errors, 0, 1);
                Marshal.FreeCoTaskMem(pErrors);

                if (errors[0] != 0)
                {
                    Marshal.DestroyStructure(pAddResults, typeof(OpcRcw.Da.OPCITEMRESULT));
                    Marshal.FreeCoTaskMem(pAddResults);
                    string ErrorString;
                    m_server.GetErrorString(errors[0], 0, out ErrorString);
                    throw new Exception(ErrorString);
                }

                OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pAddResults, typeof(OPCITEMRESULT));
                ret = result.hServer;
                m_mapServerHandles.Add(ItemId, ret);

                Marshal.FreeCoTaskMem(result.pBlob);
                result.pBlob = IntPtr.Zero;
                Marshal.DestroyStructure(pAddResults, typeof(OpcRcw.Da.OPCITEMRESULT));
                Marshal.FreeCoTaskMem(pAddResults);
            }
            return(ret);
        }
Beispiel #11
0
        private bool AddItem(OPCItem item)
        {
            bool flag = true;

            OPCITEMDEF[] pItemArray = new OPCITEMDEF[1];
            pItemArray[0].szAccessPath        = "";
            pItemArray[0].szItemID            = item.OPCItemName;
            pItemArray[0].bActive             = item.IsActive ? 1 : 0;
            pItemArray[0].hClient             = item.ClientHandler;
            pItemArray[0].dwBlobSize          = 0;
            pItemArray[0].pBlob               = IntPtr.Zero;
            pItemArray[0].vtRequestedDataType = 0;
            IntPtr zero     = IntPtr.Zero;
            IntPtr ppErrors = IntPtr.Zero;

            try
            {
                ((IOPCItemMgt)this.group).AddItems(1, pItemArray, out zero, out ppErrors);
                int[] destination = new int[1];
                Marshal.Copy(ppErrors, destination, 0, 1);
                if (destination[0] == 0)
                {
                    OPCITEMRESULT opcitemresult = (OPCITEMRESULT)Marshal.PtrToStructure(zero, typeof(OPCITEMRESULT));
                    item.ServerHandler = opcitemresult.hServer;
                    return(flag);
                }
                flag = false;
                throw new Exception("在组中添加项不成功,原因:" + this.parent.GetLastError(destination[0]));
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(zero);
                    zero = IntPtr.Zero;
                }
                if (ppErrors != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(ppErrors);
                    ppErrors = IntPtr.Zero;
                }
            }
            return(flag);
        }
Beispiel #12
0
        public void AddItem(string itemId, int clientHandle)
        {
            if (!m_server.isConnected())
            {
                throw new InvalidOperationException("Not connected to OPC-Server!");
            }
            OPCITEMDEF[] ItemDefs = new OPCITEMDEF[1];
            ItemDefs[0] = new OPCITEMDEF()
            {
                bActive  = 1,
                szItemID = itemId,
                hClient  = clientHandle
            };
            IntPtr pAddResults;
            IntPtr pErrors;

            m_itemManagement.AddItems(1, ItemDefs, out pAddResults, out pErrors);
            if (pAddResults == IntPtr.Zero)
            {
                throw new Exception("AddItems failed. No Results.");
            }
            if (pErrors == IntPtr.Zero)
            {
                Marshal.FreeCoTaskMem(pAddResults);
                throw new Exception("AddItems failed. No ErrorCodes.");
            }
            int[] errors = new int[1];
            Marshal.Copy(pErrors, errors, 0, 1);
            if (errors[0] != 0)
            {
                Marshal.FreeCoTaskMem(pAddResults);
                Marshal.FreeCoTaskMem(pErrors);
                string ErrorString;
                m_server.GetErrorString(errors[0], 0, out ErrorString);
                throw new Exception(ErrorString);
            }
            OPCITEMRESULT result  = (OPCITEMRESULT)Marshal.PtrToStructure(pAddResults, typeof(OPCITEMRESULT));
            int           hServer = result.hServer;

            m_mapServerHandles.Add(itemId, hServer);
            Marshal.FreeCoTaskMem(pAddResults);
            Marshal.FreeCoTaskMem(pErrors);
        }
Beispiel #13
0
        /// <summary>
        /// 添加组和标签异步读取
        /// </summary>
        /// <param name="name"></param>
        public static void OPCServerADDgroup(string name, string itemname)
        {
            Int32 dwRequestedUpdateRate = 1000;
            Int32 hClientGroup          = 1;
            Int32 pRevUpdateRate;


            float    deadband = 0;
            int      TimeBias = 0;
            GCHandle hTimeBias, hDeadband;

            hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned);
            hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned);
            Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID;

            if (connectedOK == false)
            {
                MessageBox.Show("OPC服务器没有连接,读取数据失败");
                return;
            }
            IntPtr pResults = IntPtr.Zero;                                                  /* 保存AddItems函数的执行结果 */
            IntPtr pErrors  = IntPtr.Zero;                                                  /* 保存AddItems函数的执行错误 */

            /* 执行结果信息 */
            try
            {
                Serverobj.AddGroup(name,
                                   0, dwRequestedUpdateRate,
                                   hClientGroup,
                                   hTimeBias.AddrOfPinnedObject(),
                                   hDeadband.AddrOfPinnedObject(),
                                   LOCALE_ID,
                                   out pSvrGroupHandle,
                                   out pRevUpdateRate,
                                   ref iidRequiredInterface,
                                   out MyobjGroup1);                                 //增加相应的组
                IOPCAsyncIO2Obj            = (IOPCAsyncIO2)MyobjGroup1;              //为组同步读写定义句柄
                IOPCGroupStateMgtObj       = (IOPCGroupStateMgt)MyobjGroup1;         //组管理对象
                pIConnectionPointContainer = (IConnectionPointContainer)MyobjGroup1; //增加特定组的异步调用连接

                Guid iid = typeof(IOPCDataCallback).GUID;                            //为所有的异步调用创建回调
                pIConnectionPointContainer.FindConnectionPoint(ref iid, out pIConnectionPoint);
                //为OPC server 的连接点与客户端接收点之间建立连接
                //  pIConnectionPoint.Advise(this, out dwCookie);
                tItemSvrHandleArray = new  int[1];
                OPCITEMDEF[] itemarray = new OPCITEMDEF[4];
                itemarray[0].szAccessPath        = "";       /* 访问路径"" */
                itemarray[0].szItemID            = itemname; /* OPC标签名称 */
                itemarray[0].hClient             = 1;
                tItemSvrHandleArray[0]           = 1;        /* 客户机的标签索引 */
                itemarray[0].dwBlobSize          = 0;
                itemarray[0].pBlob               = IntPtr.Zero;
                itemarray[0].vtRequestedDataType = 2;
                ItemSvrHandleArray               = new int[1, 1];
                ((IOPCItemMgt)MyobjGroup1).AddItems(1, itemarray, out pResults, out pErrors); //将标签加入到组中
                int[]  errors = new int[1];                                                   /* 每个标签的错误信息 */
                IntPtr pos    = pResults;
                Marshal.Copy(pErrors, errors, 0, 1);                                          /* pErrors->errors */
                for (int i = 0; i < 1; i++)                                                   /* 检查每个标签的error */
                {
                    if (errors[i] == 0)                                                       /* 如果无错误=0 */
                    {
                        if (i != 0)                                                           /* 如果不是第一个标签则指针移动一个OPCITEMRESULT */
                        {
                            pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                        }
                        OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT)); /* IntPtr->OPCITEMRESULT */
                        ItemSvrHandleArray[0, 0] = result.hServer;                                                /* 保存该标签在服务器中的句柄,以后读写标签数值时要用到 */
                    }
                    else
                    {                                                                       /* 如果有错误(向服务器添加标签失败) */
                        connectedOK = false;                                                /* 连接失败 */
                        // String strError;
                        //  Serverobj.GetErrorString(errors[i], LOCALE_ID, out strError);   /* 获取错误信息 */
                        // OutputExceptionToDatabase(.......)                               /* 将异常信息输出到数据库 */
                        throw new Exception("添加标签:" + itemarray[i].szItemID + " 错误!" //+ strError
                                            );                                       /* 抛出异常 */
                    }
                }
            }
            catch (System.Exception error)
            {
                MessageBox.Show("group组添加失败失败\n" + error.Message);
            }
            finally
            {
                if (pResults != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pResults);
                    pErrors = IntPtr.Zero;
                }
                if (pErrors != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pErrors);
                    pErrors = IntPtr.Zero;
                }
            }
        }
Beispiel #14
0
        /// <summary> adds an IOPCItemStateMgt-object to given group </summary>
        /// <param name="itemsActive"> determines which item is active </param>
        /// <param name="itemIDs"> determines the itemIDs </param>
        /// <param name="itemTypes"> the datatypes of the items </param>
        /// <param name="itmClntHndls"> the clientHandles of the items </param>
        /// <param name="itmSrvHndls"> the serverHandles given from the opc-server </param>
        /// <exception cref="Exception">throws and forwards any exception (with short error description)</exception>
        public void addOPCItems(bool[] itemsActive,    // 激活
                                string[] itemIDs,      // item id
                                short[] itemTypes,     // item的数据类型
                                int[] itmClntHndls,    // item的client句柄数组
                                out int[] itmSrvHndls) // item的server句柄数组
        {
            // initialize arguments.
            Guid iid = Guid.Empty;
            //number of elements we can add
            int numberOfItems = itmClntHndls.Length;

            OPCITEMDEF[] Itemdefs  = new OPCITEMDEF[numberOfItems];
            IntPtr       ppResults = IntPtr.Zero;
            IntPtr       ppErrors  = IntPtr.Zero;
            string       strDummy  = "";

            if (m_disposed)
            {
                throw new NullReferenceException("This object has been disposed!");
            }

            // Init item server handles
            itmSrvHndls = new int[numberOfItems];

            try
            {
                // Get Item interface
                m_OPCItem = (IOPCItemMgt)m_OPCGroupStateMgt;
                if (m_OPCItem == null)
                {
                    strDummy = "Could not get the interface 'IOPCItemMgt'!";
                    throw new Exception(strDummy);
                }

                // Now add the items
                for (int i = 0; i < numberOfItems; i++)
                {
                    // Accesspath not needed
                    Itemdefs[i].szAccessPath = "";
                    // AddItem Active, so OnDataChange will come in an active group for this item
                    Itemdefs[i].bActive = Convert.ToInt32(itemsActive[i]);
                    // We want to get the items as string
                    Itemdefs[i].vtRequestedDataType = itemTypes[i];
                    // "BinaryLargeOBject" not needed by SimaticNet OPC Server
                    Itemdefs[i].dwBlobSize = 0;
                    // no blob
                    Itemdefs[i].pBlob = IntPtr.Zero;

                    Itemdefs[i].hClient  = itmClntHndls[i];
                    Itemdefs[i].szItemID = itemIDs[i];
                }

                // Adding items to the Group
                m_OPCItem.AddItems(numberOfItems,
                                   Itemdefs,
                                   out ppResults,
                                   out ppErrors);

                if (ppResults == IntPtr.Zero)
                {
                    strDummy = "The server did not return a result array.";
                    throw new Exception(strDummy);
                }
                if (ppErrors == IntPtr.Zero)
                {
                    strDummy = "The server did not return an arror array.";
                    throw new Exception(strDummy);
                }

                //Evaluate return ErrorCodes to exclude possible Errors
                int[] errors = new int[numberOfItems];
                Marshal.Copy(ppErrors, errors, 0, numberOfItems);

                OPCITEMRESULT[] result = new OPCITEMRESULT[numberOfItems];
                IntPtr          pos    = ppResults;

                for (int dwCount = 0; dwCount < numberOfItems; dwCount++)
                {
                    try
                    {
                        if (errors[dwCount] != 0)
                        {
                            strDummy = "At least one item is not added.";
                            throw new Exception(strDummy);                             // 抛出异常
                        }
                        // Item was added succesfully
                        result[dwCount]      = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
                        itmSrvHndls[dwCount] = result[dwCount].hServer;
                    }
                    catch (Exception)
                    {
                        // Item was not added
                        throw;
                    }

                    pos = (IntPtr)(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                }

                m_itmServerHandles = new int[numberOfItems];
                m_itmServerHandles = itmSrvHndls;

                // Free allocated COM-ressouces
                Marshal.FreeCoTaskMem(ppResults);
                Marshal.FreeCoTaskMem(ppErrors);
            }
            catch (Exception)
            {
                // Free allocated COM-ressouces
                Marshal.FreeCoTaskMem(ppResults);
                Marshal.FreeCoTaskMem(ppErrors);

                throw;
            }
        }
Beispiel #15
0
        /// <summary>
        /// For each item check if is has a handle already. If not add the item.
        /// </summary>
        /// <param name="itemIds"></param>
        /// <param name="handles"></param>
        /// <returns>true if all handles could be retreived. Otherwise false.</returns>
        internal bool GetServerHandles(StringCollection itemIds, out int[] handles, out int[] pErrors)
        {
            bool bResult = true;
            int  currentHandle;

            handles = new int[itemIds.Count];
            pErrors = new int[itemIds.Count];

            ArrayList indexesToAdd = new ArrayList();

            // collect data to AddItems
            for (int i = 0; i < itemIds.Count; i++)
            {
                // Item exists already
                if (m_mapServerHandles.TryGetValue(itemIds[i], out currentHandle))
                {
                    handles[i] = currentHandle;
                    pErrors[i] = 0;
                }
                // Need to add item
                else
                {
                    indexesToAdd.Add(i);
                }
            }

            if (indexesToAdd.Count > 0)
            {
                OPCITEMDEF[] itemsToAdd = new OPCITEMDEF[indexesToAdd.Count];

                for (int i = 0; i < indexesToAdd.Count; i++)
                {
                    //itemsToAdd[i] = new OPCITEMDEF();

                    itemsToAdd[i].szItemID            = itemIds[(int)indexesToAdd[i]];
                    itemsToAdd[i].szAccessPath        = "";
                    itemsToAdd[i].bActive             = 0;
                    itemsToAdd[i].vtRequestedDataType = 0;
                    itemsToAdd[i].hClient             = 0;
                    itemsToAdd[i].dwBlobSize          = 0;
                    itemsToAdd[i].pBlob = IntPtr.Zero;
                }

                IntPtr pAddResults;
                IntPtr ppErrors;

                m_itemManagement.AddItems(
                    indexesToAdd.Count,
                    itemsToAdd,
                    out pAddResults,
                    out ppErrors);

                if (pAddResults == IntPtr.Zero)
                {
                    throw new Exception("GetServerHandle failed. No Results.");
                }
                if (ppErrors == IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pAddResults);
                    throw new Exception("GetServerHandle failed. No ErrorCodes.");
                }

                IntPtr posResults = pAddResults;
                int[]  pErrorsTmp = Helper.GetInt32s(ref ppErrors, indexesToAdd.Count, true);

                for (int i = 0; i < indexesToAdd.Count; i++)
                {
                    int currentIndex = (int)indexesToAdd[i];
                    if (pErrorsTmp[i] != 0)
                    {
                        // caller to check pErrors
                        bResult = false;
                        pErrors[currentIndex] = pErrorsTmp[i];
                        continue;
                    }

                    OPCITEMRESULT itemResult = (OPCITEMRESULT)Marshal.PtrToStructure(posResults, typeof(OPCITEMRESULT));

                    m_mapServerHandles.Add(itemsToAdd[i].szItemID, itemResult.hServer);
                    handles[currentIndex] = itemResult.hServer;

                    Marshal.FreeCoTaskMem(itemResult.pBlob);
                    itemResult.pBlob = IntPtr.Zero;

                    Marshal.DestroyStructure(posResults, typeof(OpcRcw.Da.OPCITEMRESULT));

                    posResults = (IntPtr)(posResults.ToInt64() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                }

                Marshal.FreeCoTaskMem(pAddResults);
                pAddResults = IntPtr.Zero;
            }

            return(bResult);
        }
Beispiel #16
0
        int pSvrGroupHandle = 0;                                 //OPCGroup句柄

        //连接OPCServer,建立相应OPCGroup组,并添加需要读写的Item
        private void Btn_Conn_Click(object sender, EventArgs e)
        {
            //定义变量
            Type  svrComponenttype;
            Int32 dwRequestedUpdateRate = 1000; //订阅读取速度
            Int32 hClientGroup          = 1;
            Int32 pRevUpdateRate;

            OpcRcw.Da.OPCITEMDEF[] ItemArray;

            float deadband = 0;

            int TimeBias = 0;

            //使用C#托管代码时,内存地址和GC回收不需要关心,CLR已经给我们暗箱操作
            //如果在C#中调用了非托管代码,比如VC的DLL,而且它有一个回调函数,需要引用C#中的某个对象并操作,这时候需要小心
            //要是非托管代码中用到的托管代码那个对象被GC给回收了,这时候就会报内存错误
            //所以就要把那个对象钉住"Pin",让它的内存地址固定,而不被垃圾回收掉,然后我们自己管理,自己释放内存,这时候就需要GCHandle
            GCHandle hTimeBias, hDeadband;

            hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned);
            hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned);
            Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID;

            try
            {
                svrComponenttype = Type.GetTypeFromProgID("OPC.SimaticNet", "192.168.0.102");        //OPCServer
                ServerObj        = (OpcRcw.Da.IOPCServer)Activator.CreateInstance(svrComponenttype); //注册
                try
                {
                    ServerObj.AddGroup("MyOPCGroup1",   //增加组
                                       0,
                                       dwRequestedUpdateRate,
                                       hClientGroup,
                                       hTimeBias.AddrOfPinnedObject(),
                                       hDeadband.AddrOfPinnedObject(),
                                       LOCALE_ID,
                                       out pSvrGroupHandle,
                                       out pRevUpdateRate,
                                       ref iidRequiredInterface,
                                       out MyobjGroup1);
                    IOPCSyncIO20Obj      = (IOPCSyncIO)MyobjGroup1; //Query interface for sync calls on group object
                    IOPCGroupStateMgtObj = (IOPCGroupStateMgt)MyobjGroup1;
                    ItemArray            = new OPCITEMDEF[2];       //定义读写的item,共2个变量

                    ItemArray[0].szAccessPath        = "";
                    ItemArray[0].szItemID            = "S7:[S7 conncetion_1]DB10,INT0"; //地址,不同数据类型表示方法不同
                    ItemArray[0].bActive             = 1;                               //是否激活
                    ItemArray[0].hClient             = 1;                               //表示ID
                    ItemArray[0].dwBlobSize          = 0;
                    ItemArray[0].vtRequestedDataType = 2;
                    ItemArray[1].szAccessPath        = "";
                    ItemArray[1].szItemID            = "S7:[S7 connection_1]DB10,STRING14.10";
                    ItemArray[1].bActive             = 1;
                    ItemArray[1].hClient             = 2;
                    ItemArray[1].dwBlobSize          = 0;
                    ItemArray[1].pBlob = IntPtr.Zero;
                    ItemArray[1].vtRequestedDataType = 8;
                    IntPtr pResults = IntPtr.Zero;
                    IntPtr pErrors  = IntPtr.Zero;
                    try
                    {
                        ((OpcRcw.Da.IOPCItemMgt)MyobjGroup1).AddItems(2, ItemArray, out pResults, out pErrors);
                        int[]  errors = new int[2];
                        IntPtr pos    = pResults;
                        ItemServerHandle = new int[2];
                        Marshal.Copy(pErrors, errors, 0, 2);
                        if (errors[0] == 0)
                        {
                            OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
                            ItemServerHandle[0] = result.hServer;
                        }
                        if (errors[1] == 0)
                        {
                            pos = new IntPtr(pos.ToInt32() + Marshal.SizeOf(typeof(OPCITEMRESULT)));
                            OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pos, typeof(OPCITEMRESULT));
                            ItemServerHandle[1] = result.hServer;
                        }
                    }
                    catch (System.Exception error)
                    {
                        MessageBox.Show(error.Message, "Result-Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        //free the memory
                        if (pResults != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pResults);
                            pResults = IntPtr.Zero;
                        }
                        if (pErrors != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pErrors);
                            pErrors = IntPtr.Zero;
                        }
                    }
                }
                catch (System.Exception error)
                {
                    MessageBox.Show(String.Format("Error while creating group object:-{0}", error.Message), "Result-Add group", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
                }
                finally
                {
                    if (hDeadband.IsAllocated)
                    {
                        hDeadband.Free();
                    }
                    if (hTimeBias.IsAllocated)
                    {
                        hTimeBias.Free();
                    }
                }
            }
            catch (System.Exception error)
            {
                MessageBox.Show(String.Format("Error while creating server object:-{0}", error.Message), "Result-Create Server", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);
            }
        }
        public override void Init()
        {
            // Local variables
            Type svrComponenttyp;

            OPCITEMDEF[] ItemDefArray;

            // Initialise Group properties
            int   bActive = 0;
            int   dwRequestedUpdateRate = 250;
            int   hClientGroup          = 0;
            int   dwLCID = LOCALE_ID;
            int   pRevUpdateRate;
            int   TimeBias = 0;
            float deadband = 0;

            // Access unmanaged COM memory
            GCHandle hTimeBias, hDeadband;

            hTimeBias = GCHandle.Alloc(TimeBias, GCHandleType.Pinned);
            hDeadband = GCHandle.Alloc(deadband, GCHandleType.Pinned);

            // 1. Connect to the local server.
            // Get the Type from the progID and create instance of the OPC Server COM
            // component
            Guid iidRequiredInterface = typeof(IOPCItemMgt).GUID;

            svrComponenttyp = Type.GetTypeFromProgID(SERVER_NAME);
            try
            {
                pIOPCServer = (IOPCServer)Activator.CreateInstance(svrComponenttyp);
                try
                {
                    /* 2. Add a new group
                     *  Add a group object and querry for interface IOPCItemMgt
                     *  Parameter as following:
                     *  [in] not active, so no OnDataChange callback
                     *  [in] Request this Update Rate from Server
                     *  [in] Client Handle, not necessary in this sample
                     *  [in] No time interval to system UTC time
                     *  [in] No Deadband, so all data changes are reported
                     *  [in] Server uses english language to for text values
                     *  [out] Server handle to identify this group in later calls
                     *  [out] The answer from Server to the requested Update Rate
                     *  [in] requested interface type of the group object
                     *  [out] pointer to the requested interface
                     */
                    pIOPCServer.AddGroup(GROUP_NAME,
                                         bActive,
                                         dwRequestedUpdateRate,
                                         hClientGroup,
                                         hTimeBias.AddrOfPinnedObject(),
                                         hDeadband.AddrOfPinnedObject(),
                                         dwLCID,
                                         out nSvrGroupID,
                                         out pRevUpdateRate,
                                         ref iidRequiredInterface,
                                         out pobjGroup1);

                    // Get the IOPOCSyncIO interface pointer from the group pointer.
                    // pIOPCSyncIO also needs to be released when not in use.
                    pIOPCSyncIO = (IOPCSyncIO)pobjGroup1;

                    /* 3. Add items to the group */
                    // This example shows adding of only one item in the group

                    ItemDefArray = new OPCITEMDEF[1];

                    ItemDefArray[0].szAccessPath        = "";                        // Accesspath not needed for this sample
                    ItemDefArray[0].szItemID            = ITEM_NAME_Prefix + OPCTag; // ItemID, see above
                    ItemDefArray[0].bActive             = 1;                         // item is active
                    ItemDefArray[0].hClient             = 1;                         // client handle
                    ItemDefArray[0].dwBlobSize          = 0;                         // blob size
                    ItemDefArray[0].pBlob               = IntPtr.Zero;               // pointer to blob
                    ItemDefArray[0].vtRequestedDataType = 2;                         // return values in native (cannonical) datatype

                    // initialize output parameters.
                    IntPtr pResults = IntPtr.Zero;
                    IntPtr pErrors  = IntPtr.Zero;
                    try
                    {
                        // Add items to group
                        ((IOPCItemMgt)pobjGroup1).AddItems(1, ItemDefArray, out pResults, out pErrors);
                        // Unmarshal to get the server handles out fom the m_pItemResult
                        // after checking the errors
                        int[] errors = new int[1];
                        Marshal.Copy(pErrors, errors, 0, 1);
                        if (errors[0] == 0)
                        {
                            OPCITEMRESULT result = (OPCITEMRESULT)Marshal.PtrToStructure(pResults, typeof(OPCITEMRESULT));
                            // Allocate integer array
                            nItemSvrID    = new int[1];
                            nItemSvrID[0] = result.hServer;
                        }
                        else
                        {
                            string pstrError;
                            pIOPCServer.GetErrorString(errors[0], LOCALE_ID, out pstrError);
                            MessageBox.Show(pstrError,
                                            "Result - Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        // Free indirect structure elements
                        Marshal.DestroyStructure(pResults, typeof(OPCITEMRESULT));
                    }
                    catch (Exception error) // catch for error in adding items.
                    {
                        MessageBox.Show(error.Message,
                                        "Result - Adding Items", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        // Free the unmanaged COM memory
                        if (pResults != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pResults);
                            pResults = IntPtr.Zero;
                        }
                        if (pErrors != IntPtr.Zero)
                        {
                            Marshal.FreeCoTaskMem(pErrors);
                            pErrors = IntPtr.Zero;
                        }
                    }
                }
                catch (Exception error) // catch for error in creation group
                {
                    MessageBox.Show(string.Format("Error while creating group object:-{0}", error.Message),
                                    "Result-Add Group", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (hDeadband.IsAllocated)
                    {
                        hDeadband.Free();
                    }
                    if (hTimeBias.IsAllocated)
                    {
                        hTimeBias.Free();
                    }
                }
            }
            catch (Exception error) // catch for error in creating server
            {
                MessageBox.Show(string.Format("Error while creating server object:-{0}", error.Message),
                                "Result - Create Server Instance", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }