예제 #1
0
		TsCDaBrowseElement[] Browse(TsCDaServer server)
		{
			TsCDaBrowseFilters filters;
			List<TsCDaBrowseElement> elementList;
			TsCDaBrowseElement[] elements;
			TsCDaBrowsePosition position;
			OpcItem path = new OpcItem();

			filters = new TsCDaBrowseFilters();
			filters.BrowseFilter = TsCDaBrowseFilter.All;
			filters.ReturnAllProperties = true;
			filters.ReturnPropertyValues = true;

			elementList = new List<TsCDaBrowseElement>();

			elements = server.Browse(path, filters, out position);

			foreach (var item in elements)
			{
				item.ItemPath = OpcDaTag.ROOT + OpcDaTag.SPLITTER + item.ItemName;
				elementList.Add(item);

				if (!item.IsItem)
				{
					path = new OpcItem(item.ItemPath, item.Name);
					BrowseChildren(path, filters, elementList, server);
				}

			}
			return elementList.ToArray();
		}
		public OpcTechnosoftWriteTagsViewModel(TsCDaServer server, TsCDaBrowseElement[] tags)
		{
			Title = "Запись тегов";
			_opcDaServer = server;
			_tags = tags.Select(x => OpcTechnosoftwareTagValueBaseViewModel.Create(x))
				.Where(y => y.Accessibility == TsDaAccessRights.ReadWritable ||
					y.Accessibility == TsDaAccessRights.Writable)
				.ToArray();
			WriteTagsCommand = new RelayCommand(OnWriteTags, CanWriteTags);
		}
예제 #3
0
        /// <summary>
        /// Browses the address space for a single server.
        /// </summary>
        public void ShowSingleServer(TsCDaServer server, TsCDaBrowseFilters filters)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            Clear();

            m_filters = (filters == null)?new TsCDaBrowseFilters():filters;

            m_singleServer                    = new TreeNode(server.ServerName);
            m_singleServer.ImageIndex         = Resources.IMAGE_LOCAL_SERVER;
            m_singleServer.SelectedImageIndex = Resources.IMAGE_LOCAL_SERVER;
            m_singleServer.Tag                = server.Duplicate();

            Connect(m_singleServer);
            BrowseTV.Nodes.Add(m_singleServer);
        }
        /// <summary>
        /// Deletes the specified subscription.
        /// </summary>
        private void DeleteSubscription(TreeNode node, TsCDaSubscription subscription)
        {
            if (SubscriptionModified != null)
            {
                SubscriptionModified(subscription, true);
            }

            try
            {
                TsCDaServer server = subscription.Server;
                server.CancelSubscription(subscription);
                subscription.Dispose();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

            node.Remove();
        }
예제 #5
0
        /// <summary>
        /// Displays the address space for the specified server.
        /// </summary>
        public void Initialize(TsCDaServer server)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            m_server = server;

            TsCDaBrowseFilters filters = new TsCDaBrowseFilters();

            filters.ReturnAllProperties  = true;
            filters.ReturnPropertyValues = true;

            BrowseCTRL.ShowSingleServer(m_server, filters);

            ShowDialog();

            // ensure server connection in the browse control are closed.
            BrowseCTRL.Clear();
        }
        /// <summary>
        /// Fetches the type description for the item.
        /// </summary>
        /// <param name="server">The server object</param>
        public string GetTypeDescription(TsCDaServer server)
        {
            TsCDaItemPropertyCollection[] results = server.GetProperties(
                new OpcItem[] { _typeItemID },
                new TsDaPropertyID[] { TsDaProperty.TYPE_DESCRIPTION },
                true);

            if (results == null || results.Length == 0 || results[0].Count == 0)
            {
                return(null);
            }

            TsCDaItemProperty property = results[0][0];

            if (!property.Result.Succeeded())
            {
                return(null);
            }

            return((string)property.Value);
        }
		/// <summary>
		/// Fetches the type dictionary for the item.
		/// </summary>
		/// <param name="server">The server object</param>
		public string GetTypeDictionary(TsCDaServer server)
		{
			TsCDaItemPropertyCollection[] results = server.GetProperties(
				new OpcItem[] { _dictionaryItemID },
				new TsDaPropertyID[] { TsDaProperty.DICTIONARY },
				true);

			if (results == null || results.Length == 0 || results[0].Count == 0)
			{
				return null;
			}

			TsCDaItemProperty property = results[0][0];

			if (!property.Result.Succeeded())
			{
				return null;
			}

			return (string)property.Value;
		}
        /// <summary>
        /// Browses the address space for a single server.
        /// </summary>
        public void ShowSingleServer(TsCDaServer server, TsCDaBrowseFilters filters)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            Clear();

            mFilters_ = (filters == null)?new TsCDaBrowseFilters():filters;

            browseTv_.ContextMenuStrip = popupMenu_;

            mSingleServer_                    = new TreeNode(server.ServerName);
            mSingleServer_.ImageIndex         = Resources.IMAGE_LOCAL_SERVER;
            mSingleServer_.SelectedImageIndex = Resources.IMAGE_LOCAL_SERVER;
            mSingleServer_.Tag                = server.Duplicate();

            Connect(mSingleServer_);
            browseTv_.Nodes.Add(mSingleServer_);
        }
        /// <summary>
        /// Displays the address space for the specified server.
        /// </summary>
        public void Initialize(Technosoftware.DaAeHdaClient.Da.TsCDaServer server)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            mServer_ = server;

            TsCDaBrowseFilters filters = new TsCDaBrowseFilters();

            filters.ReturnAllProperties  = true;
            filters.ReturnPropertyValues = true;

            browseCtrl_.ShowSingleServer(mServer_, filters);
            propertiesCtrl_.Initialize(null);

            ShowDialog();

            // ensure server connection in the browse control are closed.
            browseCtrl_.Clear();
        }
        /// <summary>
        /// Initializes the control with the specified server.
        /// </summary>
        public void Initialize(TsCDaServer server)
        {
            // clear the tree view.
            subscriptionTv_.Nodes.Clear();

            // check if nothing to do.
            if (server == null)
            {
                return;
            }

            // connect to server if not already.
            if (!server.IsConnected)
            {
                server.Connect((OpcConnectData)null);
            }

            // add the root node.
            TreeNode node = new TreeNode(server.ServerName);

            node.ImageIndex = node.SelectedImageIndex = Resources.IMAGE_LOCAL_SERVER;
            node.Tag        = server;

            subscriptionTv_.Nodes.Add(node);

            // add any existing subscriptions.
            foreach (TsCDaSubscription subscription in server.Subscriptions)
            {
                AddSubscription(node, subscription);

                if (SubscriptionModified != null)
                {
                    SubscriptionModified(subscription, false);
                }
            }

            // expand root node.
            node.Expand();
        }
        /// <summary>
        /// Removes a subscription an releases all resources.
        /// </summary>
        private void RemoveSubscriptionMI_Click(object sender, System.EventArgs e)
        {
            TreeNode node = subscriptionTv_.SelectedNode;

            if (IsSubscriptionNode(node))
            {
                if (node.Parent != null)
                {
                    try
                    {
                        TsCDaServer server = (TsCDaServer)node.Parent.Tag;
                        server.CancelSubscription((TsCDaSubscription)node.Tag);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }

                    node.Remove();
                }
            }
        }
예제 #12
0
        private void TestMI_Click(object sender, System.EventArgs e)
        {
            try
            {
                TsCDaServer server = (TsCDaServer)m_server;

                TsCDaItem[] items = new TsCDaItem[100];

                for (int ii = 0; ii < items.Length; ii++)
                {
                    items[ii] = new TsCDaItem();

                    items[ii].ItemName     = "Static/ArrayTypes/Object[]";
                    items[ii].ItemPath     = "DA30";
                    items[ii].ClientHandle = ii;
                }

                TsCDaSubscriptionState state = new TsCDaSubscriptionState();

                state.Active     = true;
                state.UpdateRate = 1000;

                ITsCDaSubscription subscription = server.CreateSubscription(state);
                Thread.Sleep(100);

                TsCDaItemResult[] results = subscription.AddItems(items);
                Thread.Sleep(100);

                subscription.RemoveItems(results);
                Thread.Sleep(100);

                server.CancelSubscription(subscription);
                Thread.Sleep(100);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
예제 #13
0
        /// <summary>
        /// Initializes the control with a set of identified results.
        /// </summary>
        public void Initialize(TsCDaServer server, string locale, OpcItemResult[] results)
        {
            MServer = server;
            MLocale = locale;

            MErrors.Clear();

            itemListLv_.Items.Clear();

            // check if there is nothing to do.
            if (results == null || results.Length == 0)
            {
                return;
            }

            foreach (OpcItemResult result in results)
            {
                AddResult(result);
            }

            // adjust the list view columns to fit the data.
            AdjustColumns();
        }
예제 #14
0
        /// <summary>
        /// Initializes the control with a set of item value results.
        /// </summary>
        public void Initialize(TsCDaServer server, string locale, TsCDaItemValueResult[] results)
        {
            m_server = server;
            m_locale = locale;

            m_errors.Clear();

            ItemListLV.Items.Clear();

            // check if there is nothing to do.
            if (results == null || results.Length == 0)
            {
                return;
            }

            foreach (TsCDaItemValueResult result in results)
            {
                AddResult(result);
            }

            // adjust the list view columns to fit the data.
            AdjustColumns();
        }
예제 #15
0
        /// <summary>
        /// Called to connect to a server.
        /// </summary>
        public void OnConnect(OpcServer server)
        {
            // disconnect from the current server.
            OnDisconnect();

            // create a default file name for the server.
            mConfigFile_ = server.ServerName + ".config";

            // load server object from config file if it exists.
            if (File.Exists(mConfigFile_))
            {
                if (OnLoad(false, server.Url))
                {
                    return;
                }
            }

            // use the specified server object directly.
            TsCCpxComplexTypeCache.Server = server_ = (TsCDaServer)server;

            // connect with an empty configuration.
            OnConnect();
        }
예제 #16
0
		void BrowseChildren(OpcItem opcItem, TsCDaBrowseFilters filters,
			IList<TsCDaBrowseElement> elementList, TsCDaServer server)
		{
			TsCDaBrowsePosition position;
			OpcItem path;

			var elements = server.Browse(opcItem, filters, out position);

			if (elements != null)
			{
				foreach (var item in elements)
				{
					item.ItemPath = opcItem.ItemPath + OpcDaTag.SPLITTER + item.ItemName;
					elementList.Add(item);

					if (!item.IsItem)
					{
						path = new OpcItem(item.ItemPath, item.ItemName);
						BrowseChildren(path, filters, elementList, server);
					}
				}
			}
		}
        /// <summary>
        /// Disconnects from the server and clears all objects.
        /// </summary>
        private void Disconnect(TreeNode node, TsCDaServer server)
        {
            // remove all subscriptions.
            foreach (TreeNode child in node.Nodes)
            {
                if (IsSubscriptionNode(child))
                {
                    if (SubscriptionModified != null)
                    {
                        SubscriptionModified((TsCDaSubscription)child.Tag, true);
                    }

                    TsCDaSubscription subscription = (TsCDaSubscription)child.Tag;
                    server.CancelSubscription(subscription);
                    subscription.Dispose();
                }
            }

            // disconnect server.
            server.Disconnect();

            // remove tree from view.
            node.Remove();
        }
        /// <summary>
        /// Fetches the set of type conversions from the server.
        /// </summary>
        /// <param name="server">The server object</param>
        public TsCCpxComplexItem[] GetTypeConversions(TsCDaServer server)
        {
            // only the root item can have type conversions.
            if (_unconvertedItemID != null || _unfilteredItemID != null)
            {
                return(null);
            }

            TsCDaBrowsePosition position = null;

            try
            {
                // look for the 'CPX' branch.
                TsCDaBrowseFilters filters = new TsCDaBrowseFilters {
                    ElementNameFilter = CPX_BRANCH, BrowseFilter = TsCDaBrowseFilter.Branch, ReturnAllProperties = false, PropertyIDs = null, ReturnPropertyValues = false
                };

                TsCDaBrowseElement[] elements = server.Browse(this, filters, out position);

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

                // release the browse position object.
                if (position != null)
                {
                    position.Dispose();
                    position = null;
                }

                // browse for type conversions.
                OpcItem itemID = new OpcItem(elements[0].ItemPath, elements[0].ItemName);

                filters.ElementNameFilter    = null;
                filters.BrowseFilter         = TsCDaBrowseFilter.Item;
                filters.ReturnAllProperties  = false;
                filters.PropertyIDs          = CPX_PROPERTIES;
                filters.ReturnPropertyValues = true;

                elements = server.Browse(itemID, filters, out position);

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

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

                Array.ForEach(elements, element =>
                {
                    if (element.Name != CPX_DATA_FILTERS)
                    {
                        TsCCpxComplexItem item = new TsCCpxComplexItem();
                        if (item.Init(element))
                        {
                            // check if data filters supported for type conversion.
                            item.GetDataFilterItem(server);
                            conversions.Add(item);
                        }
                    }
                });

                // return the set of available conversions.
                return((TsCCpxComplexItem[])conversions.ToArray(typeof(TsCCpxComplexItem)));
            }
            finally
            {
                if (position != null)
                {
                    position.Dispose();
                    position = null;
                }
            }
        }
예제 #19
0
        /// <summary>
        /// Loads the configuration for the current server.
        /// </summary>
        private bool OnLoad(bool prompt, OpcUrl url)
        {
            Stream stream = null;

            try
            {
                Cursor = Cursors.WaitCursor;

                // prompt user to select a configuration file.
                if (prompt)
                {
                    OpenFileDialog dialog = new OpenFileDialog();

                    dialog.CheckFileExists = true;
                    dialog.CheckPathExists = true;
                    dialog.DefaultExt      = ".config";
                    dialog.Filter          = "Config Files (*.config)|*.config|All Files (*.*)|*.*";
                    dialog.Multiselect     = false;
                    dialog.ValidateNames   = true;
                    dialog.Title           = "Open Server Configuration File";
                    dialog.FileName        = mConfigFile_;

                    if (dialog.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }

                    // save the new config file name.
                    mConfigFile_ = dialog.FileName;
                }

                // disconnect from current server.
                OnDisconnect();

                // open configuration file.
                stream = new FileStream(mConfigFile_, FileMode.Open, FileAccess.Read, FileShare.Read);

                // deserialize the server object.
                TsCCpxComplexTypeCache.Server = server_ = (TsCDaServer) new BinaryFormatter().Deserialize(stream);

                // overrided default url.
                if (url != null)
                {
                    server_.Url = url;
                }

                // connect to new server.
                OnConnect();

                // load succeeded.
                return(true);
            }
            catch (Exception e)
            {
                if (prompt)
                {
                    MessageBox.Show(e.Message);
                }
                return(false);
            }
            finally
            {
                // close the stream.
                if (stream != null)
                {
                    stream.Close();
                }

                Cursor = Cursors.Default;
            }
        }
        /// <summary>
        /// Creates a new data filter.
        /// </summary>
        /// <param name="server">The server object</param>
        /// <param name="filterName">The name of the filter</param>
        /// <param name="filterValue">The value of the filter</param>
        public TsCCpxComplexItem CreateDataFilter(TsCDaServer server, string filterName, string filterValue)
        {
            // not a valid operation for data filter items.
            if (_unfilteredItemID != null)
            {
                return(null);
            }

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

            TsCDaBrowsePosition position = null;

            try
            {
                // write the desired filter to the server.
                TsCDaItemValue item = new TsCDaItemValue(_filterItem);

                // create the filter parameters document.
                using (StringWriter ostrm = new StringWriter())
                {
                    using (XmlTextWriter writer = new XmlTextWriter(ostrm))
                    {
                        writer.WriteStartElement("DataFilters");
                        writer.WriteAttributeString("Name", filterName);
                        writer.WriteString(filterValue);
                        writer.WriteEndElement();
                        writer.Close();
                    }
                    // create the value to write.
                    item.Value = ostrm.ToString();
                }
                item.Quality            = TsCDaQuality.Bad;
                item.QualitySpecified   = false;
                item.Timestamp          = DateTime.MinValue;
                item.TimestampSpecified = false;

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

                if (result == null || result.Length == 0)
                {
                    throw new OpcResultException(new OpcResult((int)OpcResult.E_FAIL.Code, OpcResult.FuncCallType.SysFuncCall, null), "Unexpected results returned from server.");
                }

                if (result[0].Result.Failed())
                {
                    throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not create new data filter.");
                }

                // browse for new data filter item.
                TsCDaBrowseFilters filters = new TsCDaBrowseFilters {
                    ElementNameFilter = filterName, BrowseFilter = TsCDaBrowseFilter.Item, ReturnAllProperties = false, PropertyIDs = CPX_PROPERTIES, ReturnPropertyValues = true
                };

                TsCDaBrowseElement[] elements = server.Browse(_filterItem, filters, out position);

                // nothing found.
                if (elements == null || elements.Length == 0)
                {
                    throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not browse to new data filter.");
                }

                TsCCpxComplexItem filterItem = new TsCCpxComplexItem();

                if (!filterItem.Init(elements[0]))
                {
                    throw new OpcResultException(new OpcResult((int)OpcResult.Cpx.E_FILTER_ERROR.Code, OpcResult.FuncCallType.SysFuncCall, null), "Could not initialize to new data filter.");
                }

                // return the new data filter.
                return(filterItem);
            }
            finally
            {
                if (position != null)
                {
                    position.Dispose();
                    position = null;
                }
            }
        }
        ///////////////////////////////////////////////////////////////////////
        #region OPC Sample Functionality

        void DoOPCCalls()
        {
            try
            {
                const string serverUrl = "opcda://localhost/Technosoftware.DaSample";

                Console.WriteLine();
                Console.WriteLine("Simple OPC DA Client based on the OPC DA/AE/HDA Client SDK .NET");
                Console.WriteLine("--------------------------------------------------------------");
                Console.Write("   Press <Enter> to connect to "); Console.WriteLine(serverUrl);
                Console.ReadLine();
                Console.WriteLine("   Please wait...");

                //OpcBase.ValidateLicense("License Key");
                TsCDaServer myDaServer = new TsCDaServer();

                // Connect to the server
                myDaServer.Connect(serverUrl);

                OpcServerStatus status = myDaServer.GetServerStatus();

                Console.WriteLine("   Connected, press <Enter> to create an active group object and add several items.");
                Console.ReadLine();

                // Add a group with default values Active = true and UpdateRate = 500ms
                TsCDaSubscription      group;
                TsCDaSubscriptionState groupState = new TsCDaSubscriptionState {
                    Name = "MyGroup"                                                              /* Group Name*/
                };
                group = (TsCDaSubscription)myDaServer.CreateSubscription(groupState);

                // Add Items
                TsCDaItem[]       items = new TsCDaItem[2];
                TsCDaItemResult[] itemResults;
                items[0]                 = new TsCDaItem();
                items[0].ItemName        = "SimpleTypes.InOut.Integer";               // Item Name
                items[0].ClientHandle    = 100;                                       // Client Handle
                items[0].Active          = true;
                items[0].ActiveSpecified = true;

                items[1]                 = new TsCDaItem();
                items[1].ItemName        = "SimpleTypes.InOut.Short";                 // Item Name
                items[1].ClientHandle    = 200;                                       // Client Handle
                items[1].Active          = false;
                items[1].ActiveSpecified = true;

                TsCDaItem[] arAddedItems;
                itemResults = group.AddItems(items);

                for (int i = 0; i < itemResults.GetLength(0); i++)
                {
                    if (itemResults[i].Result.IsError())
                    {
                        Console.WriteLine(String.Format("   Item {0} could not be added to the group", itemResults[i].ItemName));
                    }
                }
                arAddedItems = itemResults;

                OpcItemResult[] res;
                IOpcRequest     m_ITRequest;

                TsCDaItemValue[] arItemValues = new TsCDaItemValue[1];
                arItemValues[0] = new TsCDaItemValue();
                arItemValues[0].ClientHandle = 100;
                arItemValues[0].ItemName     = "SimpleTypes.InOut.Short";

                int val = 0;
                do
                {
                    arItemValues[0].Value = val;

                    res = group.Write(arItemValues, 321, new TsCDaWriteCompleteEventHandler(OnWriteCompleteEvent), out m_ITRequest);
                    val++;
                } while (val < 1000);

                Console.ReadLine();


                group.Dispose();                                                    // optionally, it's not required
                myDaServer.Disconnect();                                            // optionally, it's not required
                Console.ReadLine();
                Console.WriteLine("   Disconnected from the server.");
                Console.WriteLine();
            }
            catch (OpcResultException e)
            {
                Console.WriteLine("   " + e.Message);
                Console.ReadLine();
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("   " + e.Message);
                Console.ReadLine();
                return;
            }
        }
예제 #22
0
		public static OpcServerStatus GetServerStatus(OpcDaServer server)
		{
			var opcServer = _Servers.FirstOrDefault(x => x.Item1.ServerName == server.ServerName);

			if (opcServer == null)
			{
				var srv = GetOpcDaServers().FirstOrDefault(s => s.ServerName == server.ServerName);
				if (srv != null)
				{
					var url = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, server.Url);
					var opcSrv = new TsCDaServer();
					try
					{
						opcSrv.Connect(url, null);
						var result = opcSrv.GetServerStatus();
						opcSrv.Disconnect();
						return result;
					}
					catch
					{
						return null;
					}
				}
				else
					return null;
			}
			else
			{
				return opcServer.Item1.IsConnected ? opcServer.Item1.GetServerStatus() : null;
			}
		}
예제 #23
0
		void OnConnect()
		{
			_activeOpcServer = new TsCDaServer();
			var opcUrl = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, SelectedOpcServer.Url.ToString());
			_activeOpcServer.Connect(opcUrl, null); // во второй параметр передаются данные для 
													// авторизации пользователя на удалённом сервере
			_activeOpcServer.ServerShutdownEvent += EventHandler_activeOpcServer_ServerShutdownEvent;
		}
예제 #24
0
 /// <summary>
 /// Prompts user to edit request option parameters in a modal dialog.
 /// </summary>
 public void ShowDialog(TsCDaServer server)
 {
     ShowDialog(server, null);
 }
        /// <summary>
        /// Browses for children of the element at the current node.
        /// </summary>
        private void GetProperties(TreeNode node)
        {
            try
            {
                // get the server for the current node.
                OpcServer selection = FindServer(node);

                if (!typeof(TsCDaServer).IsInstanceOfType(selection))
                {
                    return;
                }

                TsCDaServer server = (TsCDaServer)selection;

                // get the current element to use for a get properties.
                TsCDaBrowseElement element = null;

                if (node.Tag != null && node.Tag.GetType() == typeof(TsCDaBrowseElement))
                {
                    element = (TsCDaBrowseElement)node.Tag;
                }

                // can only get properties for an item.
                if (!element.IsItem)
                {
                    return;
                }

                // clear the node children.
                node.Nodes.Clear();

                // begin a browse.
                OpcItem itemID = new OpcItem(element.ItemPath, element.ItemName);

                TsCDaItemPropertyCollection[] propertyLists = server.GetProperties(
                    new OpcItem[] { itemID },
                    m_filters.PropertyIDs,
                    m_filters.ReturnPropertyValues);

                if (propertyLists != null)
                {
                    foreach (TsCDaItemPropertyCollection propertyList in propertyLists)
                    {
                        foreach (TsCDaItemProperty property in propertyList)
                        {
                            AddItemProperty(node, property);
                        }

                        // update element properties.
                        element.Properties = (TsCDaItemProperty[])propertyList.ToArray(typeof(TsCDaItemProperty));
                    }
                }

                node.Expand();

                // send notification that property list changed.
                if (ElementSelected != null)
                {
                    ElementSelected(element);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
예제 #26
0
		void OnDisconnect()
		{
			try
			{
				if (CancelSubscriptionCommand.CanExecute(null))
				{
					CancelSubscriptionCommand.Execute();
				}
				_activeOpcServer.ServerShutdownEvent -= EventHandler_activeOpcServer_ServerShutdownEvent;
				_activeOpcServer.Disconnect();
				_activeOpcServer = null;
			}
			catch (Exception ex)
			{
				System.Windows.MessageBox.Show(ex.Message);
			}
		}
        /// <summary>
        /// Fetches the item id for the data filters items and stores it in the internal cache.
        /// </summary>
        /// <param name="server">The server object</param>
        public void GetDataFilterItem(TsCDaServer server)
        {
            _filterItem = null;

            // not a valid operation for data filter items.
            if (_unfilteredItemID != null)
            {
                return;
            }

            TsCDaBrowsePosition position = null;

            try
            {
                OpcItem itemID = new OpcItem(this);

                // browse any existing filter instances.
                TsCDaBrowseFilters filters = new TsCDaBrowseFilters {
                    ElementNameFilter = CPX_DATA_FILTERS, BrowseFilter = TsCDaBrowseFilter.All, ReturnAllProperties = false, PropertyIDs = null, ReturnPropertyValues = false
                };

                TsCDaBrowseElement[] elements = null;

                // browse for the 'CPX' branch first.
                if (_unconvertedItemID == null)
                {
                    filters.ElementNameFilter = CPX_BRANCH;

                    elements = server.Browse(itemID, filters, out position);

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

                    // release the position object.
                    if (position != null)
                    {
                        position.Dispose();
                        position = null;
                    }

                    // update the item for the next browse operation.
                    itemID = new OpcItem(elements[0].ItemPath, elements[0].ItemName);

                    filters.ElementNameFilter = CPX_DATA_FILTERS;
                }

                // browse for the 'DataFilters' branch.
                elements = server.Browse(itemID, filters, out position);

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

                _filterItem = new OpcItem(elements[0].ItemPath, elements[0].ItemName);
            }
            finally
            {
                if (position != null)
                {
                    position.Dispose();
                    position = null;
                }
            }
        }
        /// <summary>
        /// Returns a list of servers that support the specified specification on the specified host.
        /// </summary>
        public OpcServer[] GetAvailableServers(OpcSpecification specification, string host, OpcConnectData connectData)
        {
            lock (this)
            {
                NetworkCredential credentials = (connectData != null)?connectData.GetCredential(null, null):null;

                // connect to the server.
                m_server = (IOPCServerList2)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.
                    Interop.ReleaseServer(enumerator);
                    enumerator = null;

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

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

                            OpcServer server = null;

                            if (specification == OpcSpecification.OPC_DA_30)
                            {
                                server = new TsCDaServer(factory, url);
                            }

                            else if (specification == OpcSpecification.OPC_DA_20)
                            {
                                server = new TsCDaServer(factory, url);
                            }

                            else if (specification == OpcSpecification.OPC_AE_10)
                            {
                                server = new TsCAeServer(factory, url);
                            }

                            else if (specification == OpcSpecification.OPC_HDA_10)
                            {
                                server = new TsCHdaServer(factory, url);
                            }

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

                    return((OpcServer[])servers.ToArray(typeof(OpcServer)));
                }
                finally
                {
                    // free the server.
                    Interop.ReleaseServer(m_server);
                    m_server = null;
                }
            }
        }
 /// <summary>
 /// Displays the address space of the server in a modal dialog.
 /// </summary>
 private void BrowseItems(TsCDaServer server)
 {
     new BrowseItemsDlg().Initialize(server);
 }
 /// <summary>
 /// Prompts the user to select a set of items and reads them from the server.
 /// </summary>
 private void ReadItems(TsCDaServer server)
 {
     new ReadItemsDlg().ShowDialog(server);
 }
        /// <summary>
        /// Browses for children of the element at the current node.
        /// </summary>
        private void Browse(TreeNode node)
        {
            try
            {
                // get the server for the current node.
                TsCDaServer server = FindServer(node);

                // get the current element to use for a browse.
                TsCDaBrowseElement parent = null;
                OpcItem            itemID = null;

                if (node.Tag != null && node.Tag.GetType() == typeof(TsCDaBrowseElement))
                {
                    parent = (TsCDaBrowseElement)node.Tag;
                    itemID = new OpcItem(parent.ItemPath, parent.ItemName);
                }

                // clear the node children.
                node.Nodes.Clear();

                // add properties
                if (parent != null && parent.Properties != null)
                {
                    foreach (TsCDaItemProperty property in parent.Properties)
                    {
                        AddItemProperty(node, property);
                    }
                }

                // begin a browse.
                OpcClientSdk.Da.TsCDaBrowsePosition position = null;
                TsCDaBrowseElement[] elements = server.Browse(itemID, m_filters, out position);

                // add children.
                if (elements != null)
                {
                    foreach (TsCDaBrowseElement element in elements)
                    {
                        AddBrowseElement(node, element);
                    }

                    node.Expand();
                }

                // loop until all elements have been fetched.
                while (position != null)
                {
                    DialogResult result = MessageBox.Show(
                        "More items meeting search criteria exist. Continue browse?",
                        "Browse Items",
                        MessageBoxButtons.YesNo);

                    if (result == DialogResult.No)
                    {
                        break;
                    }

                    // fetch next batch of elements,.
                    elements = server.BrowseNext(ref position);

                    // add children.
                    if (elements != null)
                    {
                        foreach (TsCDaBrowseElement element in elements)
                        {
                            AddBrowseElement(node, element);
                        }

                        node.Expand();
                    }
                }

                // send notification that property list changed.
                if (ElementSelected != null)
                {
                    if (node.Tag.GetType() == typeof(TsCDaBrowseElement))
                    {
                        ElementSelected((TsCDaBrowseElement)node.Tag);
                    }
                    else
                    {
                        ElementSelected(null);
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
 /// <summary>
 /// Prompts the user to specify a set of item values and writes them to the server.
 /// </summary>
 private void WriteItems(TsCDaServer server)
 {
     new WriteItemsDlg().ShowDialog(server);
 }
예제 #33
0
        /// <summary>
        /// Prompts user to edit request option parameters in a modal dialog.
        /// </summary>
        private void ShowDialog(TsCDaServer server, TsCDaSubscription subscription)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server");
            }

            // get supported locales.
            localeCtrl_.SetSupportedLocales(server.SupportedLocales);

            // set locale.
            string locale = (subscription == null)?server.Locale:subscription.Locale;

            localeCtrl_.Locale         = locale;
            localeSpecifiedCb_.Checked = locale != null;

            // get filters.
            int filters = (subscription == null)?server.Filters:subscription.Filters;

            itemNameCb_.Checked       = ((filters & (int)TsCDaResultFilter.ItemName) != 0);
            itemPathCb_.Checked       = ((filters & (int)TsCDaResultFilter.ItemPath) != 0);
            clientHandleCb_.Checked   = ((filters & (int)TsCDaResultFilter.ClientHandle) != 0);
            itemTimeCb_.Checked       = ((filters & (int)TsCDaResultFilter.ItemTime) != 0);
            errorTextCb_.Checked      = ((filters & (int)TsCDaResultFilter.ErrorText) != 0);
            diagnosticInfoCb_.Checked = ((filters & (int)TsCDaResultFilter.DiagnosticInfo) != 0);

            // show dialog.
            while (ShowDialog() == DialogResult.OK)
            {
                // update locale.
                try
                {
                    locale = null;

                    if (localeSpecifiedCb_.Checked)
                    {
                        locale = localeCtrl_.Locale;
                    }

                    if (subscription == null)
                    {
                        server.SetLocale(locale);
                    }
                    else
                    {
                        TsCDaSubscriptionState state = new TsCDaSubscriptionState();
                        state.Locale = locale;
                        subscription.ModifyState((int)TsCDaStateMask.Locale, state);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    continue;
                }

                // update filters.
                filters = 0;

                filters |= (itemNameCb_.Checked)?(int)TsCDaResultFilter.ItemName:0;
                filters |= (itemPathCb_.Checked)?(int)TsCDaResultFilter.ItemPath:0;
                filters |= (clientHandleCb_.Checked)?(int)TsCDaResultFilter.ClientHandle:0;
                filters |= (itemTimeCb_.Checked)?(int)TsCDaResultFilter.ItemTime:0;
                filters |= (errorTextCb_.Checked)?(int)TsCDaResultFilter.ErrorText:0;
                filters |= (diagnosticInfoCb_.Checked)?(int)TsCDaResultFilter.DiagnosticInfo:0;

                try
                {
                    if (subscription == null)
                    {
                        server.SetResultFilters(filters);
                    }
                    else
                    {
                        subscription.SetResultFilters(filters);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    continue;
                }

                // break out of loop if no error.
                break;
            }
        }
예제 #34
0
		public static void Start()
		{
			var servers = GetOpcDaServers();

			OpcDaServers =
				ConfigurationCashHelper.SystemConfiguration.AutomationConfiguration.OpcDaTsServers.ToArray();

			foreach (var server in OpcDaServers)
			{
				if (!servers.Any(x => x.Url == server.Url))
				{
					Notifier.UILog(string.Format("Не удалось запусть OPC DA сервер {0}. Сервер не найден", server.Url), true);
					//MainViewModel.SetReportAddress("<Ошибка>");
					continue;
				}
				var url = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, server.Url);
				var opcServer = new TsCDaServer();

				try
				{
					opcServer.Connect(url, null);
					opcServer.ServerShutdownEvent += reason =>
					{
						var srv = _Servers.FirstOrDefault(x => x.Item1.ServerName == opcServer.ServerName);
						if (srv != null)
						{
							try
							{
								srv.Item1.CancelSubscription(srv.Item2);
							}
							catch { }

							// Ищем все теги для данного сервера у удаляем их
							var tags = _tags.Where(t => t.ServerName == opcServer.ServerName);

							foreach (var tag in tags)
							{
								_tags.Remove(tag);
							}

							_Servers.Remove(srv);
						}
					};

					// Создаём объект подписки
					var id = Guid.NewGuid().ToString();
					var subscriptionState = new TsCDaSubscriptionState
					{
						Name = id,
						ClientHandle = id,
						Deadband = 0,
						UpdateRate = 1000,
						KeepAlive = 10000
					};

					var subscription = (TsCDaSubscription)opcServer.CreateSubscription(subscriptionState);

					_Servers.Add(Tuple.Create<TsCDaServer, TsCDaSubscription>(opcServer, subscription));

					// Добавляем в объект подписки выбранные теги
					List<TsCDaItem> list = server.Tags.Select(tag => new TsCDaItem
						{
							ItemName = tag.ElementName,
							ClientHandle = tag.ElementName // Уникальный Id определяемый пользователем
						}).ToList();

					// Добавляем теги и проверяем результат данной операции
					var results = subscription.AddItems(list.ToArray());

					var errors = results.Where(result => result.Result.IsError());

					if (errors.Count() > 0)
					{
						StringBuilder msg = new StringBuilder();
						msg.Append("Не удалось добавить теги для подписки. Возникли ошибки в тегах:");
						foreach (var error in errors)
						{
							msg.Append(String.Format("ItemName={0} ClientHandle={1} Description={2}; ",
								error.ItemName, error.ClientHandle, error.Result.Description()));
						}
						//throw new InvalidOperationException(msg.ToString());
					}

					subscription.DataChangedEvent += EventHandler_Subscription_DataChangedEvent;

					_tags.AddRange(server.Tags.Select(tag => new OpcDaTagValue
					{
						ElementName = tag.ElementName,
						TagId = tag.TagId,
						Uid = tag.Uid,
						Path = tag.Path,
						TypeNameOfValue = tag.TypeNameOfValue,
						AccessRights = tag.AccessRights,
						ScanRate = tag.ScanRate,
						ServerId = server.Uid,
						ServerName = server.ServerName
					}));
				}
				catch (Exception ex)
				{
					Notifier.UILog(ex.Message, true);
				}
			}
		}
예제 #35
0
        public void Run()
        {
            try
            {
                const string serverUrl = "opcda://localhost/Technosoftware.DaSample";

                Console.WriteLine();
                Console.WriteLine("Simple OPC DA Client based on the OPC DA/AE/HDA Client SDK .NET Standard");
                Console.WriteLine("------------------------------------------------------------------------");
                Console.Write("   Press <Enter> to connect to "); Console.WriteLine(serverUrl);
                Console.ReadLine();
                Console.WriteLine("   Please wait...");

                TsCDaServer myDaServer = new TsCDaServer();

                // Connect to the server
                myDaServer.Connect(serverUrl);

                // Get the status from the server
                OpcServerStatus status = myDaServer.GetServerStatus();
                Console.WriteLine($"   Status of Server is {status.ServerState}");

                Console.WriteLine("   Connected, press <Enter> to create an active group object and add several items.");
                Console.ReadLine();

                // Add a group with default values Active = true and UpdateRate = 500ms
                TsCDaSubscriptionState groupState = new TsCDaSubscriptionState {
                    Name = "MyGroup"                                                              /* Group Name*/
                };
                var group = (TsCDaSubscription)myDaServer.CreateSubscription(groupState);

                // Add Items
                TsCDaItem[] items = new TsCDaItem[4];
                items[0] = new TsCDaItem
                {
                    ItemName        = "SimulatedData.Ramp",
                    ClientHandle    = 100,
                    MaxAgeSpecified = true,
                    MaxAge          = 0,
                    Active          = true,
                    ActiveSpecified = true
                };
                // Item Name
                // Client Handle
                // Read from Cache

                items[1] = new TsCDaItem
                {
                    ItemName        = "CTT.SimpleTypes.InOut.Integer",
                    ClientHandle    = 150,
                    Active          = true,
                    ActiveSpecified = true
                };
                // Item Name
                // Client Handle

                items[2] = new TsCDaItem
                {
                    ItemName        = "CTT.SimpleTypes.InOut.Short",
                    ClientHandle    = 200,
                    Active          = false,
                    ActiveSpecified = true
                };
                // Item Name
                // Client Handle

                items[3] = new TsCDaItem
                {
                    ItemName = "CTT.Arrays.InOut.Word[]", ClientHandle = 250, Active = false, ActiveSpecified = true
                };
                // Item Name
                // Client Handle

                // Synchronous Read with server read function (DA 3.0) without a group
                TsCDaItemValueResult[] itemValues = myDaServer.Read(items);

                for (int i = 0; i < itemValues.GetLength(0); i++)
                {
                    if (itemValues[i].Result.IsError())
                    {
                        Console.WriteLine($"   Item {itemValues[i].ItemName} could not be read");
                    }
                }

                var itemResults = group.AddItems(items);

                for (int i = 0; i < itemResults.GetLength(0); i++)
                {
                    if (itemResults[i].Result.IsError())
                    {
                        Console.WriteLine($"   Item {itemResults[i].ItemName} could not be added to the group");
                    }
                }

                Console.WriteLine("");
                Console.WriteLine("   Group and items added, press <Enter> to create a data change subscription");
                Console.WriteLine("   and press <Enter> again to deactivate the data change subscription.");
                Console.WriteLine("   This stops the reception of data change notifications.");
                Console.ReadLine();

                group.DataChangedEvent += OnDataChangeEvent;

                Console.ReadLine();

                // Set group inactive
                groupState.Active = false;
                group.ModifyState((int)TsCDaStateMask.Active, groupState);

                Console.WriteLine("   Data change subscription deactivated, press <Enter> to remove all");
                Console.WriteLine("   and disconnect from the server.");
                group.Dispose();
                myDaServer.Disconnect();
                myDaServer.Dispose();
                Console.ReadLine();
                Console.WriteLine("   Disconnected from the server.");
                Console.WriteLine();
            }
            catch (OpcResultException e)
            {
                Console.WriteLine("   " + e.Message);

                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("   " + e.Message);
                Console.ReadLine();
            }
        }
 /// <summary>
 /// Displays the server status in a model dialog.
 /// </summary>
 private void ViewStatus(TsCDaServer server)
 {
     new ServerStatusDlg().ShowDialog(server);
 }