Ejemplo n.º 1
0
        public void Disconnect()
        {
            if (m_ShutdownPoint != null)
            {
                if (m_ShutdownCookie != 0)
                {
                    m_ShutdownPoint.Unadvise(m_ShutdownCookie);
                    m_ShutdownCookie = 0;
                }
                Marshal.ReleaseComObject(m_ShutdownPoint);
                m_ShutdownPoint = null;
            }

            m_PointContainer = null;
            m_IfBrowse       = null;
            m_IfItmProps     = null;
            m_IfCommon       = null;
            m_IfServer       = null;

            if (m_OPCServerObj != null)
            {
                Marshal.ReleaseComObject(m_OPCServerObj);
                m_OPCServerObj = null;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the property item ids.
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="properties">The properties to update.</param>
        private void GetPropertyItemIds(string itemId, DaProperty[] properties)
        {
            string methodName = "IOPCItemProperties.LookupItemIDs";

            int count = properties.Length;

            // get list of ids to request.
            int[] propertyIds = new int[count];

            for (int ii = 0; ii < propertyIds.Length; ii++)
            {
                propertyIds[ii] = properties[ii].PropertyId;
            }

            // request the item ids.
            IntPtr pItemIds = IntPtr.Zero;
            IntPtr pErrors  = IntPtr.Zero;

            try
            {
                IOPCItemProperties server = BeginComCall <IOPCItemProperties>(methodName, true);

                server.LookupItemIDs(
                    itemId,
                    count,
                    propertyIds,
                    out pItemIds,
                    out pErrors);
            }
            catch (Exception e)
            {
                if (ComUtils.IsUnknownError(e, ResultIds.E_FAIL, ResultIds.E_UNKNOWNITEMID, ResultIds.E_INVALIDITEMID))
                {
                    ComUtils.TraceComError(e, methodName);
                }

                return;
            }
            finally
            {
                EndComCall(methodName);
            }

            // unmarshal results.
            string[] itemIds = ComUtils.GetUnicodeStrings(ref pItemIds, count, true);
            int[]    errors  = ComUtils.GetInt32s(ref pErrors, count, true);

            // update the objects.
            for (int ii = 0; ii < count; ii++)
            {
                if (errors[ii] >= 0)
                {
                    properties[ii].ItemId = itemIds[ii];
                }
                else
                {
                    properties[ii].ItemId = null;
                }
            }
        }
Ejemplo n.º 3
0
        public void RemoteConnect(string p_ClsIDOPCServer, string p_MachineName)
        {
            Disconnect();

            Type l_TypeOfOPCServer = Type.GetTypeFromProgID(p_ClsIDOPCServer, p_MachineName);

            if (l_TypeOfOPCServer == null)
            {
                Marshal.ThrowExceptionForHR(HResults.OPC_E_NOTFOUND);
            }

            m_OPCServerObj = Activator.CreateInstance(l_TypeOfOPCServer);
            m_IfServer     = (IOPCServer)m_OPCServerObj;
            if (m_IfServer == null)
            {
                Marshal.ThrowExceptionForHR(HResults.CONNECT_E_NOCONNECTION);
            }

            // Connect all interfaces
            m_IfCommon       = (IOPCCommon)m_OPCServerObj;
            m_IfBrowse       = (IOPCBrowseServerAddressSpace)m_IfServer;
            m_IfItmProps     = (IOPCItemProperties)m_IfServer;
            m_PointContainer = (IConnectionPointContainer)m_OPCServerObj;
            AdviseIOPCShutdown();
        }
Ejemplo n.º 4
0
        public bool Connect()
        {
            if (_opcServerObj != null)
            {
                Dispose();
            }
            Guid cid;
            Type svrComponenttype = Guid.TryParse(_clsidOPCserver, out cid) ? Type.GetTypeFromCLSID(cid, _serverIP, false)
                : Type.GetTypeFromProgID(_clsidOPCserver, _serverIP, false);

            if (svrComponenttype == null)
            {
                return(false);
            }
            try
            {
                _opcServerObj = Activator.CreateInstance(svrComponenttype);
            }
            catch (Exception err)
            {
                if (err.Message != null)
                {
                }
                return(false);
            }
            _opcServer  = (IOPCServer)_opcServerObj;
            _opcProp    = (IOPCItemProperties)_opcServerObj;
            _opcBrowser = (IOPCBrowseServerAddressSpace)_opcServerObj;
            Guid sinkguid = typeof(IOPCShutdown).GUID;

            ((IConnectionPointContainer)_opcServerObj).FindConnectionPoint(ref sinkguid, out _shutDownPoint);
            if (_shutDownPoint == null)
            {
                return(false);
            }
            try
            {
                _shutDownPoint.Advise(this, out _shutDownCookie);
            }
            catch (COMException err)
            {
                _opcServerObj  = null;
                _opcServer     = null;
                _shutDownPoint = null;
                return(false);
            }
            if (_metaGroups.Count > 0 && _groups.Count == 0)
            {
                foreach (var metagrp in _metaGroups)
                {
                    var grp = AddGroup(metagrp.Name, metagrp.ID, metagrp.UpdateRate, metagrp.DeadBand, metagrp.Active);
                    if (grp != null)
                    {
                        grp.AddItems(_dataServer.MetaDataList);
                    }
                }
            }
            return(true);
        }
Ejemplo n.º 5
0
        public void Disconnect()
        {
            int num;

            try
            {
                if (this.shutdowncpoint != null)
                {
                    if (this.shutdowncookie != 0)
                    {
                        try
                        {
                            this.shutdowncpoint.Unadvise(this.shutdowncookie);
                        }
                        catch (Exception exception)
                        {
                            LogHelper.Error("OPCTrendLib.OPCData.OPCServer", "Disconnect", exception);
                        }
                        this.shutdowncookie = 0;
                    }
                    num = Marshal.ReleaseComObject(this.shutdowncpoint);
                    this.shutdowncpoint = null;
                }
                this.cpointcontainer = null;
                this.ifBrowse        = null;
                this.ifItmProps      = null;
                this.ifCommon        = null;
                this.ifServer        = null;
                if (this.OPCserverObj != null)
                {
                    num = Marshal.ReleaseComObject(this.OPCserverObj);
                    this.OPCserverObj = null;
                }
            }
            catch (Exception exception)
            {
                LogHelper.Error("OPCTrendLib.OPCData.OPCServer", "Disconnect", exception);
            }
            finally
            {
                if (this.shutdowncpoint != null)
                {
                    this.shutdowncpoint = null;
                }
                if (this.OPCserverObj != null)
                {
                    this.OPCserverObj = null;
                }
            }
        }
Ejemplo n.º 6
0
        public void Connect(string clsidOPCserver)
        {
            this.Disconnect();
            Type typeFromProgID = Type.GetTypeFromProgID(clsidOPCserver);

            if (typeFromProgID == null)
            {
                Marshal.ThrowExceptionForHR(-1073479663);
            }
            this.OPCserverObj = Activator.CreateInstance(typeFromProgID);
            this.ifServer     = (IOPCServer)this.OPCserverObj;
            if (this.ifServer == null)
            {
                Marshal.ThrowExceptionForHR(-2147220992);
            }
            this.ifCommon        = (IOPCCommon)this.OPCserverObj;
            this.ifBrowse        = (IOPCBrowseServerAddressSpace)this.ifServer;
            this.ifItmProps      = (IOPCItemProperties)this.ifServer;
            this.cpointcontainer = (IConnectionPointContainer)this.OPCserverObj;
            this.AdviseIOPCShutdown();
        }
Ejemplo n.º 7
0
        public List <PropertyData> GetItemProperties(string szItemID)
        {
            IOPCItemProperties properties = (IOPCItemProperties)m_pOPCServer;
            uint   pdwCount       = 0;
            IntPtr ppvData        = IntPtr.Zero;
            IntPtr ppPropertyIDs  = IntPtr.Zero;
            IntPtr ppDescriptions = IntPtr.Zero;
            IntPtr ppvtDataTypes  = IntPtr.Zero;
            IntPtr ppErrors       = IntPtr.Zero;

            properties.QueryAvailableProperties(szItemID, out pdwCount, out ppPropertyIDs, out ppDescriptions, out ppvtDataTypes);

            int[] propertiesIDs = new int[pdwCount];
            Marshal.Copy(ppPropertyIDs, propertiesIDs, 0, (int)pdwCount);
            IntPtr pdwPropertyIDs = Marshal.AllocCoTaskMem((int)pdwCount * sizeof(int));

            Marshal.Copy(propertiesIDs, 0, pdwPropertyIDs, (int)pdwCount);

            IntPtr[] pDescriptions = new IntPtr[pdwCount];
            Marshal.Copy(ppDescriptions, pDescriptions, 0, (int)pdwCount);
            string[] descriptions = new string[pdwCount];
            for (int i = 0; i < pdwCount; i++)
            {
                string description;
                int    length = 0;
                description     = Marshal.PtrToStringAuto(pDescriptions[i]);
                length         += description.Length;
                descriptions[i] = description;
                Marshal.FreeCoTaskMem(pDescriptions[i]);
            }

            short[] propertyTypes = new short[pdwCount];
            Marshal.Copy(ppvtDataTypes, propertyTypes, 0, (int)pdwCount);

            var strPropertyTypes = from type in propertyTypes
                                   let sType = Converter.GetVTString((ushort)type)
                                               let typeSize = Converter.GetVTSize((ushort)type)
                                                              select sType + " : " + typeSize;

            string[] list = strPropertyTypes.ToArray();

            properties.GetItemProperties(szItemID, pdwCount, pdwPropertyIDs, out ppvData, out ppErrors);

            List <PropertyData> pValues = new List <PropertyData>();
            int   start = 0;
            short vt;

            for (int i = 0; i < pdwCount; i++)
            {
                int   propertyID = propertiesIDs[i];
                ulong value      = (ulong)Marshal.ReadInt64(ppvData + start * sizeof(ulong));
                int   sz         = Converter.GetVTSize((ushort)value);
                vt = propertyTypes[i];
                if (vt == 8)
                {
                    start++;
                    IntPtr[] strPtr = new IntPtr[1];
                    Marshal.Copy(ppvData + start * sizeof(long), strPtr, 0, 1);
                    string val = Marshal.PtrToStringUni(strPtr[0]);
                    pValues.Add(new PropertyData()
                    {
                        ID = propertyID, Name = descriptions[i], Value = val
                    });
                    start++;
                }
                else if (vt == 8197)
                {
                    start++;
                    IntPtr[] strPtr = new IntPtr[1];
                    Marshal.Copy(ppvData + start * sizeof(long), strPtr, 0, 1);
                    string val = Marshal.PtrToStringUni(strPtr[0]);
                    pValues.Add(new PropertyData()
                    {
                        ID = propertyID, Name = descriptions[i], Value = val
                    });
                    start++;
                }
                else if (vt == 4)
                {
                    start++;
                    value = (ulong)Marshal.ReadInt64(ppvData + start * sizeof(ulong));
                    object obj = Converter.GetPropertyValue(vt, value);
                    pValues.Add(new PropertyData()
                    {
                        ID = propertyID, Name = descriptions[i], Value = obj
                    });
                    start++;
                }
                else if (vt == 7)
                {
                    // Пока не разобрался с конвертированием данных в формат даты
                    // поэтому присваивается текущее значение даты и времени
                    start++;
                    IntPtr pDate = ppvData + start * sizeof(ulong);
                    //IntPtr pp = Marshal.AllocCoTaskMem(8);
                    //byte[] bb = new byte[8];
                    //Marshal.GetNativeVariantForObject(pDate, pp);
                    //Marshal.Copy(pp, bb, 0, 8);

                    Type type = typeof(DateTime);

                    long lValue = Marshal.ReadInt64(pDate);

                    uint lt = (uint)Marshal.ReadInt32(pDate, 4);
                    uint ht = (uint)Marshal.ReadInt32(pDate, 0);

                    lValue = ((long)ht << 32) + lt;
                    //DateTime ft = (DateTime)Marshal.PtrToStructure(pDate, type);

                    _FILETIME ft = new _FILETIME()
                    {
                        dwHighDateTime = ht, dwLowDateTime = lt
                    };
                    //DateTime dt = DateTime.FromBinary(lValue);
                    //string s = Converter.GetFTSting(ft);
                    //DateTime dt = new DateTime(lValue);
                    string strDate = DateTime.Now.ToString();
                    pValues.Add(new PropertyData()
                    {
                        ID = propertyID, Name = descriptions[i], Value = strDate
                    });
                    //Marshal.FreeCoTaskMem(pDate);
                    start++;
                }
                else
                {
                    start++;
                    value = (ulong)Marshal.ReadInt64(ppvData + start * sizeof(ulong));
                    pValues.Add(new PropertyData()
                    {
                        ID = propertyID, Name = descriptions[i], Value = value
                    });
                    start++;
                }
            }

            Marshal.FreeCoTaskMem(ppDescriptions);
            Marshal.FreeCoTaskMem(ppPropertyIDs);
            Marshal.FreeCoTaskMem(ppvtDataTypes);
            Marshal.FreeCoTaskMem(ppvData);
            Marshal.FreeCoTaskMem(ppErrors);

            return(pValues);
        }
Ejemplo n.º 8
0
        public void Disconnect()
        {
            if( ! (shutdowncpoint == null) )
            {
            if( shutdowncookie != 0 )
                {
                shutdowncpoint.Unadvise( shutdowncookie );
                shutdowncookie = 0;
                }
            int	rc = Marshal.ReleaseComObject( shutdowncpoint );
            shutdowncpoint = null;
            }

            cpointcontainer = null;
            ifBrowse		= null;
            ifItmProps		= null;
            ifCommon		= null;
            ifServer		= null;
            if( ! (OPCserverObj == null) )
            {
            int rc = Marshal.ReleaseComObject( OPCserverObj );
            OPCserverObj = null;
            }
        }
Ejemplo n.º 9
0
        public void Connect( string	clsidOPCserver )
        {
            Disconnect();

            Type	typeofOPCserver = Type.GetTypeFromProgID( clsidOPCserver );
            if( typeofOPCserver == null )
            Marshal.ThrowExceptionForHR( HRESULTS.OPC_E_NOTFOUND );

            OPCserverObj = Activator.CreateInstance( typeofOPCserver );
            ifServer = (IOPCServer) OPCserverObj;
            if( ifServer == null )
            Marshal.ThrowExceptionForHR( HRESULTS.CONNECT_E_NOCONNECTION );

            // connect all interfaces
            ifCommon		= (IOPCCommon)						OPCserverObj;
            ifBrowse		= (IOPCBrowseServerAddressSpace)	ifServer;
            ifItmProps		= (IOPCItemProperties)				ifServer;
            cpointcontainer	= (UCOMIConnectionPointContainer)	OPCserverObj;
            AdviseIOPCShutdown();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Reads the values of the properties from the server.
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="propertyIds">The list of property ids to read. All properties are read if null.</param>
        /// <returns>True if the element has properies.</returns>
        private DaValue[] ReadPropertyValues(string itemId, params int[] propertyIds)
        {
            string methodName = "IOPCItemProperties.GetItemProperties";

            // check for trivial case.
            if (propertyIds == null)
            {
                return(null);
            }

            int count = propertyIds.Length;

            DaValue[] results = new DaValue[count];

            // check for empty list.
            if (count == 0)
            {
                return(results);
            }

            // get the values from the server.
            IntPtr pValues = IntPtr.Zero;
            IntPtr pErrors = IntPtr.Zero;

            try
            {
                IOPCItemProperties server = BeginComCall <IOPCItemProperties>(methodName, true);

                server.GetItemProperties(
                    itemId,
                    count,
                    propertyIds,
                    out pValues,
                    out pErrors);
            }
            catch (Exception e)
            {
                if (ComUtils.IsUnknownError(e, ResultIds.E_FAIL, ResultIds.E_UNKNOWNITEMID, ResultIds.E_INVALIDITEMID))
                {
                    ComUtils.TraceComError(e, methodName);
                    return(null);
                }

                for (int ii = 0; ii < count; ii++)
                {
                    DaValue result = results[ii] = new DaValue();
                    result.Value     = null;
                    result.Quality   = OpcRcw.Da.Qualities.OPC_QUALITY_GOOD;
                    result.Timestamp = DateTime.UtcNow;
                    result.Error     = Marshal.GetHRForException(e);
                }

                return(results);
            }
            finally
            {
                EndComCall(methodName);
            }

            // unmarshal results.
            object[] values = ComUtils.GetVARIANTs(ref pValues, count, true);
            int[]    errors = ComUtils.GetInt32s(ref pErrors, count, true);

            for (int ii = 0; ii < count; ii++)
            {
                DaValue result = results[ii] = new DaValue();
                result.Value     = ComUtils.ProcessComValue(values[ii]);
                result.Quality   = OpcRcw.Da.Qualities.OPC_QUALITY_GOOD;
                result.Timestamp = DateTime.UtcNow;
                result.Error     = errors[ii];
            }

            return(results);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Read the available non-built in properties from the server.
        /// </summary>
        /// <param name="itemId">The item id.</param>
        /// <param name="updateCache">if set to <c>true</c> the cache is updated.</param>
        /// <returns>The array of properties.</returns>
        public DaProperty[] ReadAvailableProperties(string itemId, bool updateCache)
        {
            string methodName = "IOPCItemProperties.QueryAvailableProperties";

            // query for available properties.
            int count = 0;

            IntPtr pPropertyIds  = IntPtr.Zero;
            IntPtr pDescriptions = IntPtr.Zero;
            IntPtr pDataTypes    = IntPtr.Zero;

            try
            {
                IOPCItemProperties server = BeginComCall <IOPCItemProperties>(methodName, true);

                server.QueryAvailableProperties(
                    itemId,
                    out count,
                    out pPropertyIds,
                    out pDescriptions,
                    out pDataTypes);
            }
            catch (Exception e)
            {
                if (ComUtils.IsUnknownError(e, ResultIds.E_FAIL, ResultIds.E_UNKNOWNITEMID, ResultIds.E_INVALIDITEMID))
                {
                    ComUtils.TraceComError(e, methodName);
                }

                return(null);
            }
            finally
            {
                EndComCall(methodName);
            }

            // unmarshal results.
            int[]    propertyIds  = ComUtils.GetInt32s(ref pPropertyIds, count, true);
            string[] descriptions = ComUtils.GetUnicodeStrings(ref pDescriptions, count, true);
            short[]  datatype     = ComUtils.GetInt16s(ref pDataTypes, count, true);

            List <DaProperty> properties = new List <DaProperty>();

            for (int ii = 0; ii < count; ii++)
            {
                // do not return any of the built in properties.
                if (propertyIds[ii] <= PropertyIds.TimeZone)
                {
                    continue;
                }

                DaProperty property = new DaProperty();

                property.PropertyId = propertyIds[ii];
                property.Name       = descriptions[ii];
                property.DataType   = datatype[ii];

                properties.Add(property);
            }

            // fetch the item ids.
            if (properties.Count > 0)
            {
                DaProperty[] array = properties.ToArray();

                GetPropertyItemIds(itemId, array);

                // update the cache.
                if (updateCache)
                {
                    lock (m_cache)
                    {
                        DaElement element = null;

                        if (m_cache.TryGetValue(itemId, out element))
                        {
                            element.Properties = array;
                        }
                    }
                }

                return(array);
            }

            return(null);
        }