/// <summary>
        /// Creates a subscription with the specified parameters.
        /// </summary>
        private void DoCreate()
        {
            try
            {
                // assign a globally unique handle to the subscription.
                TsCDaSubscriptionState state = (TsCDaSubscriptionState)subscriptionCtrl_.Get();

                state.ClientHandle = Guid.NewGuid().ToString();

                // create the subscription.
                mSubscription_ = (TsCDaSubscription)mServer_.CreateSubscription(state);

                // move to add items panel.
                backBtn_.Enabled          = true;
                nextBtn_.Enabled          = true;
                cancelBtn_.Visible        = false;
                doneBtn_.Visible          = true;
                optionsBtn_.Visible       = true;
                subscriptionCtrl_.Visible = false;
                browseCtrl_.Visible       = true;
                itemsCtrl_.Visible        = true;
                resultsCtrl_.Visible      = false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Example #2
0
 /// <summary>
 /// Creates a new instance of a subscription.
 /// </summary>
 protected virtual Subscription CreateSubscription(
     object group,
     TsCDaSubscriptionState state,
     int filters)
 {
     return(new Subscription(group, state, filters));
 }
Example #3
0
        /// <summary>
        /// Creates a new object.
        /// </summary>
        public object Create()
        {
            TsCDaSubscriptionState state = new TsCDaSubscriptionState();

            state.UpdateRate = 1000;
            return(state);
        }
Example #4
0
        /// <summary>
        /// Creates a subscription with the specified parameters.
        /// </summary>
        private void DoCreate()
        {
            try
            {
                // assign a globally unique handle to the subscription.
                TsCDaSubscriptionState state = (TsCDaSubscriptionState)SubscriptionCTRL.Get();

                state.ClientHandle = Guid.NewGuid().ToString();

                // create the subscription.
                m_subscription = (TsCDaSubscription)m_server.CreateSubscription(state);

                // move to add items panel.
                BackBTN.Enabled          = true;
                NextBTN.Enabled          = true;
                CancelBTN.Visible        = false;
                DoneBTN.Visible          = true;
                OptionsBTN.Visible       = true;
                SubscriptionCTRL.Visible = false;
                BrowseCTRL.Visible       = true;
                ItemsCTRL.Visible        = true;
                ResultsCTRL.Visible      = false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Example #5
0
 /// <summary>
 /// Creates a new instance of a subscription.
 /// </summary>
 protected virtual Technosoftware.DaAeHdaClient.Com.Da.Subscription CreateSubscription(
     object group,
     TsCDaSubscriptionState state,
     int filters)
 {
     return(new Technosoftware.DaAeHdaClient.Com.Da.Subscription(group, state, filters));
 }
Example #6
0
        /// <summary>
        /// Copy object values into controls.
        /// </summary>
        public void Set(object value)
        {
            // check for null value.
            if (value == null)
            {
                SetDefaults(); return;
            }

            TsCDaSubscriptionState state = (TsCDaSubscriptionState)value;

            // save subscription handles.
            mClientHandle_ = state.ClientHandle;
            mServerHandle_ = state.ClientHandle;

            nameTb_.Text                  = state.Name;
            activeCb_.Checked             = state.Active;
            updateRateCtrl_.Value         = (decimal)state.UpdateRate;
            keepAliveRateCtrl_.Value      = (decimal)state.KeepAlive;
            keepAliveSpecifiedCb_.Checked = state.KeepAlive != 0;
            deadbandCtrl_.Value           = (decimal)state.Deadband;
            deadbandSpecifiedCb_.Checked  = state.Deadband != 0;
            localeCtrl_.Locale            = state.Locale;
            localeSpecifiedCb_.Checked    = state.Locale != null;

            if (mServer_ != null)
            {
                localeCtrl_.SetSupportedLocales(mServer_.SupportedLocales);
            }
        }
Example #7
0
        /// <summary>
        /// Releases unmanaged resources held by the object.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (!m_disposed)
            {
                lock (this)
                {
                    if (disposing)
                    {
                        // Release managed resources.
                        if (m_server != null)
                        {
                            // release all groups.
                            foreach (Subscription subscription in subscriptions_.Values)
                            {
                                string methodName = "IOPCServer.RemoveGroup";

                                // remove subscription from server.
                                try
                                {
                                    TsCDaSubscriptionState state = subscription.GetState();
                                    if (state != null)
                                    {
                                        IOPCServer server = BeginComCall <IOPCServer>(methodName, true);
                                        server?.RemoveGroup((int)state.ServerHandle, 0);
                                    }
                                }
                                catch (Exception e)
                                {
                                    ComCallError(methodName, e);
                                }
                                finally
                                {
                                    EndComCall(methodName);
                                }
                                // dispose of the subscription object (disconnects all subscription connections).
                                subscription.Dispose();
                            }

                            // clear subscription table.
                            subscriptions_.Clear();
                        }
                    }

                    // Release unmanaged resources.
                    // Set large fields to null.

                    if (m_server != null)
                    {
                        // release the COM server.
                        Technosoftware.DaAeHdaClient.Com.Interop.ReleaseServer(m_server);
                        m_server = null;
                    }
                }

                // Call Dispose on your base class.
                m_disposed = true;
            }

            base.Dispose(disposing);
        }
Example #8
0
        /// <summary>
        /// Copy object values into controls.
        /// </summary>
        public void Set(object value)
        {
            // check for null value.
            if (value == null)
            {
                SetDefaults(); return;
            }

            TsCDaSubscriptionState state = (TsCDaSubscriptionState)value;

            // save subscription handles.
            m_clientHandle = state.ClientHandle;
            m_serverHandle = state.ClientHandle;

            NameTB.Text                  = state.Name;
            ActiveCB.Checked             = state.Active;
            UpdateRateCTRL.Value         = (decimal)state.UpdateRate;
            KeepAliveRateCTRL.Value      = (decimal)state.KeepAlive;
            KeepAliveSpecifiedCB.Checked = state.KeepAlive != 0;
            DeadbandCTRL.Value           = (decimal)state.Deadband;
            DeadbandSpecifiedCB.Checked  = state.Deadband != 0;
            LocaleCTRL.Locale            = state.Locale;
            LocaleSpecifiedCB.Checked    = state.Locale != null;

            if (m_server != null)
            {
                LocaleCTRL.SetSupportedLocales(m_server.SupportedLocales);
            }
        }
        /// <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;
            }
        }
        /// <summary>
        /// Cancels a subscription and releases all resources allocated for it.
        /// </summary>
        /// <param name="subscription">The subscription to cancel.</param>
        public void CancelSubscription(ITsCDaSubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException(nameof(subscription));
            }

            lock (this)
            {
                if (server_ == null)
                {
                    throw new NotConnectedException();
                }
                string methodName = "IOPCServer.RemoveGroup";

                // validate argument.
                if (!typeof(Subscription).IsInstanceOfType(subscription))
                {
                    throw new ArgumentException("Incorrect object type.", nameof(subscription));
                }

                // get the subscription state.
                TsCDaSubscriptionState state = subscription.GetState();

                if (!subscriptions_.ContainsKey(state.ServerHandle))
                {
                    throw new ArgumentException("Handle not found.", nameof(subscription));
                }

                subscriptions_.Remove(state.ServerHandle);

                // release all subscription resources.
                subscription.Dispose();

                // invoke COM method.
                try
                {
                    IOPCServer server = BeginComCall <IOPCServer>(methodName, true);
                    server.RemoveGroup((int)state.ServerHandle, 0);

                    if (DCOMCallWatchdog.IsCancelled)
                    {
                        throw new Exception($"{methodName} call was cancelled due to response timeout");
                    }
                }
                catch (Exception e)
                {
                    ComCallError(methodName, e);
                    throw Utilities.Interop.CreateException(methodName, e);
                }
                finally
                {
                    EndComCall(methodName);
                }
            }
        }
Example #11
0
        /// <summary>
        /// Copy values from control into object - throw exceptions on error.
        /// </summary>
        public object Get()
        {
            TsCDaSubscriptionState state = new TsCDaSubscriptionState();

            state.ClientHandle = m_clientHandle;
            state.ServerHandle = m_serverHandle;
            state.Name         = NameTB.Text;
            state.Active       = ActiveCB.Checked;
            state.UpdateRate   = (int)UpdateRateCTRL.Value;
            state.KeepAlive    = (int)KeepAliveRateCTRL.Value;
            state.Deadband     = (float)DeadbandCTRL.Value;
            state.Locale       = (LocaleSpecifiedCB.Checked)?LocaleCTRL.Locale:null;

            return(state);
        }
Example #12
0
        /// <summary>
        /// Copy values from control into object - throw exceptions on error.
        /// </summary>
        public object Get()
        {
            TsCDaSubscriptionState state = new TsCDaSubscriptionState();

            state.ClientHandle = mClientHandle_;
            state.ServerHandle = mServerHandle_;
            state.Name         = nameTb_.Text;
            state.Active       = activeCb_.Checked;
            state.UpdateRate   = (int)updateRateCtrl_.Value;
            state.KeepAlive    = (int)keepAliveRateCtrl_.Value;
            state.Deadband     = (float)deadbandCtrl_.Value;
            state.Locale       = (localeSpecifiedCb_.Checked)?localeCtrl_.Locale:null;

            return(state);
        }
        //----------------------------------------------------------------------------------------------------------------------
        // btnAddItem_Click
        //--------------------
        // This method tries to add the specified item to the preceding added group object.
        //----------------------------------------------------------------------------------------------------------------------
        private void btnAddItem_Click(object sender, System.EventArgs e)
        {
            try
            {
                TsCDaSubscriptionState groupState = new TsCDaSubscriptionState();
                groupState.Name = "MyGroup";                                          // Group Name
                m_pOpcGroup     = (TsCDaSubscription)m_OpcDaServer.CreateSubscription(groupState);

                TsCDaItemResult[] res;
                TsCDaItem[]       items = new TsCDaItem[1];
                items[0]              = new TsCDaItem();
                items[0].ItemName     = txtboxOpcItem.Text;                       // Item Name
                items[0].ClientHandle = 100;                                      // Client Handle

                res = m_pOpcGroup.AddItems(items);

                if (res[0].Result.IsSuccess())
                {
                    if (!(res[0].Result.IsOk()))                                                        // Note: Since this sample adds only one item it's required that AddItems()
                    {
                        return;                                                                         // succeeds for all specified items (in this case only one).
                    }
                    else
                    {
                        m_arAddedItems = res;
                    }
                }
                else
                {
                    MessageBox.Show("AddItems() method failed: " + res[0].Result.Description(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }


                /// All succeeded, update buttons and text fields
                txtboxOpcItem.Enabled = false;
                btnAddItem.Enabled    = false;
                btnRead.Enabled       = true;
                btnWrite.Enabled      = true;
                txtboxWrite.Enabled   = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        /// <summary>
        /// Prompts the user to modify the subscription state parameters.
        /// </summary>
        public TsCDaSubscriptionState ShowDialog(TsCDaServer server, TsCDaSubscriptionState state)
        {
            ObjectCTRL.Server = server;

            if (state == null)
            {
                state = (TsCDaSubscriptionState)ObjectCTRL.Create();
            }

            ArrayList results = ShowDialog(new object[] { state });

            if (results != null && results.Count == 1)
            {
                return((TsCDaSubscriptionState)results[0]);
            }

            return(null);
        }
        /// <summary>
        /// Toggles the active state of a subscription.
        /// </summary>
        private void SetActive(TsCDaSubscription subscription, bool active)
        {
            try
            {
                TsCDaSubscriptionState state = new TsCDaSubscriptionState();
                state.Active = active;
                subscription.ModifyState((int)TsCDaStateMask.Active, state);

                if (SubscriptionModified != null)
                {
                    SubscriptionModified(subscription, !state.Active);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
Example #16
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);
            }
        }
Example #17
0
        //----------------------------------------------------------------------------------------------------------------------
        // btnAddItem_Click
        //--------------------
        // This method tries to add the specified item to the preceding added group object.
        //----------------------------------------------------------------------------------------------------------------------
        private void btnAddItem_Click(object sender, System.EventArgs e)
        {
            try
            {
                TsCDaSubscriptionState groupState = new TsCDaSubscriptionState();
                groupState.Name         = "MyGroup";                  // Group Name
                groupState.ClientHandle = "test";
                groupState.Deadband     = 0;
                groupState.UpdateRate   = 1000;
                groupState.KeepAlive    = 10000;
                m_pOpcGroup             = (TsCDaSubscription)m_OpcDaServer.CreateSubscription(groupState);

                TsCDaItemResult[] itemResults;
                TsCDaItem[]       items = new TsCDaItem[1];
                items[0]              = new TsCDaItem();
                items[0].ItemName     = txtboxOpcItem.Text;       // Item Name
                items[0].ClientHandle = 100;                      // Client Handle

                itemResults    = m_pOpcGroup.AddItems(items);
                m_arAddedItems = itemResults;

                /// Activate data change subscription
                m_pOpcGroup.DataChangedEvent += new TsCDaDataChangedEventHandler(DataChangeHandler);

                /// All succeeded, update buttons and text fields
                txtboxOpcItem.Enabled      = false;
                btnAddItem.Enabled         = false;
                btnRead.Enabled            = true;
                btnRefresh.Enabled         = true;
                btnCancel.Enabled          = true;
                btnWrite.Enabled           = true;
                txtboxWrite.Enabled        = true;
                chboxNotifications.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
		void OnCreateSubscription()
		{
			// Создаём объект подписки
			var subscriptionState = new TsCDaSubscriptionState
			{
				Name = "MySubscription",
				ClientHandle = "MySubscriptionId",
				Deadband = 0,
				UpdateRate = 1000,
				KeepAlive = 10000
			};
			_activeSubscription = (TsCDaSubscription)_activeOpcServer.CreateSubscription(subscriptionState);

			// Добавляем в объект подписки выбранные теги
			var x = 0;
			List<TsCDaItem> list = new List<TsCDaItem>();
			foreach (var item in CheckedTags)
			{
				var tag = new TsCDaItem
				{
					ItemName = item.Element.ItemName,
					ClientHandle = 100 + x // Уникальный Id определяемый пользователем
				};
				list.Add(tag);
				++x;
			}

			// Добавляем теги и проверяем результат данной операции
			var results = _activeSubscription.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());
			}

			_activeSubscription.DataChangedEvent += _dataChangeEventHandler;
		}
Example #19
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 #20
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();
            }
        }
Example #21
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;
            }
        }
Example #22
0
        /// <summary>
        /// Returns the current state of the subscription.
        /// </summary>
        /// <returns>The current state of the subscription.</returns>
        public override TsCDaSubscriptionState GetState()
        {
            if (subscription_ == null)
            {
                throw new NotConnectedException();
            }
            lock (lock_)
            {
                string methodName            = "IOPCGroupStateMgt.GetState";
                TsCDaSubscriptionState state = new TsCDaSubscriptionState {
                    ClientHandle = _handle
                };

                string name = null;

                try
                {
                    int   active       = 0;
                    int   updateRate   = 0;
                    float deadband     = 0;
                    int   timebias     = 0;
                    int   localeID     = 0;
                    int   clientHandle = 0;
                    int   serverHandle = 0;

                    IOPCGroupStateMgt subscription = BeginComCall <IOPCGroupStateMgt>(methodName, true);
                    subscription.GetState(
                        out updateRate,
                        out active,
                        out name,
                        out timebias,
                        out deadband,
                        out localeID,
                        out clientHandle,
                        out serverHandle);

                    if (DCOMCallWatchdog.IsCancelled)
                    {
                        throw new Exception($"{methodName} call was cancelled due to response timeout");
                    }

                    state.Name         = name;
                    state.ServerHandle = serverHandle;
                    state.Active       = active != 0;
                    state.UpdateRate   = updateRate;
                    state.TimeBias     = timebias;
                    state.Deadband     = deadband;
                    state.Locale       = Technosoftware.DaAeHdaClient.Com.Interop.GetLocale(localeID);

                    // cache the name separately.
                    name_ = state.Name;
                }
                catch (Exception e)
                {
                    ComCallError(methodName, e);
                    throw Technosoftware.DaAeHdaClient.Com.Interop.CreateException(methodName, e);
                }
                finally
                {
                    EndComCall(methodName);
                }

                state.KeepAlive = 0;

                return(state);
            }
        }
Example #23
0
        //======================================================================
        // Construction

        /// <summary>
        /// Initializes a new instance of a subscription.
        /// </summary>
        internal Subscription(object subscription, TsCDaSubscriptionState state, int filters)
            :
            base(subscription, state, filters)
        {
        }
        ///////////////////////////////////////////////////////////////////////
        #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 #25
0
        //======================================================================
        // State Management

        /// <summary>
        /// Returns the current state of the subscription.
        /// </summary>
        /// <returns>The current state of the subscription.</returns>
        public TsCDaSubscriptionState GetState()
        {
            lock (this)
            {
                TsCDaSubscriptionState state = new TsCDaSubscriptionState();

                state.ClientHandle = _handle;

                string methodName = "IOPCGroupStateMgt.GetState";
                try
                {
                    string name         = null;
                    int    active       = 0;
                    int    updateRate   = 0;
                    float  deadband     = 0;
                    int    timebias     = 0;
                    int    localeID     = 0;
                    int    clientHandle = 0;
                    int    serverHandle = 0;

                    IOPCGroupStateMgt subscription = BeginComCall <IOPCGroupStateMgt>(methodName, true);
                    subscription.GetState(
                        out updateRate,
                        out active,
                        out name,
                        out timebias,
                        out deadband,
                        out localeID,
                        out clientHandle,
                        out serverHandle);

                    state.Name         = name;
                    state.ServerHandle = serverHandle;
                    if (active == 1)
                    {
                        state.Active = true;
                    }
                    else
                    {
                        state.Active = false;
                    }
                    state.UpdateRate = updateRate;
                    state.TimeBias   = timebias;
                    state.Deadband   = deadband;
                    state.Locale     = Utilities.Interop.GetLocale(localeID);

                    // cache the name separately.
                    name_ = state.Name;

                    state.KeepAlive = 0;
                }
                catch (Exception e)
                {
                    ComCallError(methodName, e);
                    throw Utilities.Interop.CreateException(methodName, e);
                }
                finally
                {
                    EndComCall(methodName);
                }

                return(state);
            }
        }
Example #26
0
        /// <summary>
        /// Creates a new subscription.
        /// </summary>
        /// <param name="state">The initial state of the subscription.</param>
        /// <returns>The new subscription object.</returns>
        public ITsCDaSubscription CreateSubscription(TsCDaSubscriptionState state)
        {
            if (state == null)
            {
                throw new ArgumentNullException(nameof(state));
            }

            lock (this)
            {
                if (m_server == null)
                {
                    throw new NotConnectedException();
                }
                string methodName = "IOPCServer.AddGroup";

                // copy the subscription state.
                TsCDaSubscriptionState result = (TsCDaSubscriptionState)state.Clone();

                // initialize arguments.
                Guid   iid   = typeof(IOPCItemMgt).GUID;
                object group = null;

                int serverHandle      = 0;
                int revisedUpdateRate = 0;

                GCHandle hDeadband = GCHandle.Alloc(result.Deadband, GCHandleType.Pinned);

                // invoke COM method.
                try
                {
                    IOPCServer server = BeginComCall <IOPCServer>(methodName, true);
                    server.AddGroup(
                        (result.Name != null) ? result.Name : "",
                        (result.Active) ? 1 : 0,
                        result.UpdateRate,
                        0,
                        IntPtr.Zero,
                        hDeadband.AddrOfPinnedObject(),
                        Technosoftware.DaAeHdaClient.Com.Interop.GetLocale(result.Locale),
                        out serverHandle,
                        out revisedUpdateRate,
                        ref iid,
                        out group);
                }
                catch (Exception e)
                {
                    ComCallError(methodName, e);
                    throw Technosoftware.DaAeHdaClient.Utilities.Interop.CreateException(methodName, e);
                }
                finally
                {
                    if (hDeadband.IsAllocated)
                    {
                        hDeadband.Free();
                    }
                    EndComCall(methodName);
                }

                if (group == null)
                {
                    throw new OpcResultException(OpcResult.E_FAIL, "The subscription  was not created.");
                }

                methodName = "IOPCGroupStateMgt2.SetKeepAlive";

                // set the keep alive rate if requested.
                try
                {
                    int keepAlive = 0;
                    IOPCGroupStateMgt2 comObject = BeginComCall <IOPCGroupStateMgt2>(group, methodName, true);
                    comObject.SetKeepAlive(result.KeepAlive, out keepAlive);
                    result.KeepAlive = keepAlive;
                }
                catch (Exception e1)
                {
                    result.KeepAlive = 0;
                    ComCallError(methodName, e1);
                }
                finally
                {
                    EndComCall(methodName);
                }

                // save server handle.
                result.ServerHandle = serverHandle;

                // set the revised update rate.
                if (revisedUpdateRate > result.UpdateRate)
                {
                    result.UpdateRate = revisedUpdateRate;
                }

                // create the subscription object.
                Technosoftware.DaAeHdaClient.Com.Da.Subscription subscription = CreateSubscription(group, result, filters_);

                // index by server handle.
                subscriptions_[serverHandle] = subscription;

                // return subscription.
                return(subscription);
            }
        }