예제 #1
1
파일: OpcClient.cs 프로젝트: BdGL3/CXPortal
        private void ConnectionAgent()
        {
            while (!_connectionEnd.WaitOne(0) && !Connected)
                try
                {
                    URL url = new URL(_OpcSection.Server.Name);
                    _Server = new Opc.Da.Server(new OpcCom.Factory(), null);
                    _Server.Connect(url, new ConnectData(new NetworkCredential()));

                    _groupRead = (Subscription)_Server.CreateSubscription(_GroupReadState);
                    _groupWrite = (Subscription)_Server.CreateSubscription(_GroupWriteState);

                    for (int i = 0; i < _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags.Count; i++)
                    {
                        _Items[i] = new Opc.Da.Item();
                        //_Items[i].ItemName = String.Format("{0}{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name);
                        _Items[i].ItemName = _OpcSection.Server.Channel + "." + _OpcSection.Server.Device + "." + _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name;
                        //string itmNam = String.Format("{0}]{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name);
                        _logger.LogInfo(/*Mtd*/ ": recognized element " + _Items[i].ItemName);
                    }
                    _Items = _groupRead.AddItems(_Items);
                    _groupRead.DataChanged += new DataChangedEventHandler(Group_DataChanged);
                }
                catch (Exception ex) { _logger.LogError(ex); }
        }
예제 #2
1
        private Int16 GetTagCanonicalType(string itemName)
        {
            const int ItemCanonicalDataTypeProperty = 1;

            TreeNode rootNode = uiGroupsTab_AllFoldersTreeView.SelectedNode;
            while (rootNode.Parent != null)
            {
                rootNode = rootNode.Parent;
            }

            var opcServer = Settings.OpcServers.Where(os => rootNode.FullPath == os.ServerName).Single();
            string urlstring = opcServer.URL;
            Server server = new Server(new Factory(), new URL(urlstring));
            server.Connect();

            ItemIdentifier [] itemIdentifiers = new ItemIdentifier[] {new ItemIdentifier(itemName)};
            PropertyID[] propertyIDs = new PropertyID[] { new PropertyID(ItemCanonicalDataTypeProperty) };

            var result = server.GetProperties(itemIdentifiers, propertyIDs, true);

            server.Disconnect();

            var resultType = result[0][0].Value.GetType();
            PropertyInfo nameProperty = resultType.GetProperty("Name");
            string name = nameProperty.GetValue(result[0][0].Value, null) as string;

            switch (name.ToLower())
            {
                case "string":
                case "char":
                    return 0;
                case "int16":
                case "int32":
                case "int64":
                case "uint16":
                case "uint32":
                case "uint64":
                    return 1;
                case "boolean":
                    return 2;
                case "decimal":
                case "double":
                    return 3;
                case "datetime":
                case "datetimeoffset":
                    return 4;
                default:
                    return 0;
            }
        }
예제 #3
1
파일: OpcClient.cs 프로젝트: BdGL3/CXPortal
 public static void TestConnection (string connection)
 {
     URL url = new URL(connection);
     Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), null);
     server.Connect(url, new ConnectData(new NetworkCredential()));
 }
예제 #4
0
        /// <summary>
        /// Fetches the set of data filters from the server.
        /// </summary>
        public ComplexItem[] GetDataFilters(Opc.Da.Server server)
        {
            // not a valid operation for data filter items.
            if (m_unfilteredItemID != null)
            {
                return(null);
            }

            // data filters not supported by the item.
            if (m_filterItem == null)
            {
                return(null);
            }

            BrowsePosition position = null;

            try
            {
                // browse any existing filter instances.
                BrowseFilters filters = new BrowseFilters();

                filters.ElementNameFilter    = null;
                filters.BrowseFilter         = browseFilter.item;
                filters.ReturnAllProperties  = false;
                filters.PropertyIDs          = CPX_PROPERTIES;
                filters.ReturnPropertyValues = true;

                BrowseElement[] elements = server.Browse(m_filterItem, filters, out position);

                // nothing found.
                if (elements == null || elements.Length == 0)
                {
                    return(new ComplexItem[0]);
                }

                // contruct an array of complex data items for each available data filter.
                ArrayList dataFilters = new ArrayList(elements.Length);

                foreach (BrowseElement element in elements)
                {
                    ComplexItem item = new ComplexItem();

                    if (item.Init(element))
                    {
                        dataFilters.Add(item);
                    }
                }

                // return the set of available data filters.
                return((ComplexItem[])dataFilters.ToArray(typeof(ComplexItem)));
            }
            finally
            {
                if (position != null)
                {
                    position.Dispose();
                    position = null;
                }
            }
        }
예제 #5
0
        /// <summary>
        /// Reads the current complex data item properties from the server.
        /// </summary>
        public void Update(Opc.Da.Server server)
        {
            // clear the existing state.
            Clear();

            // check if the item supports any of the complex data properties.
            ItemPropertyCollection[] results = server.GetProperties(
                new ItemIdentifier[] { this },
                CPX_PROPERTIES,
                true);

            // unexpected return value.
            if (results == null || results.Length != 1)
            {
                throw new ApplicationException("Unexpected results returned from server.");
            }

            // update object.
            if (!Init((ItemProperty[])results[0].ToArray(typeof(ItemProperty))))
            {
                throw new ApplicationException("Not a valid complex item.");
            }

            // check if data filters are suppported for the item.
            GetDataFilterItem(server);
        }
예제 #6
0
        public void ConnectToServer()
        {
            try
            {
                //LOCAL OPC CONNECTION kepware
                //url = new Opc.URL("opcda://PCNAME/Kepware.KEPServerEX.V6");
                //LOCAL OPC CONNECTION RSLinx
                //url = new Opc.URL("opcda://PCNAME/RSLinx OPC Server");

                //REMOTE OPC CONNECTION WHEN USING opcexpert tunneling
                url = new Opc.URL("opcda://PCNAME/RSLinx Remote OPC Server.REMOTEPCNAME");

                //REMOTE RSLinx OPC
                //this requires DCOM setup
                //url = new Opc.URL("opcda://PCNAME/RSLinx Remote OPC Server");

                server = new Opc.Da.Server(fact, url);
                System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential();
                Opc.ConnectData connecteddata = new Opc.ConnectData(networkCredential);
                server.Connect(url, connecteddata);
                groupState             = new Opc.Da.SubscriptionState();
                groupState.Name        = "Group";
                groupState.UpdateRate  = 1;                                                 // this isthe time between every reads from OPC server
                groupState.Active      = true;                                              //this must be true if you the group has to read value
                groupRead              = (Opc.Da.Subscription)server.CreateSubscription(groupState);
                groupRead.DataChanged += new Opc.Da.DataChangedEventHandler(UpdateTagData); //callback when the data are readed

                Opc.Da.Item[] items_read = groupRead.AddItems(createSomeTags());
            }
            catch (Exception E)
            {
                Console.WriteLine(E.Message);
            }
        }
예제 #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);
            }
        }
예제 #8
0
        static void Main(string[] args)
        {
            Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), new URL
            {
                Path   = @"Matrikon.OPC.Simulation.1",
                Scheme = Opc.UrlScheme.DA
            });
            server.Connect();

            //Write Values
            int       counter  = 1;
            ItemValue item     = new ItemValue("Bucket Brigade.TestWrite");
            var       itemList = new List <ItemValue>();

            itemList.Add(item);
            Item item_read = new Item();

            item_read.ItemName = "Bucket Brigade.TestWrite";
            item_read.Active   = true;
            List <Item> readItems = new List <Item>();

            readItems.Add(item_read);
            while (true)
            {
                item.Value = "Testing" + counter;
                server.Write(itemList.ToArray());
                counter++;

                var result = server.Read(readItems.ToArray());
                foreach (var value in result)
                {
                    System.Console.WriteLine(value.ItemName + " : " + value.Value.ToString());
                }
            }
        }
예제 #9
0
        public ItemIdentifier ShowDialog(Opc.Da.Server server)
        {
            ItemIdentifier result;

            try
            {
                if (server == null)
                {
                    throw new System.ArgumentNullException("server");
                }
                this.m_server = server;
                this.m_itemID = null;
                BrowseFilters browseFilters = new BrowseFilters();
                browseFilters.ReturnAllProperties  = false;
                browseFilters.ReturnPropertyValues = false;
                this.BrowseCTRL.ShowSingleServer(this.m_server, browseFilters);
                this.PropertiesCTRL.Initialize(null);
                if (base.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    result = null;
                }
                else
                {
                    result = this.m_itemID;
                }
            }
            finally
            {
                this.BrowseCTRL.Clear();
            }
            return(result);
        }
예제 #10
0
        /// <summary>
        /// Updates a data filter.
        /// </summary>
        public void UpdateDataFilter(Opc.Da.Server server, string filterValue)
        {
            // not a valid operation for non data filter items.
            if (m_unfilteredItemID == null)
            {
                throw new ApplicationException("Cannot update the data filter for this item.");
            }

            ItemValue item = new ItemValue(this);

            // create the value to write.
            item.Value              = filterValue;
            item.Quality            = Quality.Bad;
            item.QualitySpecified   = false;
            item.Timestamp          = DateTime.MinValue;
            item.TimestampSpecified = false;

            // write the value.
            IdentifiedResult[] result = server.Write(new ItemValue[] { item });

            if (result == null || result.Length == 0)
            {
                throw new ApplicationException("Unexpected result from server.");
            }

            if (result[0].ResultID.Failed())
            {
                throw new ApplicationException("Could not update data filter.");
            }

            // update locale copy of the filter value.
            m_filterValue = filterValue;
        }
예제 #11
0
        //Connect to server
        public override void Connect(string host, string serverName)
        {
            var url = new URL("opcda://" + host + "/" + serverName);

            Server = new Opc.Da.Server(new OpcCom.Factory(), url);
            Server.Connect();
        }
예제 #12
0
        public static void TestConnection(string connection)
        {
            URL url = new URL(connection);

            Opc.Da.Server server = new Opc.Da.Server(new OpcCom.Factory(), null);
            server.Connect(url, new ConnectData(new NetworkCredential()));
        }
예제 #13
0
        /// <summary>
        /// 连接OPC
        /// </summary>
        /// <returns></returns>
        public bool Connect(string opcServerName, string opcServerIp)
        {
            try
            {
                Opc.Server[] serverArray = new ServerEnumerator().GetAvailableServers(Specification.COM_DA_20, opcServerIp, null);
                if (serverArray != null)
                {
                    Opc.Server server = serverArray.Where(a => a.Name == opcServerName).FirstOrDefault();
                    if (server != null)
                    {
                        server.Connect();
                        this.Server = (Opc.Da.Server)server;
                        return(true);
                    }
                }
            }
            catch (Exception ex) { if (OnScanError != null)
                                   {
                                       OnScanError(ex);
                                   }
            }

            this.Close();
            return(false);
        }
예제 #14
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);
        }
예제 #15
0
            /// <summary>
            /// Adds the row.
            /// </summary>
            /// <param name="credential">The credential.</param>
            /// <param name="server">The server.</param>
            /// <returns>ServersTableRow.</returns>
            public ServersTableRow AddRow(ConnectData credential, Opc.Da.Server server)
            {
                ServersTableRow mRow = this.NewServersTableRow();

                mRow.LicenseKey = credential.LicenseKey;
                if (credential.Credentials != null)
                {
                    mRow.Domain   = credential.Credentials.Domain;
                    mRow.Password = credential.Credentials.Password;
                    mRow.UserName = credential.Credentials.UserName;
                }
                ServerStatus status = server.GetStatus();

                mRow.CurrentTime              = status.CurrentTime;
                mRow.ProductVersion           = status.ProductVersion;
                mRow.SpecificationDescription = server.PreferedSpecyfication.Description;
                mRow.SpecificationID          = server.PreferedSpecyfication.ID;
                mRow.URLString  = server.Url.ToString();
                mRow.VendorInfo = status.VendorInfo;
                this.AddServersTableRow(mRow);
                foreach (var loc in server.SupportedLocales)
                {
                    ((AddressSpaceDataBase)this.DataSet).LocalesTable.AddRow(mRow.ID, loc);
                }
                return(mRow);
            }
예제 #16
0
        private void recursiveTreeFill(Server server, string itemId)
        {
            BrowsePosition position;
            BrowseFilters  filters = new BrowseFilters()
            {
                BrowseFilter = browseFilter.all
            };

            ItemIdentifier item = (itemId == null) ? new ItemIdentifier() : new ItemIdentifier(itemId);

            BrowseElement[] browseElements = server.Browse(item, filters, out position);

            repository.Add(itemId, browseElements);

            for (int index = 0; index < browseElements.Length; index++)
            {
                BrowseElement browsedElement = browseElements[index];
                string        itemName       = browsedElement.ItemName;
                if (browsedElement.HasChildren)
                {
                    recursiveTreeFill(server, itemName);
                }
                else
                {
                    if (!repository.ContainsKey(itemId))
                    {
                        repository.Add(itemId, new BrowseElement[] { });
                    }
                }
            }
        }
예제 #17
0
        public OpcIoDevice(string options)
        {
            _url = new URL(options);
            var fact = new OpcCom.Factory();

            _server = new Server(fact, null);
        }
        /*********************************************************************************************************************
        *
        * Buttons End
        *
        *********************************************************************************************************************/

        /*********************************************************************************************************************
        *
        *  Methods
        *
        *  Show Components():
        *  Search For Components():
        *  Search For Job():
        *
        *
        *********************************************************************************************************************/

        private void JobData_ConnectToOPCServer(object sender, EventArgs e)
        {
            try
            {
                OPCServer     = new Opc.Da.Server(OPCFactory, null);
                OPCServer.Url = new Opc.URL("opcda://OHN66OPC/Kepware.KEPServerEX.V6");
                OPCServer.Connect();

                Component_StateRead            = new Opc.Da.SubscriptionState();
                Component_StateRead.Name       = "Component_Reading";
                Component_StateRead.UpdateRate = 1000;
                Component_StateRead.Active     = true;
                Component_Read              = (Opc.Da.Subscription)OPCServer.CreateSubscription(Component_StateRead);
                Component_Read.DataChanged += new Opc.Da.DataChangedEventHandler(Component_Read_DataChanged);

                ScanNewPart_StateWrite        = new Opc.Da.SubscriptionState();
                ScanNewPart_StateWrite.Name   = "ScanNewPart_WriteGroup";
                ScanNewPart_StateWrite.Active = true;
                ScanNewPart_Write             = (Opc.Da.Subscription)OPCServer.CreateSubscription(ScanNewPart_StateWrite);

                Hardware_StateWrite        = new Opc.Da.SubscriptionState();
                Hardware_StateWrite.Name   = "Hardware_WriteGroup";
                Hardware_StateWrite.Active = true;
                Hardware_Write             = (Opc.Da.Subscription)OPCServer.CreateSubscription(Hardware_StateWrite);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
예제 #19
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);
        }
예제 #20
0
        public void WithGroupOfItems(Opc.Da.Server server, string groupName, IEnumerable <OpisenseOpcItem> opcItems, Action <OpcDaClientConnector, Subscription> action, Action <Exception> onError = null)
        {
            if (opcItems is null)
            {
                return;
            }

            var opcItemsList = opcItems.ToList();

            if (!opcItemsList.Any())
            {
                return;
            }

            var groupState = new SubscriptionState
            {
                Name   = groupName,
                Active = false
            };

            using (var opcGroup = server.CreateSubscription(groupState))
            {
                //There is a bug in the library, ClientHandle is not propagated with item results
                var subscriptionItems = opcItemsList.Select(i => new Item {
                    ItemName = i.OpcItemName, ClientHandle = i.VariableId
                });
                opcGroup.AddItems(subscriptionItems.ToArray());
                action(this, opcGroup as Subscription);
            }
        }
예제 #21
0
        /// <summary>
        /// OPC建立连接
        /// </summary>
        public void mOPC_ConnToServer()
        {
            try
            {
                string hostName = IEGInterface.Properties.Settings.Default.MachineName;
                //查询服务器
                m_Server = null;
                Opc.Server[] servers = m_Discovery.GetAvailableServers(Specification.COM_DA_20, hostName, null);
                if (servers != null)
                {
                    foreach (Opc.Da.Server sr in servers)
                    {
                        //获取需要连接的OPC数据存取服务器
                        if (String.Compare(sr.Name, hostName + ".OPC.SimaticNET", true) == 0)
                        {
                            m_Server = sr;
                            break;
                        }
                    }
                }

                if (m_Server != null)
                {
                    m_Server.Connect();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("OPC连接函数(mOPC_ConnToServer)异常:" + ex.ToString());
            }
        }
예제 #22
0
        public void UpdateDataFilter(Opc.Da.Server server, string filterValue)
        {
            if (this.m_unfilteredItemID == null)
            {
                throw new ApplicationException("Cannot update the data filter for this item.");
            }
            ItemValue value2 = new ItemValue(this)
            {
                Value              = filterValue,
                Quality            = Quality.Bad,
                QualitySpecified   = false,
                Timestamp          = DateTime.MinValue,
                TimestampSpecified = false
            };

            IdentifiedResult[] resultArray = server.Write(new ItemValue[] { value2 });
            if ((resultArray == null) || (resultArray.Length == 0))
            {
                throw new ApplicationException("Unexpected result from server.");
            }
            if (resultArray[0].ResultID.Failed())
            {
                throw new ApplicationException("Could not update data filter.");
            }
            this.m_filterValue = filterValue;
        }
예제 #23
0
        //***************************************************************
        //* Create the Data Link Layer Instances
        //* if the IP Address is the same, then resuse a common instance
        //***************************************************************
        public bool Connection()
        {
            try
            {
                if (DLL == null)
                {
                    if (DLL != null && DLL.IsConnected)
                    {
                        DLL.Disconnect();
                    }

                    DLL = new Server(fact, null)
                    {
                        Url = new URL(m_OPCServerPath + "/" + OPCServer)
                    };
                    DLL.Connect();
                    if (DLL.IsConnected)
                    {
                        EventscadaException?.Invoke(GetType().Name, "ConnectedSuccess");
                        IsConnected = true;
                    }
                    else
                    {
                        EventscadaException?.Invoke(GetType().Name, "ConnectedFailed");
                        IsConnected = false;
                    }
                }
            }
            catch (Exception)
            {
                EventscadaException?.Invoke(GetType().Name, "ConnectedFailed");
                IsConnected = false;
            }
            return(IsConnected);
        }
예제 #24
0
        private void ConnectionAgent()
        {
            while (!_connectionEnd.WaitOne(0) && !Connected)
            {
                try
                {
                    URL url = new URL(_OpcSection.Server.Name);
                    _Server = new Opc.Da.Server(new OpcCom.Factory(), null);
                    _Server.Connect(url, new ConnectData(new NetworkCredential()));

                    _groupRead  = (Subscription)_Server.CreateSubscription(_GroupReadState);
                    _groupWrite = (Subscription)_Server.CreateSubscription(_GroupWriteState);

                    for (int i = 0; i < _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags.Count; i++)
                    {
                        _Items[i] = new Opc.Da.Item();
                        //_Items[i].ItemName = String.Format("{0}{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name);
                        _Items[i].ItemName = _OpcSection.Server.Channel + "." + _OpcSection.Server.Device + "." + _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name;
                        //string itmNam = String.Format("{0}]{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name);
                        _logger.LogInfo(/*Mtd*/ ": recognized element " + _Items[i].ItemName);
                    }
                    _Items = _groupRead.AddItems(_Items);
                    _groupRead.DataChanged += new DataChangedEventHandler(Group_DataChanged);
                }
                catch (Exception ex) { _logger.LogError(ex); }
            }
        }
예제 #25
0
 private void BrowseServers(System.Windows.Forms.TreeNode node)
 {
     try
     {
         node.Nodes.Clear();
         string host = null;
         if (node != this.m_localServers)
         {
             host = node.Text;
         }
         ConnectData  connectData      = this.FindConnectData(node);
         Opc.Server[] availableServers = this.m_discovery.GetAvailableServers(this.m_specification, host, connectData);
         if (availableServers != null)
         {
             Opc.Server[] array = availableServers;
             for (int i = 0; i < array.Length; i++)
             {
                 Opc.Da.Server server = (Opc.Da.Server)array[i];
                 System.Windows.Forms.TreeNode treeNode = new System.Windows.Forms.TreeNode(server.Name);
                 treeNode.ImageIndex = (treeNode.SelectedImageIndex = Resources.IMAGE_LOCAL_SERVER);
                 treeNode.Tag        = server;
                 node.Nodes.Add(treeNode);
             }
             node.Expand();
         }
     }
     catch (System.Exception ex)
     {
         System.Windows.Forms.MessageBox.Show(ex.Message);
     }
 }
예제 #26
0
 public Connection(string aServerUrl, Opc.Da.Server aServer)
 {
     lockRoot  = new object();
     active    = true;
     serverUrl = aServerUrl;
     server    = aServer;
     Ping();
 }
예제 #27
0
 public rextoth()
 {
     setStringValue();
     if (opcServer == null)
     {
         opcServer = GetOpcServer();
     }
 }
예제 #28
0
파일: Form1.cs 프로젝트: Tibe93/OPC_Writer
        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);
            }
        }
예제 #29
0
        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="serverName"></param>
        /// <param name="host"></param>
        public OpcResult Connect(string serverName, string host = "127.0.0.1")
        {
            OpcResult opcResult = OpcResult.ServerNoConnect;

            try
            {
                this.OpcServerName = serverName;
                this.Host          = host;
                if (string.IsNullOrWhiteSpace(serverName) || string.IsNullOrWhiteSpace(host))
                {
                    if (!Equals(null, OnLogHappened))
                    {
                        OnLogHappened(this, new OpcLogEventArgs("未指定服务器或主机名称"));
                    }
                    opcResult = OpcResult.E_FAIL;
                    return(opcResult);
                }
                if (IsConnected)
                {
                    if (!Equals(null, OnLogHappened))
                    {
                        OnLogHappened(this, new OpcLogEventArgs("Opc服务器已经连接,host=" + host + ",serverName=" + serverName));
                    }
                    opcResult = OpcResult.S_OK;
                    return(opcResult);
                }
                var servers = OpcClientHelper.getOpcServers(host);
                if (!Equals(null, servers) && servers.Any(a => a.Name == serverName))
                {
                    opcServer = (Opc.Da.Server)servers.FirstOrDefault(a => a.Name == serverName);
                    opcServer.Connect();
                    //服务器断开事件
                    opcServer.ServerShutdown += opcServer_ServerShutdown;
                    IsConnected = true;
                    if (!Equals(null, OnLogHappened))
                    {
                        OnLogHappened(this, new OpcLogEventArgs("连接Opc服务器成功,host=" + host + ",serverName=" + serverName));
                    }
                    //连接成功后开启守护进程
                    daemonTimer.Enabled = true;
                    daemonTimer.Start();
                    opcResult = OpcResult.S_OK;
                }
                return(opcResult);
            }
            catch (Exception ex)
            {
                IsConnected = false;
                if (!Equals(null, OnErrorHappened))
                {
                    OnErrorHappened(this, new OpcErrorEventArgs(OpcResult.E_FAIL, "连接Opc服务器时出错:" + ex.Message, ex));
                }
                opcResult = OpcResult.E_FAIL;
                return(opcResult);
            }
        }
예제 #30
0
 public void Browse(System.Windows.Forms.TreeNode node)
 {
     try
     {
         Opc.Da.Server  server = this.FindServer(node);
         ItemIdentifier itemID = null;
         if (node.Tag != null && node.Tag.GetType() == typeof(BrowseElement))
         {
             BrowseElement browseElement = (BrowseElement)node.Tag;
             itemID = new ItemIdentifier(browseElement.ItemPath, browseElement.ItemName);
         }
         node.Nodes.Clear();
         BrowsePosition  browsePosition = null;
         BrowseElement[] array          = server.Browse(itemID, this.m_filters, out browsePosition);
         if (array != null)
         {
             BrowseElement[] array2 = array;
             for (int i = 0; i < array2.Length; i++)
             {
                 BrowseElement browseElement2 = array2[i];
                 if (!browseElement2.ItemName.Contains("alrosa_w") && !browseElement2.ItemName.Contains("List of"))
                 {
                     if (!browseElement2.IsItem)
                     {
                         this.AddBrowseElement(node, browseElement2);
                     }
                 }
             }
             node.Expand();
         }
         while (browsePosition != null)
         {
             System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.MessageBox.Show("More items meeting search criteria exist. Continue browse?", "Browse Items", System.Windows.Forms.MessageBoxButtons.YesNo);
             if (dialogResult == System.Windows.Forms.DialogResult.No)
             {
                 break;
             }
             array = server.BrowseNext(ref browsePosition);
             if (array != null)
             {
                 BrowseElement[] array2 = array;
                 for (int i = 0; i < array2.Length; i++)
                 {
                     BrowseElement browseElement2 = array2[i];
                     this.AddBrowseElement(node, browseElement2);
                 }
                 node.Expand();
             }
         }
     }
     catch (System.Exception ex)
     {
         System.Windows.Forms.MessageBox.Show(ex.Message);
     }
 }
예제 #31
0
        private string getRootName(Server server)
        {
            BrowsePosition position;
            BrowseFilters  filters = new BrowseFilters()
            {
                BrowseFilter = browseFilter.all
            };

            BrowseElement[] rootElements = server.Browse(new ItemIdentifier(), filters, out position);
            return(rootElements[0].ItemName);
        }
예제 #32
0
파일: DaClient.cs 프로젝트: pilhokim/h-opc
 /// <summary>
 /// Connect the client to the OPC Server
 /// </summary>
 public void Connect()
 {
     if (Status == OpcStatus.Connected)
     {
         return;
     }
     _server = new OpcDa.Server(new Factory(), _url);
     _server.Connect();
     RootNode = new DaNode(this, string.Empty, string.Empty);
     AddNodeToCache(RootNode);
 }
예제 #33
0
        public void WithConnectedOpcDaServer(string opcServerUrl, Action <OpcDaClientConnector, Opc.Da.Server> action, Action <Exception> onError = null)
        {
            var url = new URL(opcServerUrl);

            using (var server = new Opc.Da.Server(new OpcCom.Factory(), null))
            {
                var connectData = new ConnectData(new System.Net.NetworkCredential());
                server.Connect(url, connectData);
                action(this, server);
            }
        }
예제 #34
0
        public OPCServer(string serverName)
        {
            if (String.IsNullOrEmpty(serverName))
                throw new ArgumentException("Server name is invalid.");

            _serverURL = new URL(serverName);
            _serverURL.Scheme = "opcda";
            _server = new Opc.Da.Server(new OpcCom.Factory(), _serverURL);

            try
            {
                _server.Connect();
            }
            catch (Opc.ConnectFailedException connectionExc) {
                Console.WriteLine("Connection to OPC server could not be established");
                Console.WriteLine(connectionExc.ToString());
            }
        }
예제 #35
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);
			}
		}
예제 #36
0
        private void UpdateFolderData(TreeNode node)
        {
            if (node == null)
            {
                uiFolderTagsBindingSource.DataSource = null;
                return;
            }

            //Add items to folder, read from OPC Server if first time
            var folderTags = node.Tag as List<BrowseElement>;
            if (folderTags == null)
            {
                TreeNode rootNode = node;
                while (rootNode.Parent != null)
                {
                    rootNode = rootNode.Parent;
                }

                var opcServer = Settings.OpcServers.Where(os => rootNode.FullPath == os.ServerName).Single();
                string urlstring = opcServer.URL;
                Server server = new Server(new Factory(), new URL(urlstring));
                server.Connect();

                BrowsePosition position;
                BrowseFilters filters = new BrowseFilters() { BrowseFilter = browseFilter.all };
                ItemIdentifier itemId = null;

                if (node.FullPath != server.Name)
                {
                    itemId = new ItemIdentifier(node.Name);
                }

                BrowseElement[] elements = server.Browse(itemId, filters, out position);
                server.Disconnect();

                var items = elements.Where(e => e.IsItem);
                if (items.Any())
                {
                    folderTags = items.ToList();
                }
                else
                {
                    folderTags = new List<BrowseElement>();
                }

                var folders = elements.Where(e => e.IsItem == false);
                if(folders.Any())
                {
                    foreach (var element in elements.Where(e => !e.IsItem))
                    {
                        node.Nodes.Add(element.Name).Name = element.ItemName;
                    }
                }

                node.Tag = folderTags;
            }

            //Exlude elements which already are in group
            folderTags = folderTags.ToList();
            var selectedGroup = uiGroupsTab_Groups.SelectedItem as Group;
            if (selectedGroup != null)
            {
                if (selectedGroup.Properties != null)
                {
                    foreach (var property in selectedGroup.Properties)
                    {
                        folderTags.RemoveAll(t => t.ItemName == property.TagName);
                    }
                }
            }

            uiFolderTagsBindingSource.DataSource = folderTags;

            //if (elements != null)
            //{
            //    var itemsIDs = new List<ItemIdentifier>();
            //    foreach (var element in elements)
            //    {
            //        itemsIDs.Add(new ItemIdentifier(element.ItemName));
            //    }

            //    var prid = new List<PropertyID>();
            //    prid.Add(new PropertyID(1));
            //    prid.Add(new PropertyID(2));

            //    var tst = server.GetProperties(itemsIDs.ToArray(), prid.ToArray(), true);
            //}
        }
예제 #37
0
        //private void AddNode(Server opcServer, TreeNode treeNode)
        //{
        //    ItemIdentifier itemId;
        //    BrowsePosition position;
        //    BrowseFilters filters = new BrowseFilters() { BrowseFilter = browseFilter.branch };
        //    if (treeNode.FullPath == opcServer.Name)
        //    {
        //        itemId = null;
        //    }
        //    else
        //    {
        //        //int serverNameLength = opcServer.Name.Length;
        //        //string itemIdentifier = treeNode.FullPath.Substring(serverNameLength + 1);
        //        itemId = new ItemIdentifier(treeNode.Name);
        //    }
        //    BrowseElement[] elements = opcServer.Browse(itemId, filters, out position);
        //    if (elements == null)
        //    {
        //        return;
        //    }
        //    foreach (var element in elements)
        //    {
        //        treeNode.Nodes.Add(element.Name).Name = element.ItemName;
        //    }
        //    //foreach (TreeNode node in treeNode.Nodes)
        //    //{
        //    //    AddNode(opcServer, node);
        //    //}
        //}
        private void UpdateFoldersTree()
        {
            uiGroupsTab_AllFoldersTreeView.Nodes.Clear();
            List<OpcServer> opcServers;

            if (uiGroupsTab_Groups.SelectedItem == null)
            {
                opcServers = Settings.OpcServers;
            }
            else
            {
                var selectedGroup = uiGroupsTab_Groups.SelectedItem as Group;
                opcServers = new List<OpcServer>();
                opcServers.Add(selectedGroup.OpcServer);
            }

            foreach (var opcServer in opcServers)
            {
                string urlstring = opcServer.URL;
                Server server = new Server(new Factory(), new URL(urlstring));
                if (opcServer.RootNode == null)
                {
                    var newNode = uiGroupsTab_AllFoldersTreeView.Nodes.Add(server.Name);
                    server.Connect();
                    //AddNode(server, newNode);
                    UpdateFolderData(newNode);
                    server.Disconnect();
                    opcServer.RootNode = newNode;
                }
                else
                {
                    uiGroupsTab_AllFoldersTreeView.Nodes.Add(opcServer.RootNode);
                }
            }

            if (uiGroupsTab_AllFoldersTreeView.Nodes != null)
            {
                foreach (TreeNode node in uiGroupsTab_AllFoldersTreeView.Nodes)
                {
                    node.Expand();
                }
            }
            UpdateFolderData(uiGroupsTab_AllFoldersTreeView.SelectedNode);
        }
예제 #38
0
파일: OpcIoDevice.cs 프로젝트: phmi/phmi
 public OpcIoDevice(string options)
 {
     _url = new URL(options);
     var fact = new OpcCom.Factory();
     _server = new Server(fact, null);
 }
예제 #39
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());
            }
        }