Esempio n. 1
0
        /// <summary>
        /// Připojení k OPC serveru. Volající musí ošetřit případnou výjimku
        /// </summary>
        /// <param name="serverUrl">Adresa OPC serveru (např "opcda://localhost/OPC.SimaticNET.DP")</param>
        public void pripojit(string serverUrl)
        {
            /*    //Odpojení od serveru
             * if (server != null)
             *  try
             *  {
             *      server.Disconnect();   //Zde se to v některých případech zasekne, tak jsem to raději zrušil a při opětovném připojení si OPC server inkrementuje počet připojených klientů. Možná by to šlo přes timer...
             *  }
             *  catch
             *  {
             *  }*/

            //Připojení k serveru
            string strErr = "";

            try
            {
                strErr = "Chyba při připojování na server. ";
                Opc.URL url;
                url = new Opc.URL(serverUrl);
                OpcCom.Factory fact = new OpcCom.Factory();
                server = new Opc.Da.Server(fact, null);
                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
                strErr = "Chyba při vytváření groups. ";
                vytvoritGroups(server);
                strErr = "Chyba při vytváření items. ";
                vytvoritItems();
            }
            catch (Exception ex)
            {
                throw new Exception(strErr + ex.Message);
            }
        }
Esempio n. 2
0
        public void Connect(string serverName)
        {
            /* When the factory creates an HDA server, it passes along 2 parameters:
             *    SerializationInfo info
             *    StreamingContext context
             *
             * The Factory class casts the COM object (pointing to the HDA server) to the IServer interface.
             * All calls to the interface or proxied to the COM object.
             */
            Opc.URL url = new Opc.URL(String.Format("opchda://localhost/{0}", serverName));
            OpcCom.Factory fact = new OpcCom.Factory();
            _hdaServer = new Opc.Hda.Server(fact, url);

            try
            {
                _hdaServer.Connect();
                Console.WriteLine(String.Format("Connect to server {0}", serverName));
            }
            catch(Opc.ConnectFailedException opcConnExc)
            {
                Console.WriteLine(String.Format("Could not connect to server {0}", serverName));
                Console.WriteLine(opcConnExc.ToString());
            }

            Console.WriteLine("Are we connected? " + _hdaServer.IsConnected);
        }
Esempio n. 3
0
        public Boolean Connect()
        {
            // Create a server object and connect to the TwinCATOpcServer
            Opc.URL url = new Opc.URL(opcServerEndpoint);

            OpcCom.Factory fact = new OpcCom.Factory();
            server = new Opc.Da.Server(fact, null);
            server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

            // Create a group
            Opc.Da.Subscription group;

            foreach (BrowsableGroup BrowsableGroup in browsableGroups)
            {
                Opc.Da.SubscriptionState groupState = new SubscriptionState();
                groupState.Name = BrowsableGroup.GroupName;

                groupState.Active = true;
                group             = (Opc.Da.Subscription)server.CreateSubscription(groupState);
                Opc.Da.Item[] items = BrowsableGroup.produceItemsFromNodes();

                items = group.AddItems(items);
                EnableDataChangedCallback(group);
                //todo:
                //EnableDataReadCallback(group);
                //todo:
                //EnableDataWriteCallback(group, BrowsableGroup.produceValueToWrite(items[0],34.0) );
            }


            return(false);
        }
Esempio n. 4
0
        public OpcIoDevice(string options)
        {
            _url = new URL(options);
            var fact = new OpcCom.Factory();

            _server = new Server(fact, null);
        }
Esempio n. 5
0
        /// <summary>
        /// Server connection procedure
        /// </summary>
        /// <param name="urlString">OPC server URL in string format</param>
        /// <returns>isConnected</returns>
        public bool ConnectServer(string urlString)
        {
            isConnected = false;

            this.url = new Opc.URL(urlString);
            factory  = new OpcCom.Factory();
            server   = new Opc.Da.Server(factory, url);

            try
            {
                selectedServer = selectedServer ?? new mServerItem(true);
                server.Connect();
                if (isConnected = server.IsConnected)
                {
                    OnReportMessage(0, "Server is connected");

                    server.ServerShutdown -= server_ServerShutdown;
                    server.ServerShutdown += server_ServerShutdown;
                    RefreshServerStatus();
                }
                else
                {
                    OnReportMessage("Server connection fail, unknown error");
                }
            }
            catch (Exception ex)
            {
                OnReportMessage(ex.Message.ToString());
            }

            return(isConnected);
        }
        public void Connect(string serverName)
        {
            /* When the factory creates an HDA server, it passes along 2 parameters:
             *    SerializationInfo info
             *    StreamingContext context
             *
             * The Factory class casts the COM object (pointing to the HDA server) to the IServer interface.
             * All calls to the interface or proxied to the COM object.
             */
            Opc.URL        url  = new Opc.URL(String.Format("opchda://localhost/{0}", serverName));
            OpcCom.Factory fact = new OpcCom.Factory();
            _hdaServer = new Opc.Hda.Server(fact, url);

            try
            {
                _hdaServer.Connect();
                Console.WriteLine(String.Format("Connect to server {0}", serverName));
            }
            catch (Opc.ConnectFailedException opcConnExc)
            {
                Console.WriteLine(String.Format("Could not connect to server {0}", serverName));
                Console.WriteLine(opcConnExc.ToString());
            }

            Console.WriteLine("Are we connected? " + _hdaServer.IsConnected);
        }
Esempio n. 7
0
        public RFID ReadTagsRFID(bool identify_card)
        {
            try
            {
                Opc.Da.Server  server = null;
                OpcCom.Factory fact   = new OpcCom.Factory();
                server = new Opc.Da.Server(fact, null);

                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                //
                Opc.Da.Subscription      group;
                Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState();
                groupState.Name   = "RFID";
                groupState.Active = true;
                group             = (Opc.Da.Subscription)server.CreateSubscription(groupState);

                //добавление айтемов в группу
                Opc.Da.Item[] items = new Opc.Da.Item[2];
                items[0]          = new Opc.Da.Item();
                items[0].ItemName = "ZREADER.RFID_reader.part1";
                items[1]          = new Opc.Da.Item();
                items[1].ItemName = "ZREADER.RFID_reader.part2";
                items             = group.AddItems(items);
                //List<oldRFID> result_list = new List<oldRFID>();
                ItemValueResult[] res = group.Read(items);
                RFID       rfid       = new RFID();
                EFazsCards ef_card    = new EFazsCards();
                if (res != null)
                {
                    //UInt16? part1 = res[0].Value != null ? res[0].Value as UInt16? : 37;
                    //UInt16? part2 = res[1].Value != null ? res[1].Value as UInt16? : 50907;
                    UInt16?part1 = res[0].Value != null ? res[0].Value as UInt16? : null;
                    UInt16?part2 = res[1].Value != null ? res[1].Value as UInt16? : null;
                    if (part1 != null && part2 != null)
                    {
                        rfid.part1 = part1;
                        rfid.part2 = part2;
                        if (identify_card)
                        {
                            int code1 = int.Parse(part1.ToString());
                            int code2 = int.Parse(part2.ToString());
                            String.Format("Определим ID=карты code1={0}, code2={1}", code1, code2).SaveInformation();
                            azsCards card = ef_card.Get().Where(c => c.Number == (code1).ToString("00") + "," + (code2).ToString("00000")).FirstOrDefault();
                            if (card == null)
                            {
                                card = ef_card.Get().Where(c => c.Number == (code1).ToString("000") + "," + (code2).ToString("00000")).FirstOrDefault();
                            }
                            rfid.card = card;
                        }
                    }
                }
                return(rfid);
            }
            catch (Exception e)
            {
                String.Format("Ошибка выполнения метода ReadTagsRFID(identify_card={0})", identify_card).SaveError(e);
                return(null);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Tries to connect to the server.
        /// </summary>
        public bool Connect(string serverurl)
        {
            if (String.IsNullOrEmpty(serverurl))
            {
                throw new Exception(String.Format("Server url '{0}' is not valid", serverurl));
            }

            Opc.URL        url  = new Opc.URL(serverurl);
            OpcCom.Factory fact = new OpcCom.Factory();
            Server = new Opc.Da.Server(fact, null);
            try
            {
                Server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
            }
            catch (Exception ex)
            {
                _error.Append(ex.ToString());
                if (ex.InnerException != null)
                {
                    _error.Append(ex.InnerException.ToString());
                }
                return(false);
            }
            return(true);
        }
Esempio n. 9
0
        public static ItemValueResult[] RsLinx_OPC_Client_Read_Array(string ItemName, int Length)
        {
            try
            {
                //Creo un istanza di OPC.server
                Opc.Da.Server server;
                //Parametro necessario alla connect
                OpcCom.Factory fact = new OpcCom.Factory();
                //Creo un istanza di Sottoscrizione
                Opc.Da.Subscription groupRead;
                //Creo un istanza di SubscriptionState, utile per controllare lo stato della sottoscrizione
                Opc.Da.SubscriptionState groupState;
                //Creo un array di OPC.Da.Item
                Opc.Da.Item[] items = new Opc.Da.Item[1];
                //Setto factory e url del server, come url utilizzo quello del RSLinx OPC Server
                server     = new Opc.Da.Server(fact, null);
                server.Url = new Opc.URL(Url);

                //Connetto il server
                server.Connect();

                //Istanzio la sottoscrizione
                groupState            = new Opc.Da.SubscriptionState();
                groupState.Name       = "Group";
                groupState.UpdateRate = UpdateRate; //Setto il tempo di Refresh del gruppo
                groupState.Active     = true;       //Questo valore deve essere true se voglio aver la possibilità di leggere
                //Creo il gruppo sul server
                groupRead = (Opc.Da.Subscription)server.CreateSubscription(groupState);
                //Istanzio l'Item
                items[0] = new Opc.Da.Item();
                //Gli do il nome (Rockwell utilizza questa formzattazione dei nomi per gli array
                //[NomeTopicOPC]NomeTag,LDimensioneArray es. [MyOPCTopic]Posizione,L50)
                items[0].ItemName = $"{ItemName},L{Length}";

                //Aggiungo l'oggetto al gruppo
                items = groupRead.AddItems(items);
                //Leggo il valore dell'item aggiunto
                ItemValueResult[] Ritorno = groupRead.Read(items);

                //Controllo che la lettura dell'array sia andata a buon fine, se non è così lancio un'eccezione
                if (!Ritorno[0].ResultID.Name.Name.Equals("S_OK"))
                {
                    throw new System.Exception("Errore lettura OPC Tag");
                }
                return(groupRead.Read(items));
            }
            catch (Exception ex)
            {
                //Se viene lanciata un'eccezione ritorno un array di ItemValueResult con il primo che ha valore -1 e mostro un Messagebox con l'errore
                MessageBox.Show(ex.Message);
                ItemValueResult[] Errore = new ItemValueResult[1];
                Errore[0] = new ItemValueResult();
                float[] Err = { (float)-1, (float)-1 };
                Errore[0].Value = Err;
                return(Errore);
            }
        }
Esempio n. 10
0
        public void conectarOpc()
        {
            try
            {
                fact       = new OpcCom.Factory();
                server     = new Opc.Da.Server(fact, null);
                server.Url = new Opc.URL("opcda://KeStudio.Opc.LC.1.96");
                server.Connect();

                MessageBox.Show("OPC SERVER CONECTADO COM SUCESSO");
            }
            catch (Exception exc)
            {
                MessageBox.Show("ERRO AO SE CONECTAR COM O OPC SERVER");
            }
        }
Esempio n. 11
0
        public Boolean Connect()
        {
            // Create a server object and connects to
            Opc.URL url = new Opc.URL(opcServerEndpoint);

            Factory fact = new Factory();

            server = new Server(fact, null);
            server.Connect(url, new Opc.ConnectData(new NetworkCredential()));

            string root = getRootName(server);

            recursiveTreeFill(server, root);

            subscribeToNodes(root);

            return(false);
        }
Esempio n. 12
0
        /// <summary>
        /// 连接OPC服务器
        /// </summary>
        /// <returns></returns>
        public bool ConnectServer()
        {
            _ServerStatus = "Connecting";

            //先PING地址
            string strIP = _ServerAddress.Split('/')[0];

            if (strIP.ToLower() != "127.0.0.1" && strIP.ToLower() != "localhost")
            {
                Ping      ping = new Ping();
                PingReply pr   = ping.Send(strIP);
                if (pr.Status != IPStatus.Success)
                {
                    EnqueueLog("网络出现错误:" + pr.Status.ToString());
                    //LogClass.Logs.Enqueue("网络出现错误:" + pr.Status.ToString());
                    return(false);
                }
            }

            OpcCom.Factory fac = new OpcCom.Factory(false);
            opcserver = new Opc.Da.Server(fac, new Opc.URL(string.Format(@"opcda://{0}", _ServerAddress)));

            try
            {
                opcserver.Connect();
                opcserver.ServerShutdown += new Opc.ServerShutdownEventHandler(opcserver_ServerShutdown);

                Opc.Da.SubscriptionState ss = new Opc.Da.SubscriptionState();
                ss.Active           = true;
                opcSub              = opcserver.CreateSubscription(ss);
                _ServerStatus       = "Connected";
                opcSub.DataChanged += new Opc.Da.DataChangedEventHandler(opcSub_DataChanged);

                return(true);
            }
            catch (Exception ex)
            {
                EnqueueLog("连接OPC服务器出现错误:" + ex.Message);
                //LogClass.Logs.Enqueue("连接OPC服务器出现错误:" + ex.Message);
                _ErrorMessage = ex.Message;
                _ServerStatus = "NotConnected";
                return(false);
            }
        }
Esempio n. 13
0
 /// <summary>
 /// 连接HDA服务器
 /// </summary>
 /// <param name="hostName">主机名称或者IP</param>
 /// <param name="serverName">服务器名称</param>
 public bool Connect()
 {
     Opc.URL        url  = new Opc.URL(String.Format("opchda://" + _hostName + @"/{0}", _serverName));
     OpcCom.Factory fact = new OpcCom.Factory();
     _hdaServer = new Opc.Hda.Server(fact, url);
     try
     {
         _hdaServer.Connect();
         //Console.WriteLine(String.Format("Connect to server {0}", serverName));
     }
     catch (Opc.ConnectFailedException opcConnExc)
     {
         Console.WriteLine(String.Format("Could not connect to server {0}", _serverName));
         Console.WriteLine(opcConnExc.ToString());
         //return false;
     }
     return(_hdaServer.IsConnected ? true : false);
     //Console.WriteLine("Are we connected? " + _hdaServer.IsConnected);
 }
Esempio n. 14
0
        /// <summary>
        /// Tries to connect to the server.
        /// </summary>
        private void Connect()
        {
            Opc.URL        url  = new Opc.URL("opcda://localhost/" + _serverName);
            OpcCom.Factory fact = new OpcCom.Factory();
            _server = new Opc.Da.Server(fact, null);

            try
            {
                _server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
            }
            catch (Exception ex)
            {
                _error.Append(ex.ToString());
                if (ex.InnerException != null)
                {
                    _error.Append(ex.InnerException.ToString());
                }
            }
        }
Esempio n. 15
0
        public void Connect()
        {
            try
            {
                XmlElement docRoot = _xmlDocument.DocumentElement;
                foreach (XmlNode driverNode in docRoot.ChildNodes)
                {
                    if (driverNode.Attributes["Id"].Value.Equals("6A1B8105-BD9A-4658-870F-D35D4029C928"))
                    {
                        OpcCom.Factory fact = new OpcCom.Factory();
                        _opcDaServer = new Opc.Da.Server(fact, null);

                        Opc.URL url = new Opc.URL(driverNode.Attributes["OpcServerUrl"].Value);
                        _opcDaServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 16
0
        public override bool Initialize(string connectionString, int newPollerId)
        {
            bool result = false;

            ConnString = connectionString;

            try
            {
                PollerId = newPollerId;
                url      = new Opc.URL(connectionString);
                server   = null;
                var fact = new OpcCom.Factory();
                server = new Opc.Da.Server(fact, null);
                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
                server.ServerShutdown += Shutdown;
                _tags = new List <Opc.Da.Item>();
                Browse();

                _groupWriteState        = new Opc.Da.SubscriptionState();
                _groupWriteState.Name   = "GroupWrite";
                _groupWriteState.Active = false;

                groupWrite = (Opc.Da.Subscription)server.CreateSubscription(_groupWriteState);
                Activated  = true;
                logger.Logged("Info", "Состояние сервера: " + server.GetStatus().StatusInfo, "", "");
                result = true;
            }
            catch (Exception ex)
            {
                logger.Logged("Error", "Не удалось подключиться к OPC DA серверу " + connectionString + ": " + ex.Message, "", "");
                // logger.Logged("Warn", "Повторная попытка через 5 секунд...", "", "");
                //Thread.Sleep(5000);
            }

            return(result);
        }
Esempio n. 17
0
 public Opc.Server[] GetAvailableServers(Specification specification, string host, ConnectData connectData)
 {
     Opc.Server[] serverArray;
     lock (this)
     {
         NetworkCredential credential = (connectData != null) ? connectData.GetCredential(null, null) : null;
         this.m_server = (IOPCServerList2)Interop.CreateInstance(CLSID, host, credential);
         this.m_host   = host;
         try
         {
             ArrayList    list        = new ArrayList();
             Guid         guid        = new Guid(specification.ID);
             IOPCEnumGUID ppenumClsid = null;
             Guid[]       rgcatidImpl = new Guid[] { guid };
             this.m_server.EnumClassesOfCategories(1, rgcatidImpl, 0, null, out ppenumClsid);
             Guid[] guidArray = this.ReadClasses(ppenumClsid);
             Interop.ReleaseServer(ppenumClsid);
             ppenumClsid = null;
             foreach (Guid guid2 in guidArray)
             {
                 OpcCom.Factory factory = new OpcCom.Factory();
                 try
                 {
                     URL        url    = this.CreateUrl(specification, guid2);
                     Opc.Server server = null;
                     if (specification == Specification.COM_DA_30)
                     {
                         server = new Opc.Da.Server(factory, url);
                     }
                     else if (specification == Specification.COM_DA_20)
                     {
                         server = new Opc.Da.Server(factory, url);
                     }
                     else if (specification == Specification.COM_AE_10)
                     {
                         server = new Opc.Ae.Server(factory, url);
                     }
                     else if (specification == Specification.COM_HDA_10)
                     {
                         server = new Opc.Hda.Server(factory, url);
                     }
                     else if (specification == Specification.COM_DX_10)
                     {
                         server = new Opc.Dx.Server(factory, url);
                     }
                     list.Add(server);
                 }
                 catch (Exception)
                 {
                 }
             }
             serverArray = (Opc.Server[])list.ToArray(typeof(Opc.Server));
         }
         finally
         {
             Interop.ReleaseServer(this.m_server);
             this.m_server = null;
         }
     }
     return(serverArray);
 }
Esempio n. 18
0
        public Tank ReadTagsTank()
        {
            try
            {
                Opc.Da.Server  server = null;
                OpcCom.Factory fact   = new OpcCom.Factory();
                server = new Opc.Da.Server(fact, null);

                server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));

                //
                Opc.Da.Subscription      group;
                Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState();
                groupState.Name   = "Tank";
                groupState.Active = true;
                group             = (Opc.Da.Subscription)server.CreateSubscription(groupState);

                //добавление айтемов в группу
                Opc.Da.Item[] items = new Opc.Da.Item[7];
                items[0]          = new Opc.Da.Item();
                items[0].ItemName = "Gamma.UIP1.Dens.Dens__1_";
                items[1]          = new Opc.Da.Item();
                items[1].ItemName = "Gamma.UIP1.Mass.Mass__1_";
                items[2]          = new Opc.Da.Item();
                items[2].ItemName = "Gamma.UIP1.OilLevel.OilLevel__1_";
                items[3]          = new Opc.Da.Item();
                items[3].ItemName = "Gamma.UIP1.Temper.Temper__1_";
                items[4]          = new Opc.Da.Item();
                items[4].ItemName = "Gamma.UIP1.volume.volume__1_";
                items[5]          = new Opc.Da.Item();
                items[5].ItemName = "Gamma.UIP1.Water.Water__1_";
                items[6]          = new Opc.Da.Item();
                items[6].ItemName = "Gamma.UIP1.WaterVol.WaterVol__1_";

                items = group.AddItems(items);


                ItemValueResult[] res = group.Read(items);
                if (res != null && res.Count() > 0)
                {
                    Tank tank = new Tank()
                    {
                        dens         = res[0].Value != null ? res[0].Value as double? : null,
                        mass         = res[1].Value != null ? res[1].Value as double? : null,
                        level        = res[2].Value != null ? res[2].Value as double? : null,
                        temp         = res[3].Value != null ? res[3].Value as double? : null, // преабразуем
                        volume       = res[4].Value != null ? res[4].Value as double? : null,
                        water_level  = res[5].Value != null ? res[5].Value as double? : null, // преабразуем
                        water_volume = res[6].Value != null ? res[6].Value as double? : null,
                        //dens = res[0].Value != null ? res[0].Value as double? : 790,
                        //mass = res[1].Value != null ? res[1].Value as double? : 10000,
                        //level = res[2].Value != null ? res[2].Value as double? : 0,
                        //temp = res[3].Value != null ? res[3].Value as double? : 20.4, // преабразуем
                        //volume = res[4].Value != null ? res[4].Value as double? : 11000,
                        //water_level = res[5].Value != null ? res[5].Value as double? : 0.1, // преабразуем
                        //water_volume = res[6].Value != null ? res[6].Value as double? : 0.1,
                    };
                    return(tank);
                }
                return(null);
            }
            catch (Exception e)
            {
                String.Format("Ошибка выполнения метода ReadTagsTank()").SaveError(e);
                return(null);
            }
        }
Esempio n. 19
0
        public void Connect_OPC()
        {
            //Console.WriteLine("Connect_OPC");
            try
            {
                servername = Pub_dtTSetting.Rows[0][2].ToString();
                if (servername != "")
                {
                    Opc.URL        url       = new Opc.URL("opcda://" + Pub_dtTSetting.Rows[0][1].ToString() + "/" + Pub_dtTSetting.Rows[0][2].ToString());
                    Opc.Da.Server  serveropc = null;
                    OpcCom.Factory fact      = new OpcCom.Factory();
                    //Kepware.KEPServerEX.V6
                    Opc.Da.ServerStatus serverStatus = new Opc.Da.ServerStatus();
                    //serveropc = new Opc.Da.Server(fact, null);
                    serveropc = new Opc.Da.Server(fact, url);
                    System.Net.NetworkCredential mCredentials = new System.Net.NetworkCredential();
                    Opc.ConnectData mConnectData = new Opc.ConnectData(mCredentials);

                    try
                    {
                        //2nd: Connect to the created server
                        serveropc.Connect(url, mConnectData);
#if DEBUG_ERROR
#warning   you must install RSLinx server OR Kepware.KEPServerEX.V6 for install important .dll then you can easy test with Kepware.KEPServerEX.V6
#endif
                        //serveropc.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential())); //ไม่เปิดเซิฟเวอ จะติดตรงนี้
                        serverStatus            = serveropc.GetStatus();
                        servercurrent_status    = serverStatus.ServerState.ToString();
                        ServerStatusInTime.Text = serverStatus.ServerState.ToString();

                        //Append Log file if server Status running-------------------------------------------------
                        string CompareServerstatus = "running";
                        if (serverStatus.ServerState.ToString() == CompareServerstatus)
                        {
                            if (PortStatus.Text.ToString() == "Stop")
                            {
                                //StartPort.Visible = true;
                            }
                            string timeinlog = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd HH:mm:ss= ");
                            if (write_log == false) //First Time Write Log
                            {
                                using (StreamWriter sw = File.AppendText(AppendFilepath))
                                {
                                    sw.WriteLine(timeinlog + Pub_dtTSetting.Rows[0][2].ToString() + " DCOM security The operation completed successfully");
                                    sw.WriteLine(timeinlog + "Connected to OPC server");
                                    sw.WriteLine(timeinlog + "MyGroup Added group to server The operation completed successfully");
                                }
                            }
                            write_log = true; // 1 mean don't write agian use in ReadCompleteCallback
                        }

                        //----------------------------------------------------------------

                        //3rd Create a group if items
                        Opc.Da.SubscriptionState groupState = new Opc.Da.SubscriptionState();
                        groupState.Name   = "group";
                        groupState.Active = true;
                        group             = (Opc.Da.Subscription)serveropc.CreateSubscription(groupState);

                        // add items to the group

                        Opc.Da.Item[] items = new Opc.Da.Item[Pub_dtTTAGMapping.Rows.Count];

                        //Add item by DataTable From Function Get_TagMapping
                        for (int index_Tag = 0; index_Tag < Pub_dtTTAGMapping.Rows.Count; index_Tag++)
                        {
                            items[index_Tag] = new Opc.Da.Item();
                            //Tag_Name
                            items[index_Tag].ItemName = Pub_dtTTAGMapping.Rows[index_Tag][2].ToString();//Pub_dtTTAGMapping.Rows[Row][Column]
                        }
                        items = group.AddItems(items);
                        this.timerModbus.Interval  = (Convert.ToInt32(Pub_dtTSetting.Rows[0][5]) * 100);
                        this.timerModbus.AutoReset = false;
                        this.timerModbus.Start();
                    }//end try
                    catch (Exception)
                    {
                        servercurrent_status = "Stop";
                        //Exception Server Not Run
                        string timeinlog = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd HH:mm:ss= ");
                        write_log = false; // 1 mean don't write agian use in ReadCompleteCallback
                        ServerStatusInTime.Text = "Stop";

                        using (StreamWriter sw = File.AppendText(AppendFilepath))
                        {
                            //Pub_dtTSetting.Rows[0][2].ToString() => ServerName
                            sw.WriteLine(timeinlog + Pub_dtTSetting.Rows[0][2].ToString() + " DCOM security The operation completed successfully");
                            sw.WriteLine(timeinlog + "Unable to connect to OPC server");
                            sw.WriteLine(timeinlog + "MyGroup Unable to add group to server Unspecified error");
                            sw.WriteLine(timeinlog + "Service will be Reconnect To OPC Server With in 1 minutes");
                        }
                        this.timerModbus.Interval  = (Convert.ToInt32(Pub_dtTSetting.Rows[0][5])) * 1000;
                        this.timerModbus.AutoReset = false;
                        this.timerModbus.Start();
                    } //end catch
                }     //end if
            }
            catch (Exception ex)
            {
                using (StreamWriter sw = File.AppendText(indebuglogFolderPath + "\\" + filename + ".txt"))
                {
                    sw.WriteLine("ERROR : " + ex);
                }
            }
            // 1st: Create a server object and connect to the RSLinx OPC Server
        }
Esempio n. 20
0
        public void OnCheckOpc()
        {
            if (_model.VerificationList != null && _model.VerificationList.Any())
            {
                _opcServers = new Dictionary <Guid, Opc.Da.Server>();
                foreach (var server in _model.VerificationList.Where(x => !string.IsNullOrEmpty(x.Connectionstring)))
                {
                    // 1st: Create a server object and connect to the RSLinx OPC Server
                    //var url = new Opc.URL("opcda://10.85.5.111/Infinity.OPCServer");
                    var url       = new Opc.URL(server.Connectionstring);
                    var fact      = new OpcCom.Factory();
                    var opcServer = new Opc.Da.Server(fact, null);

                    //2nd: Connect to the created server

                    try
                    {
                        try
                        {
                            opcServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
                        }
                        catch
                        {
                            MessageBox.Show("Сервер " + url + " недостпуен.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        var id = server.Id;
                        _opcServers.Add(id, opcServer);
                        if (server.OpcStatements != null && server.OpcStatements.Any())
                        {
                            //3rd Create a group if items
                            var groupState = new Opc.Da.SubscriptionState();
                            groupState.Name       = "Group of " + server.Caption;
                            groupState.UpdateRate = 1000;                                                      // this isthe time between every reads from OPC server
                            groupState.Active     = true;                                                      //this must be true if you the group has to read value
                            var groupRead = (Opc.Da.Subscription)opcServer.CreateSubscription(groupState);
                            groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(TagValue_DataChanged); //callback when the data are readed
                            var items = new List <Opc.Da.Item>();


                            foreach (var tag in server.OpcStatements)
                            {
                                items.Add(new Opc.Da.Item
                                {
                                    ItemName     = tag.TagValue,
                                    ClientHandle = id
                                });
                            }

                            //// add items to the group    (in Rockwell names are identified like [Name of PLC in the server]Block of word:number of word,number of consecutive readed words)

                            ////items[0] = new Opc.Da.Item();
                            ////items[0].ItemName = "NPS_Berez2.DPS_1.Scr.Scr1";//this reads 2 word (short - 16 bit)
                            ////items[1] = new Opc.Da.Item();
                            ////items[1].ItemName = "SIKN_592.BIK.Vmom";//this reads an array of 10 words (short[])
                            //items[0] = new Opc.Da.Item();
                            //items[0].ItemName = "AK.SIBNP.R_Uraj.NPS_Berez2.DPS_1.Scr.Scr1";//this reads 2 word (short - 16 bit)
                            //items[0].ClientHandle = Guid.NewGuid();
                            ////items[1] = new Opc.Da.Item();
                            ////items[1].ItemName = "AK.SIBNP.R_Uraj.SERVICE.WebRouter_AK.SIBNP.R_Uraj.StatusInt.Cause";//this reads an array of 10 words (short[])
                            ////items[2] = new Opc.Da.Item();
                            ////items[2].ItemName = "AK.SIBNP.R_Uraj.Offline_14";//this read a 2 word array (but in the plc the are used as bits so you have to mask them)
                            ////items[3] = new Opc.Da.Item();
                            ////items[3].ItemName = "AK.SIBNP.R_Uraj.Test_14";//this read a 2 word array (but in the plc the are used as bits so you have to mask them)

                            groupRead.AddItems(items.ToArray());
                        }
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("Ошибка при чтении тега OPC с сервера " + url + ". " + e.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
Esempio n. 21
0
 public PLCWrapper(string url)
 {
     this.opcURL = url;
     OpcCom.Factory fact = new OpcCom.Factory();
     opcServer = new Opc.Da.Server(fact, null);
 }
Esempio n. 22
0
 public OpcIoDevice(string options)
 {
     _url = new URL(options);
     var fact = new OpcCom.Factory();
     _server = new Server(fact, null);
 }
Esempio n. 23
0
		public void Connect()
		{
			try
			{
				XmlElement docRoot = _xmlDocument.DocumentElement;
				foreach (XmlNode driverNode in docRoot.ChildNodes)
				{
					if (driverNode.Attributes["Id"].Value.Equals("6A1B8105-BD9A-4658-870F-D35D4029C928"))
					{
						OpcCom.Factory fact = new OpcCom.Factory();
						_opcDaServer = new Opc.Da.Server(fact, null);

						Opc.URL url = new Opc.URL(driverNode.Attributes["OpcServerUrl"].Value);
						_opcDaServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
					}
				}
			}
			catch (Exception ex)
			{
				Console.WriteLine(ex.Message);
			}
		}
Esempio n. 24
0
        // Connect to OPC HDA server
        public bool Connect(string HostName, string ServerName)
        {
            var url = new Opc.URL();

            url.Scheme   = Opc.UrlScheme.HDA;
            url.HostName = HostName;
            url.Path     = ServerName;

            try {
                var fact = new OpcCom.Factory();
                if ((_OPCServer != null) && (!_OPCServer.IsConnected))
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "_OPCServer is disconnected, disposing object");
                    //Unfortunately, in case of lost connection simply calling .Connect() doesn't work :(
                    //Let's try to recreate the object from scratch
                    _OPCServer.Dispose();
                    _OPCServer = null;
                }

                if (_OPCServer == null)
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "_OPCServer is null, creating new object");
                    _OPCServer = new Opc.Hda.Server(fact, null);
                }

                if (!_OPCServer.IsConnected)
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "OPC server is disconnected, trying to connect");
                    _OPCServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential(), null));
                    if (!_OPCServer.IsConnected)
                    {
                        _trace.TraceEvent(TraceEventType.Error, 0, "Connection failed without exception: {0}", url.ToString());
                        return(false);
                    }
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "Succesfully connected to {0}, obj: {1}", url.ToString(), _OPCServer.GetHashCode().ToString());
                }
                try
                {
                    Status = _OPCServer.GetStatus();
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "OPC server status:\n" +
                                      "\tCurrentTime:     {0}\n" +
                                      "\tMaxReturnValues: {1}\n" +
                                      "\tProductVersion:  {2}\n" +
                                      "\tServerState:     {3}\n" +
                                      "\tStartTime:       {4}\n" +
                                      "\tStatusInfo:      {5}\n" +
                                      "\tVendorInfo:      {6}\n",
                                      Status.CurrentTime,
                                      Status.MaxReturnValues,
                                      Status.ProductVersion,
                                      Status.ServerState,
                                      Status.StartTime,
                                      Status.StatusInfo,
                                      Status.VendorInfo);
                }
                catch (Exception e)
                {
                    _trace.TraceEvent(TraceEventType.Warning, 0, "Can't get server status: {0}, {1}", url.ToString(), e.Message);
                }
                try
                {
                    _trace.TraceEvent(TraceEventType.Verbose, 0, "SupportedAggregates:");
                    SupportedAggregates = _OPCServer.GetAggregates();
                    foreach (Opc.Hda.Aggregate agg in SupportedAggregates)
                    {
                        _trace.TraceEvent(TraceEventType.Verbose, 0, "{0}\t{1}\t{2}", agg.ID, agg.Name, agg.Description);
                    }
                }
                catch (Exception e)
                {
                    _trace.TraceEvent(TraceEventType.Warning, 0, "Can't get server supported aggregates: {0}, {1}", url.ToString(), e.Message);
                }
            }
            catch (Exception e)
            {
                _trace.TraceEvent(TraceEventType.Error, 0, "Connection failed: {0}, {1}", url.ToString(), e.Message);
                return(false);
            }
            return(true);
        }
Esempio n. 25
0
 public PLCFactory(string url)
 {
     opcURL = new Opc.URL(url);
     OpcCom.Factory fact = new OpcCom.Factory();
     opcServer = new Opc.Da.Server(fact, null);
 }
Esempio n. 26
0
        /// <summary>
        /// Tries to connect to the server.
        /// </summary>
        private void Connect()
        {
            Opc.URL url = new Opc.URL("opcda://localhost/" + _serverName);
            OpcCom.Factory fact = new OpcCom.Factory();
            _server = new Opc.Da.Server(fact, null);

            try
            {
                _server.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
            }
            catch (Exception ex)
            {
                _error.Append(ex.ToString());
                if (ex.InnerException != null)
                    _error.Append(ex.InnerException.ToString());
            }
        }
Esempio n. 27
0
        public static void RsLinx_OPC_Client_Write(string ItemName, int Value)
        {
            try
            {
                //Creo un istanza di OPC.server
                Opc.Da.Server server;
                //Parametro necessario alla connect
                OpcCom.Factory fact = new OpcCom.Factory();
                //Creo un istanza di Sottoscrizione
                Opc.Da.Subscription groupWrite;
                //Creo un istanza di SubscriptionState, utile per controllare lo stato della sottoscrizione
                Opc.Da.SubscriptionState groupStateWrite;
                //Creo un array di OPC.Da.Item
                Opc.Da.Item[] items = new Opc.Da.Item[1];
                //Setto factory e url del server, come url utilizzo quello del RSLinx OPC Server
                server     = new Opc.Da.Server(fact, null);
                server.Url = new Opc.URL(Url);

                //Connetto il server
                server.Connect();

                //Istanzio la sottoscrizione
                groupStateWrite      = new Opc.Da.SubscriptionState();
                groupStateWrite.Name = "Group Write";
                //Questo valore deve essere true se voglio aver la possibilità di leggere, se devo solo scrivere lo metto false
                groupStateWrite.Active = false;
                //Creo il gruppo sul server
                groupWrite = (Opc.Da.Subscription)server.CreateSubscription(groupStateWrite);

                //Creo l'Item da scrivere (se il gruppo non lo possiede, lo devo inserire)
                Opc.Da.Item[] itemToAdd = new Opc.Da.Item[1];
                itemToAdd[0]          = new Opc.Da.Item();
                itemToAdd[0].ItemName = ItemName;

                //Creo l'istanza di ItemValue che possiede il mio Item e il valore che voglio assegnargli
                Opc.Da.ItemValue[] writeValues = new Opc.Da.ItemValue[1];
                writeValues[0] = new Opc.Da.ItemValue(itemToAdd[0]);

                //Controllo se l'oggetto esiste nel gruppo
                bool itemFound = false;
                foreach (Opc.Da.Item item in groupWrite.Items)
                {
                    if (item.ItemName == itemToAdd[0].ItemName)
                    {
                        //Se lo trovo gli setto il nuovo valore
                        writeValues[0].ServerHandle = item.ServerHandle;
                        itemFound = true;
                    }
                }
                if (!itemFound)
                {
                    //Se non ho trovato l'oggetto nel gruppo lo aggiungo..
                    groupWrite.AddItems(itemToAdd);
                    writeValues[0].ServerHandle = groupWrite.Items[groupWrite.Items.Length - 1].ServerHandle;
                }
                //...gli setto il valore
                writeValues[0].Value = Value;
                //e lo scrivo
                groupWrite.Write(writeValues);
            }
            catch (Exception ex)
            {
                //Se viene lanciata un'eccezione la mostro
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 28
0
 public RSLinxOPCDA()
 {
     m_factory = new OpcCom.Factory();
 }
        /// <summary>
        /// Returns a list of servers that support the specified specification on the specified host.
        /// </summary>
        public Opc.Server[] GetAvailableServers(Specification specification, string host, ConnectData connectData)
        {
            lock (this)
            {
                NetworkCredential credentials = (connectData != null)?connectData.GetCredential(null, null):null;

                // connect to the server.
                m_server = (IOPCServerList2)OpcCom.Interop.CreateInstance(CLSID, host, credentials);
                m_host   = host;

                try
                {
                    ArrayList servers = new ArrayList();

                    // convert the interface version to a guid.
                    Guid catid = new Guid(specification.ID);

                    // get list of servers in the specified specification.
                    IOPCEnumGUID enumerator = null;

                    m_server.EnumClassesOfCategories(
                        1,
                        new Guid[] { catid },
                        0,
                        null,
                        out enumerator);

                    // read clsids.
                    Guid[] clsids = ReadClasses(enumerator);

                    // release enumerator object.
                    OpcCom.Interop.ReleaseServer(enumerator);
                    enumerator = null;

                    // fetch class descriptions.
                    foreach (Guid clsid in clsids)
                    {
                        Factory factory = new OpcCom.Factory();

                        try
                        {
                            URL url = CreateUrl(specification, clsid);

                            Opc.Server server = null;

                            if (specification == Specification.COM_DA_30)
                            {
                                server = new Opc.Da.Server(factory, url);
                            }

                            else if (specification == Specification.COM_DA_20)
                            {
                                server = new Opc.Da.Server(factory, url);
                            }

                            else if (specification == Specification.COM_AE_10)
                            {
                                server = new Opc.Ae.Server(factory, url);
                            }

                            else if (specification == Specification.COM_HDA_10)
                            {
                                server = new Opc.Hda.Server(factory, url);
                            }

                            else if (specification == Specification.COM_DX_10)
                            {
                                server = new Opc.Dx.Server(factory, url);
                            }

                            servers.Add(server);
                        }
                        catch (Exception)
                        {
                            // ignore bad clsids.
                        }
                    }

                    return((Opc.Server[])servers.ToArray(typeof(Opc.Server)));
                }
                finally
                {
                    // free the server.
                    OpcCom.Interop.ReleaseServer(m_server);
                    m_server = null;
                }
            }
        }
Esempio n. 30
0
        private bool Connect(string serverUrl)
        {
            /* When the factory creates an HDA server, it passes along 2 parameters:
             *    SerializationInfo info
             *    StreamingContext context
             *
             * The Factory class casts the COM object (pointing to the HDA server) to the IServer interface.
             * All calls to the interface or proxied to the COM object.
             */


            Opc.URL        url  = new Opc.URL(serverUrl);
            OpcCom.Factory fact = new OpcCom.Factory();
            _view.daServer = new Server(fact, url);

            try
            {
                //_hdaServer.Connect();
                try
                {
                    _view.daServer.Connect(url, new Opc.ConnectData(new System.Net.NetworkCredential()));
                }
                catch (Exception ex)
                {
                    _view.ResultnMessage = ex.Message;
                    return(false);
                }
                //Console.WriteLine(String.Format("Connect to server {0}", serverName));

                //3rd Create a group if items
                #region Group read interlock and Machine status
                _view.groupStateRead      = new SubscriptionState();
                _view.groupStateRead.Name = "InterLockGroup";
                //_view.groupStateRead.UpdateRate = 1000;// this isthe time between every reads from OPC server
                _view.groupStateRead.Active = false;//this must be true if you the group has to read value
                _view.groupRead             = (Subscription)_view.daServer.CreateSubscription(_view.groupStateRead);
                //_view.groupRead.DataChanged += new DataChangedEventHandler(_view.group_DataChanged);//callback when the data are readed

                // add items to the group    (in Rockwell names are identified like [Name of PLC in the server]Block of word:number of word,number of consecutive readed words)
                if (_view.groupRead.Items != null)
                {
                    _view.groupRead.RemoveItems(_view.groupRead.Items);
                }

                _view.items = new Item[_view.plcTags.Count];
                int i = 0;
                foreach (var tag in _view.plcTags)
                {
                    _view.items[i]          = new Item();
                    _view.items[i].ItemName = _view.tagMainBlock + tag.PlcTag;
                    _view.items[i].Active   = true;

                    i++;
                }
                _view.items = _view.groupRead.AddItems(_view.items);
                #endregion

                #region Group write
                //_view.groupStateWrite = new SubscriptionState();
                //_view.groupStateWrite.Name = "WriteInterLock";
                //_view.groupStateWrite.Active = false;//not needed to read if you want to write only
                //_view.groupWrite = (Subscription)_view.daServer.CreateSubscription(_view.groupStateWrite);
                #endregion

                return(true);
            }
            catch (Opc.ConnectFailedException opcConnExc)
            {
                MessageBox.Show(String.Format("Could not connect to server {0}{1}{2}"
                                              , serverUrl
                                              , Environment.NewLine
                                              , opcConnExc.ToString())
                                , "Connection failed!"
                                , MessageBoxButtons.OK
                                , MessageBoxIcon.Error);
                return(false);
            }
        }