/// <summary>
        /// Connects to the server and browses for top level nodes.
        /// </summary>
        private void Connect(TreeNode node)
        {
            try
            {
                if (!IsServerNode(node))
                {
                    return;
                }

                // get the server for the current node.
                TsCDaServer server = (TsCDaServer)node.Tag;

                // connect to server if not already connected.
                if (!server.IsConnected)
                {
                    server.Connect(FindConnectData(node));
                }

                // browse for top level elements.
                Browse(node);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        /// <summary>
        /// Set things in motion so your service can do its work.
        /// </summary>
        protected override void OnStart(string[] args)
        {
            const string serverName = "opcda://localhost/Technosoftware.DaSample";

            try
            {
                myDaServer = new TsCDaServer();

                myDaServer.Connect(serverName);
                OpcServerStatus status = myDaServer.GetServerStatus();

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

                // Add Items
                TsCDaItem[]       items = new TsCDaItem[3];
                TsCDaItemResult[] itemResults;
                items[0]                 = new TsCDaItem();
                items[0].ItemName        = "SimulatedData.Ramp";                      // Item Name
                items[0].ClientHandle    = 100;                                       // Client Handle
                items[0].MaxAgeSpecified = true;
                items[0].MaxAge          = Int32.MaxValue;
                items[1]                 = new TsCDaItem();
                items[1].ItemName        = "SimulatedData.Random";                    // Item Name
                items[1].ClientHandle    = 150;                                       // Client Handle
                items[2]                 = new TsCDaItem();
                items[2].ItemName        = "InOut_I4";                                // Item Name
                items[2].ClientHandle    = 200;                                       // Client Handle

                TsCDaItem[] arAddedItems;
                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");
                    }
                }

                arAddedItems = itemResults;

                group.DataChangedEvent += new TsCDaDataChangedEventHandler(DataChangeHandler);
                Console.WriteLine("Wait 5 seconds ...");
                //System.Threading.Thread.Sleep(5000);
            }
            catch (OpcResultException e)
            {
                Console.WriteLine("   " + e.Message);
                return;
            }
            catch (Exception e)
            {
                Console.WriteLine("   " + e.Message);
                return;
            }
        }
Example #3
0
        //----------------------------------------------------------------------------------------------------------------------
        // btnConnect_Click
        //-----------------------
        // This method tries to connect to the specified OPC Server.
        // If connected successfully, this method also registers the name of the client with the server and
        // adds an OPC Group.
        //----------------------------------------------------------------------------------------------------------------------
        private void btnConnect_Click(object sender, EventArgs e)
        {
            TsCDaBrowseElement[] BrowserElement;
            TsCDaBrowsePosition  BrowserPos;
            OpcItem Path = new OpcItem("");

            _filter.BrowseFilter         = TsCDaBrowseFilter.All;
            _filter.ReturnAllProperties  = true;
            _filter.ReturnPropertyValues = true;

            try
            {
                Cursor = Cursors.WaitCursor;
                if (!_myServer.IsConnected)
                {
                    // No connection to server, connect to it
                    _textBoxServerUrl.Enabled = false;

                    _myServer.Connect(_textBoxServerUrl.Text);          // Connect now with Server
                    BrowserElement = _myServer.Browse(Path, _filter, out BrowserPos);

                    /// All succeeded, update buttons and text fields
                    _textBoxServerUrl.Enabled = false;
                    _btnConnect.Text          = "Disconnect";
                    BrowseCTRL.ShowSingleServer(_myServer, _filter);
                    PropertiesCTRL.Initialize(null);
                }
                else
                {
                    // connection to server exists, disconnect to it
                    _textBoxServerUrl.Enabled = true;

                    BrowseCTRL.Clear();
                    PropertiesCTRL.Initialize(null);
                    _myServer.Disconnect();
                    _btnConnect.Text = "Connect";
                }
                Cursor = Cursors.Default;                                                       // Set default cursor
            }
            catch (OpcResultException exe)
            {
                Cursor = Cursors.Default;                                                       /// Set default cursor
                MessageBox.Show(exe.Message, exe.Source, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _textBoxServerUrl.Enabled = true;
                _btnConnect.Text          = "Connect";
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;                                                       /// Set default cursor
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _textBoxServerUrl.Enabled = true;
                _btnConnect.Text          = "Connect";
            }
        }
Example #4
0
        /// <summary>
        /// Called to connect to a server.
        /// </summary>
        public void OnConnect()
        {
            if (server_ == null)
            {
                return;
            }

            Cursor = Cursors.WaitCursor;

            try
            {
                OpcUserIdentity credentials = null;

                do
                {
                    try
                    {
                        server_.ForceDa20Usage = forceDa20Usage_;
                        server_.Connect(new OpcConnectData(credentials, mProxy_));
                        break;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }

                    credentials = new NetworkCredentialsDlg().ShowDialog(credentials);
                }while (credentials != null);

                // select all filters by default.
                server_.SetResultFilters((int)TsCDaResultFilter.All);

                // initialize controls.
                statusCtrl_.Start(server_);
                updatesCtrl_.Initialize(server_);
                subscriptionCtrl_.Initialize(server_);
                selectServerCtrl_.OnConnect(server_);

                // register for shutdown events.
                server_.ServerShutdownEvent += Server_ServerShutdown;

                // save settings.
                SaveSettings();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                TsCCpxComplexTypeCache.Server = server_ = null;
            }

            Cursor = Cursors.Default;
        }
Example #5
0
        /// <summary>
        /// Called to connect to a target.
        /// </summary>
        public void OnConnectTarget(OpcServer server)
        {
            if (m_target != null)
            {
                m_target.Disconnect();
                m_target.Dispose();
                m_target = null;
            }

            // use the specified server object directly.
            m_target = (TsCDaServer)server;

            Cursor = Cursors.WaitCursor;

            try
            {
                OpcUserIdentity credentials = null;

                do
                {
                    try
                    {
                        m_target.Connect(new OpcConnectData(credentials, m_proxy));
                        break;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }

                    credentials = new NetworkCredentialsDlg().ShowDialog(credentials);
                }while (credentials != null);

                // select all filters by default.
                m_target.SetResultFilters((int)TsCDaResultFilter.All);

                // initialize controls.
                SelectTargetCTRL.OnConnect(m_target);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                m_target = null;
            }

            Cursor = Cursors.Default;
        }
Example #6
0
        /// <summary>
        /// Called to connect to a server.
        /// </summary>
        public void OnConnect()
        {
            Cursor = Cursors.WaitCursor;

            try
            {
                OpcUserIdentity credentials = null;

                do
                {
                    try
                    {
                        m_server.ForceDa20Usage = _forceDa20Usage;
                        m_server.Connect(new OpcConnectData(credentials, m_proxy));
                        break;
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message);
                    }

                    credentials = new NetworkCredentialsDlg().ShowDialog(credentials);
                }while (credentials != null);

                // select all filters by default.
                m_server.SetResultFilters((int)TsCDaResultFilter.All);

                // initialize controls.
                StatusCTRL.Start(m_server);
                UpdatesCTRL.Initialize(m_server);
                SubscriptionCTRL.Initialize(m_server);
                SelectServerCTRL.OnConnect(m_server);

                // register for shutdown events.
                m_server.ServerShutdownEvent += new OpcServerShutdownEventHandler(Server_ServerShutdown);

                // save settings.
                SaveSettings();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                TsCCpxComplexTypeCache.Server = m_server = null;
            }

            Cursor = Cursors.Default;
        }
        /// <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();
        }
Example #8
0
        //----------------------------------------------------------------------------------------------------------------------
        // btnConnect_Click
        //-----------------------
        // This method tries to connect to the specified OPC Server.
        // If connected successfully, this method also registers the name of the client with the server and
        // adds an OPC Group.
        //----------------------------------------------------------------------------------------------------------------------
        private void btnConnect_Click(object sender, System.EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;

                /// Check the correct sDefaultItem
                if (CboxListServer.Text == m_sDefaultServer)
                {
                    txtboxOpcItem.Text = m_sDefaultItem;
                }
                else
                {
                    txtboxOpcItem.Text = null;
                }

                OpcUrl opcUrl = new OpcUrl(OpcSpecification.OPC_DA_20, OpcUrlScheme.DA, CboxListServer.Text);
                m_OpcDaServer.Connect(opcUrl, null);    /// Connect now with Server
                Cursor = Cursors.Default;               /// Set default cursor

                /// All succeeded, update buttons and text fields
                CboxListServer.Enabled = false;
                btnConnect.Enabled     = false;
                txtboxOpcItem.Enabled  = true;
                btnAddItem.Enabled     = true;
            }
            catch (OpcResultException exe)
            {
                Cursor = Cursors.Default;                                                       /// Set default cursor
                MessageBox.Show(exe.Message, exe.Source, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;                                                       /// Set default cursor
                MessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Example #9
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();
            }
        }
        ///////////////////////////////////////////////////////////////////////
        #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;
            }
        }
Example #11
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);
				}
			}
		}
Example #12
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;
			}
		}
		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;
		}