Ejemplo n.º 1
0
        /// <summary>
        /// This removes the OPC group items, opc group and disconnects and nulls the OPC server connection.
        /// </summary>
        public void Disconnect()
        {
            try
            {
                if (_opcserver == null)
                {
                    return;
                }
                if (!IsConnected())
                {
                    return;
                }

                agent.StoreEvent(DateTime.Now.ToString("s"), device, "power", "OFF", null, null, null, null, null, null);

                if (opcgroup != null)
                {
                    opcgroup.RemoveItems(handlesSrv, out aE);
                    opcgroup.Remove(false);
                }
                _opcserver.Disconnect();
                opcgroup   = null;
                _opcserver = null;
            }
            catch (Exception e)
            {
                LogMessage("OPC Disconnect Error: " + e.Message, Logger.ERROR);
                _opcserver = null;
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// 为OPC组OPC项List内与给定服务端句柄对应的OPC项写入数据,指定是否使用异步写入
 /// </summary>
 /// <param name="serverHandles">服务端句柄Array</param>
 /// <param name="using_async">是否使用异步写入</param>
 /// <param name="message">返回信息</param>
 /// <returns></returns>
 public bool WriteValues(Array serverHandles, bool using_async, out string message)
 {
     message = string.Empty;
     try
     {
         IEnumerable <int> temp = serverHandles == null || serverHandles.Length == 0 ? null : serverHandles.Cast <int>();
         Array             handles = GetServerHandles(temp), values = GetValues(temp);
         int itemCount = handles.Length - 1;
         if (!using_async)
         {
             OpcGroup.SyncWrite(itemCount, ref handles, ref values, out _errors);
         }
         else
         {
             OpcGroup.AsyncWrite(itemCount, ref handles, ref values, out _errors, _random.Next(1, 1000), out int cancelId);
         }
         GC.Collect();
     }
     catch (Exception ex)
     {
         message = string.Format("向名称为{0}的OPC组写入值失败:{1}", OpcGroup.Name, ex.Message);
         return(false);
     }
     return(true);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// This removes the OPC group iutem, opc group and disconnects and nulls the OPC server connection.
        /// </summary>
        public void Disconnect()
        {
            try
            {
                if (_opcserver == null)
                {
                    return;
                }
                if (!IsConnected())
                {
                    return;
                }

                if (opcgroup != null)
                {
                    opcgroup.RemoveItems(handlesSrv, out aE);
                    opcgroup.Remove(false);
                }
                _opcserver.Disconnect();
                opcgroup   = null;
                _opcserver = null;
            }
            catch (Exception e)
            {
                LogMessage("OPC Disconnect Error: " + e.Message, LogLevel.ERROR);
                _opcserver = null;
            }
        }
Ejemplo n.º 4
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder("OPCIST: ", 256);

            sb.AppendFormat("error=0x{0:x} hclt=0x{1:x}", Error, HandleClient);
            if (Error == HRESULTS.S_OK)
            {
                sb.AppendFormat(" val={0} time={1} qual=", DataValue, TimeStamp);
                sb.Append(OpcGroup.QualityToString(Quality));
            }

            return(sb.ToString());
        }
Ejemplo n.º 5
0
        public OpcGroup AddGroup(string groupName, bool setActive, int requestedUpdateRate,
                                 int[] biasTime, float[] percentDeadband, int localeID)
        {
            if (ifServer == null)
            {
                Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT);
            }

            OpcGroup grp = new OpcGroup(ref ifServer, false, groupName, setActive, requestedUpdateRate);

            grp.internalAdd(biasTime, percentDeadband, localeID);
            return(grp);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 为OPC组OPC项List内与给定服务端句柄对应的OPC项读取数据
        /// </summary>
        /// <param name="serverHandles">服务端句柄Array</param>
        /// <param name="message">返回信息</param>
        /// <returns></returns>
        public bool ReadValues(Array serverHandles, out string message)
        {
            message = string.Empty;
            Array values;

            try
            {
                IEnumerable <int> temp    = serverHandles == null || serverHandles.Length == 0 ? null : serverHandles.Cast <int>();
                Array             handles = GetServerHandles(temp);
                int itemCount             = handles.Length - 1;
                //OPCDataSource指定的是OPCCache或者OPCDevice
                //它的含义是当你执行同步读操作时,读取的数据来自OPC服务器的缓存还是来自硬件设备
                OpcGroup.SyncRead((short)OPCDataSource.OPCDevice, itemCount, ref handles, out values, out _errors, out object qualities, out object timeStamps);
                //假如至少读取到1个值,根据服务端句柄找到OPC项信息并更新值
                if (values.Length > 0)
                {
                    for (int i = 1; i <= values.Length; i++)
                    {
                        OpcItemInfo itemInfo = ListItemInfo.Find(item => item.ServerHandle.Equals(handles.GetValue(i)));
                        if (itemInfo != null)
                        {
                            itemInfo.Value = values.GetValue(i).ToString();
                            itemInfo.SetPropertyValue(_dataSource);
                        }
                    }
                }
                if (values.Length < itemCount)
                {
                    message = "至少有1个OPC项的值未找到";
                }
                GC.Collect();
            }
            catch (Exception ex)
            {
                message = string.Format("从名称为{0}的OPC组读取值失败:{1}", OpcGroup == null ? "null" : OpcGroup.Name, ex.Message);
                return(false);
            }
            return(values.Length > 0);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// This removes the OPC group items, opc group and disconnects and nulls the OPC server connection. 
        /// </summary>
        public void Disconnect()
        {
            try
            {

                if (_opcserver == null)
                    return;
                if (!IsConnected())
                    return;

                agent.StoreEvent(DateTime.Now.ToString("s"), device, "power", "OFF", null, null, null, null, null, null);

                if (opcgroup != null)
                {
                    opcgroup.RemoveItems(handlesSrv, out aE);
                    opcgroup.Remove(false);
                }
                _opcserver.Disconnect();
                opcgroup = null;
                _opcserver = null;
            }
            catch (Exception e)
            {
                LogMessage("OPC Disconnect Error: " + e.Message, Logger.ERROR);
                _opcserver = null;
            }
        }
Ejemplo n.º 8
0
        public void Connect()
        {
            int i;
            try
            {

            #if CREDENTIALS
                 LogMessage("Test if CNC Exe IsExecuting()", 1);
                if ((sCNCProcessName.Length > 0) && !IsExecuting(sOPCMachine, sCNCProcessName))
                {
                    throw new Exception("Cannot start OPC Server" + sCNCProcessName + " not running");

                }

                LogMessage("Connect to CNC", 1);

                // This is used as credentials to logon ont remote pc to see if CNC running
                System.Net.NetworkCredential credential;
                if (sDomain.Length > 0)
                    credential = new System.Net.NetworkCredential(sUser, sPassword, sDomain);
                else
                    credential = new System.Net.NetworkCredential(sUser, sPassword); // , sDomain);
            #endif
                _opcserver = new OpcServer();

                LogMessage("Attempt OPC Server Connection", Logger.DEBUG);
                // _opcserver will be null if failed...
                _opcserver.Connect(this.clsid, this.sIpAddress);

                LogMessage("Create OPC Group", Logger.DEBUG);
                opcgroup = _opcserver.AddGroup("OPCCSharp-Group", false, 900);

                if (opcgroup == null)
                    throw new Exception("Connect - AddGroup failed");

                // FIXME: this only works if OPC item exists.
                // Add items to OPC Group
                LogMessage("Add OPC Items", Logger.DEBUG);
                OPCItemResult[] itemresult;
                opcgroup.AddItems(tags, out itemresult);

                if (itemresult == null)
                    throw new Exception("Connect - OPC AddItems failed");

                LogMessage("Check OPC items for errors.", Logger.DEBUG);
                for (i = 0; i < itemresult.Length; i++)
                {
                    // If the OPC item failed - remove it from the tags to be updated.
                    if (HRESULTS.Failed(itemresult[i].Error))
                    {
                        LogMessage("OPC AddItems Error: " + tags[i].ItemID, Logger.DEBUG);
                        itemresult = (OPCItemResult[])RemoveAt(itemresult, i);
                        tags = (OPCItemDef[])RemoveAt(tags, i);
                        handlesSrv = (int[])RemoveAt(handlesSrv, i);
                        continue;

                    }
                    handlesSrv[i] = itemresult[i].HandleServer;
                }

                // read group
                LogMessage("OPC ReadStatus", Logger.DEBUG);
                ReadStatus();
                LogMessage("OPC ReadGroup", Logger.DEBUG);
                ReadGroup();
            }
            catch (Exception e)
            {
                LogMessage("OPC Connect Error: " + e.Message, Logger.ERROR);
                Disconnect();

            }
        }
Ejemplo n.º 9
0
        public void Connect()
        {
            int i;

            try
            {
#if CREDENTIALS
                LogMessage("Test if CNC Exe IsExecuting()", 1);
                if ((sCNCProcessName.Length > 0) && !IsExecuting(sOPCMachine, sCNCProcessName))
                {
                    throw new Exception("Cannot start OPC Server" + sCNCProcessName + " not running");
                }


                LogMessage("Connect to CNC", 1);

                // This is used as credentials to logon ont remote pc to see if CNC running
                System.Net.NetworkCredential credential;
                if (sDomain.Length > 0)
                {
                    credential = new System.Net.NetworkCredential(sUser, sPassword, sDomain);
                }
                else
                {
                    credential = new System.Net.NetworkCredential(sUser, sPassword); // , sDomain);
                }
#endif
                _opcserver = new OpcServer();

                LogMessage("Attempt OPC Server Connection", Logger.DEBUG);
                // _opcserver will be null if failed...
                _opcserver.Connect(this.clsid, this.sIpAddress);

                LogMessage("Create OPC Group", Logger.DEBUG);
                opcgroup = _opcserver.AddGroup("OPCCSharp-Group", false, 900);

                if (opcgroup == null)
                {
                    throw new Exception("Connect - AddGroup failed");
                }

                // FIXME: this only works if OPC item exists.
                // Add items to OPC Group
                LogMessage("Add OPC Items", Logger.DEBUG);
                OPCItemResult[] itemresult;
                opcgroup.AddItems(tags, out itemresult);

                if (itemresult == null)
                {
                    throw new Exception("Connect - OPC AddItems failed");
                }

                LogMessage("Check OPC items for errors.", Logger.DEBUG);
                for (i = 0; i < itemresult.Length; i++)
                {
                    // If the OPC item failed - remove it from the tags to be updated.
                    if (HRESULTS.Failed(itemresult[i].Error))
                    {
                        LogMessage("OPC AddItems Error: " + tags[i].ItemID, Logger.DEBUG);
                        itemresult = (OPCItemResult[])RemoveAt(itemresult, i);
                        tags       = (OPCItemDef[])RemoveAt(tags, i);
                        handlesSrv = (int[])RemoveAt(handlesSrv, i);
                        continue;
                    }
                    handlesSrv[i] = itemresult[i].HandleServer;
                }

                // read group
                LogMessage("OPC ReadStatus", Logger.DEBUG);
                ReadStatus();
                LogMessage("OPC ReadGroup", Logger.DEBUG);
                ReadGroup();
            }
            catch (Exception e)
            {
                LogMessage("OPC Connect Error: " + e.Message, Logger.ERROR);
                Disconnect();
            }
        }
Ejemplo n.º 10
0
        public OpcGroup AddGroup(string groupName, bool setActive, int requestedUpdateRate,
                                    int[] biasTime, float[] percentDeadband, int localeID)
        {
            if (ifServer == null)
                Marshal.ThrowExceptionForHR(HRESULTS.E_ABORT);

            OpcGroup grp = new OpcGroup(ref ifServer, false, groupName, setActive, requestedUpdateRate);
            grp.internalAdd(biasTime, percentDeadband, localeID);
            return grp;
        }