/// <summary>
        /// Creates a DomainParticipant, Topic, Publisher and DataWriter<HelloWorld>.
        /// </summary>
        public HelloWorldPublisher(int domainId)
        {
            // Enable network capture.
            // This must be called before any other network capture function, and
            // before creating any participant for which we want to capture traffic.
            NetworkCapture.Enable();

            // Start communicating in a domain, usually one participant per application
            // Load QoS profile from USER_QOS_PROFILES.xml file
            participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic = participant.CreateTopic <HelloWorld>(
                "Network capture shared memory example");

            // Create a Publisher
            Publisher publisher = participant.CreatePublisher();

            // Create a DataWriter, loading QoS profile from USER_QOS_PROFILES.xml, and
            writer = publisher.CreateDataWriter(topic);
        }
예제 #2
0
        private void InitializeDDS()
        {
            //string id = usuario.Id;
            string id = "0";

            int.TryParse(id, out domainId);


            // Create the DomainFactory
            factory = DomainParticipantFactory.GetInstance(Bootstrap.CreateInstance());
            // Create the DomainParticipant with reference to the configuration file with the domain ID
            dp = factory.CreateParticipant(domainId);
            // Console.WriteLine("Domain ID = {0} has been created", domainId);
            // Implicitly create TypeSupport and register type:
            tp = dp.CreateTopic <ChatMessage>("Greetings Topic");
            // Create the subscriber
            sub = dp.CreateSubscriber();
            // Create a Listener for the publishing data
            ls = new MyListener(backgroundWorker1, backgroundWorker2, backgroundWorker3, backgroundWorker4, backgroundWorker5,
                                backgroundWorker6);
            ls2 = new MyListener2();
            // Create the DataReader using the topic, politics of QoS for DataReader and implemented listener
            dr = sub.CreateDataReader <ChatMessage>(tp,
                                                    sub.GetDefaultDataReaderQos(),
                                                    ls,
                                                    null);



            // Create the publisher
            pub = dp.CreatePublisher();
            // Create the DataWriter using the topic specified
            //dw = pub.CreateDataWriter(tp);

            dw = pub.CreateDataWriter <ChatMessage>(tp,
                                                    pub.GetDefaultDataWriterQos(),
                                                    ls2,
                                                    null);
        }
        /// <summary>
        /// Creates a DomainParticipant, Topic, Subscriber and DataReader<HelloWorld>.
        /// </summary>
        public HelloWorldSubscriber(int domainId, string password, string topicName)
        {
            // Configure the DomainParticipantQos add the UserData policy to it.
            // We're simply converting the input string into bytes, assuming
            // that only ASCII characters are used to keep the example simple.
            // We also set the maximum user data length.
            DomainParticipantQos participantQos =
                DomainParticipantFactory.Instance.DefaultParticipantQos
                .WithUserData(new UserData(password.Select(c => (byte)c)))
                .WithResourceLimits(policy => policy.ParticipantUserDataMaxLength = 1024);

            // Create the participant with the QoS
            participant = DomainParticipantFactory.Instance
                          .CreateParticipant(domainId, participantQos);

            Topic <HelloWorld> topic = participant.CreateTopic <HelloWorld>(topicName);

            // Create a subscriber and a DataReader
            Subscriber subscriber = participant.CreateSubscriber();

            reader = subscriber.CreateDataReader(topic);
        }
        public void TestTakeNextSample()
        {
            TopicBuiltinTopicData data  = default;
            SampleInfo            infos = new SampleInfo();
            ReturnCode            ret   = _dr.TakeNextSample(ref data, infos);

            Assert.AreEqual(ReturnCode.NoData, ret);

            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.INFOREPO_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindTcpTransportConfig();

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            TopicQos qos   = TestHelper.CreateNonDefaultTopicQos();
            var      topic = otherParticipant.CreateTopic(TestContext.TestName, typeName, qos);

            Assert.IsNotNull(topic);

            Thread.Sleep(500);

            ret = _dr.TakeNextSample(ref data, infos);
            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(typeName, data.TypeName);
            Assert.IsNotNull(data.Key);
            TestHelper.TestNonDefaultTopicData(data);

            ret = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, ret);

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
        /// <summary>
        /// Runs the publisher example.
        /// </summary>
        public static void RunPublisher(int domainId, int sampleCount)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            //
            // A participant needs to be Disposed to release middleware resources.
            // The 'using' keyword indicates that it will be Disposed when this
            // scope ends.
            using DomainParticipant participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic = participant.CreateTopic <HelloWorld>("Example PartitionsExample_HelloWorld");

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter will write data on Topic "Example HelloWorld"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <HelloWorld> writer = publisher.CreateDataWriter(topic);

            var sample = new HelloWorld();

            for (int count = 0; count < sampleCount; count++)
            {
                // Modify the data to be sent here
                sample.x = count;

                Console.WriteLine($"Writing HelloWorld, count {count}");

                writer.Write(sample);

                // Every 5 samples we will change the partition name.
                // These are the partition expressions we are going to try:
                // "bar", "A*", "A?C", "X*Z", "zzz" and "A*C".
                string[] newPartitions = null;
                if ((count + 1) % 25 == 0)
                {
                    // Matches "ABC", name[1] here can match name[0] there,
                    // as long as there is some overlapping name.
                    newPartitions = new string[] { "zzz", "A*C" };
                }
                else if ((count + 1) % 25 == 20)
                {
                    // Strings that are regular expressions aren't tested for
                    // literal matches, so this won't match "X*Z".
                    newPartitions = new string[] { "X*Z" };
                }
                else if ((count + 1) % 25 == 15)
                {
                    // Matches "ABC".
                    newPartitions = new string[] { "A?C" };
                }
                else if ((count + 1) % 25 == 10)
                {
                    // Matches "ABC".
                    newPartitions = new string[] { "A*" };
                }
                else if ((count + 1) % 25 == 5)
                {
                    // No literal match for "bar".
                    // For the next iterations we are using only one partition.
                    newPartitions = new string[] { "bar" };
                }

                if (newPartitions != null)
                {
                    // Update the publisher QoS with the new partitions
                    publisher.Qos = publisher.Qos.WithPartition(currentPartition =>
                    {
                        currentPartition.Clear();                 // remove previous partitions
                        currentPartition.AddRange(newPartitions); // add new partitions
                    });

                    Console.WriteLine(
                        "Publisher partition set to: "
                        + string.Join(separator: ",", values: publisher.Qos.Partition.Name));
                }

                Thread.Sleep(1000);
            }
        }
        /// <summary>
        /// Creates a DomainParticipant, Topic, Subscriber and DataReader<Temperature>.
        /// </summary>
        public SubscriberApplication(int domainId, bool useXmlQos = true)
        {
            // Start communicating in a domain, usually one participant per application
            // Load QoS profile from USER_QOS_PROFILES.xml file
            participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // Create the topics
            var alarmTopic       = participant.CreateTopic <Alarm>("Alarm");
            var heartRateTopic   = participant.CreateTopic <HeartRate>("HeartRate");
            var temperatureTopic = participant.CreateTopic <Temperature>("Temperature");

            // Create a subscriber
            SubscriberQos subscriberQos = null;

            if (useXmlQos)
            {
                // Retrieve the Subscriber QoS, from USER_QOS_PROFILES.xml
                subscriberQos = QosProvider.Default.GetSubscriberQos();
            }
            else
            {
                // Set the Subscriber QoS programatically, to the same effect
                subscriberQos = participant.DefaultSubscriberQos
                                .WithPresentation(policy =>
                {
                    policy.AccessScope    = PresentationAccessScopeKind.Group;
                    policy.CoherentAccess = true;
                    policy.OrderedAccess  = true;

                    // Uncomment this line to keep and deliver incomplete
                    // coherent sets to the application
                    // policy.DropIncompleteCoherentSet = false;
                });
            }
            subscriber = participant.CreateSubscriber(subscriberQos);

            // Create a DataReader for each topic
            DataReaderQos readerQos = null;

            if (useXmlQos)
            {
                // Retrieve the DataReader QoS, from USER_QOS_PROFILES.xml
                readerQos = QosProvider.Default.GetDataReaderQos();
            }
            else
            {
                // Set the DataReader QoS programatically, to the same effect
                readerQos = subscriber.DefaultDataReaderQos
                            .WithReliability(policy => policy.Kind = ReliabilityKind.Reliable)
                            .WithHistory(policy => policy.Kind     = HistoryKind.KeepAll);
            }

            alarmReader       = subscriber.CreateDataReader(alarmTopic, readerQos);
            heartRateReader   = subscriber.CreateDataReader(heartRateTopic, readerQos);
            temperatureReader = subscriber.CreateDataReader(temperatureTopic, readerQos);

            // We are monitoring the sample lost status in case an
            // incomplete coherent set is received and dropped (assuming the
            // Presentation.DropIncompleteCoherentSet is true (the default))
            alarmReader.SampleLost       += OnSampleLost;
            heartRateReader.SampleLost   += OnSampleLost;
            temperatureReader.SampleLost += OnSampleLost;
        }
예제 #7
0
        public void TestGetDefaultDataReaderQos()
        {
            // Initialize entities
            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(_participant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            Topic topic = _participant.CreateTopic(nameof(TestGetDefaultDataReaderQos), typeName);

            Assert.IsNotNull(topic);
            Assert.IsNull(topic.GetListener());
            Assert.AreEqual(nameof(TestGetDefaultDataReaderQos), topic.Name);
            Assert.AreEqual(typeName, topic.TypeName);

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            // Create a non-default DataReader Qos, call GetDefaultDataReaderQos and check the default values
            DataReaderQos qos = TestHelper.CreateNonDefaultDataReaderQos();

            result = subscriber.GetDefaultDataReaderQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataReaderQos(qos);

            // Test GetDefaultDataReaderQos with null parametr
            result = subscriber.GetDefaultDataReaderQos(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);
        }
예제 #8
0
        public void TestTakeInstance()
        {
            ReturnCode        ret;
            DomainParticipant otherParticipant = null;
            Topic             topic            = null;

            try
            {
                List <TopicBuiltinTopicData> data  = new List <TopicBuiltinTopicData>();
                List <SampleInfo>            infos = new List <SampleInfo>();
                ret = _dr.Read(data, infos);
                Assert.AreEqual(ReturnCode.NoData, ret);
                Assert.AreEqual(0, data.Count);
                Assert.AreEqual(0, infos.Count);

                otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.INFOREPO_DOMAIN);
                Assert.IsNotNull(otherParticipant);
                otherParticipant.BindRtpsUdpTransportConfig();

                TestStructTypeSupport support = new TestStructTypeSupport();
                string     typeName           = support.GetTypeName();
                ReturnCode result             = support.RegisterType(otherParticipant, typeName);
                Assert.AreEqual(ReturnCode.Ok, result);

                TopicQos qos = TestHelper.CreateNonDefaultTopicQos();
                topic = otherParticipant.CreateTopic(TestContext.TestName, typeName, qos);
                Assert.IsNotNull(topic);

                int count = 200;
                ret = ReturnCode.NoData;
                while (ret != ReturnCode.Ok && count > 0)
                {
                    Thread.Sleep(100);
                    ret = _dr.ReadNextInstance(data, infos, InstanceHandle.HandleNil);
                    count--;
                }

                Assert.AreEqual(ReturnCode.Ok, ret);
                Assert.AreEqual(1, data.Count);
                Assert.AreEqual(1, infos.Count);
                Assert.AreEqual(typeName, data.First().TypeName);
                Assert.IsNotNull(data.First().Key);
                TestHelper.TestNonDefaultTopicData(data.First());

                var handle = infos.First().InstanceHandle;
                data  = new List <TopicBuiltinTopicData>();
                infos = new List <SampleInfo>();

                ret = _dr.TakeInstance(data, infos, handle);
                Assert.AreEqual(ReturnCode.Ok, ret);
                Assert.AreEqual(1, data.Count);
                Assert.AreEqual(1, infos.Count);
                Assert.AreEqual(typeName, data.First().TypeName);
                Assert.IsNotNull(data.First().Key);
                TestHelper.TestNonDefaultTopicData(data.First());
            }
            finally
            {
                ret = otherParticipant.DeleteTopic(topic);
                Assert.AreEqual(ReturnCode.Ok, ret);
                ret = otherParticipant.DeleteContainedEntities();
                Assert.AreEqual(ReturnCode.Ok, ret);

                ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
                Assert.AreEqual(ReturnCode.Ok, ret);
            }
        }
        /// <summary>
        /// Runs the publisher example.
        /// </summary>
        public static void RunPublisher(
            int domainId,
            int sampleCount,
            CancellationToken cancellationToken,
            bool useXmlQos = false)
        {
            // Start communicating in a domain, usually one participant per application
            // Load default QoS profile from USER_QOS_PROFILES.xml file
            using DomainParticipant participant =
                      DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic =
                participant.CreateTopic <HelloWorld>("Example async");

            // Create a Publisher
            Publisher publisher = participant.CreatePublisher();

            DataWriterQos writerQos;

            if (useXmlQos)
            {
                // Retrieve the DataWriterQos from the default profile in
                // USER_QOS_PROFILES.xml
                writerQos = QosProvider.Default.GetDataWriterQos();
            }
            else
            {
                // Configure the DataWriterQos in code, to the same effect as
                // the XML file.
                writerQos = publisher.DefaultDataWriterQos
                            .WithReliability(policy =>
                {
                    policy.Kind            = ReliabilityKind.Reliable;
                    policy.MaxBlockingTime = Duration.FromSeconds(60);
                })
                            .WithHistory(policy =>
                {
                    policy.Kind  = HistoryKind.KeepLast;
                    policy.Depth = 12;
                })
                            .WithProtocol(policy =>
                {
                    policy.RtpsReliableWriter.MinSendWindowSize = 50;
                    policy.RtpsReliableWriter.MaxSendWindowSize = 50;
                })
                            .WithPublishMode(policy =>
                {
                    policy.Kind = PublishModeKind.Asynchronous;

                    // The built-in fixed-rate flow controller publishes
                    // all written samples once per second
                    policy.FlowControllerName = PublishMode.FixedRateFlowControllerName;
                });
            }

            DataWriter <HelloWorld> writer =
                publisher.CreateDataWriter(topic, writerQos);

            var sample = new HelloWorld();

            for (int count = 0;
                 count < sampleCount && !cancellationToken.IsCancellationRequested;
                 count++)
            {
                // Modify the data to be sent here
                sample.x = count;

                Console.WriteLine($"Writing x={sample.x}");

                // With asynchronous publish mode, the Write() puts the sample
                // in the queue but doesn't send it until the flow controller
                // indicates so.
                writer.Write(sample);

                Thread.Sleep(100);
            }

            // You can wait until all written samples have been actually published
            // (note that this doesn't ensure that they have actually been received
            // if the sample required retransmission)
            writer.WaitForAsynchronousPublishing(Duration.FromSeconds(10));
        }
예제 #10
0
        static void Main(string[] args)
        {
            bool useListener = true;

            OpenDDSharp.Ace.Init();

            ParticipantService       participantService = ParticipantService.Instance;
            DomainParticipantFactory domainFactory      = participantService.GetDomainParticipantFactory(args);
            DomainParticipantQos     qos = new DomainParticipantQos();

            qos.EntityFactory.AutoenableCreatedEntities = false;
            qos.UserData.Value = Encoding.UTF8.GetBytes("sometext");
            DomainParticipant participant = domainFactory.CreateParticipant(42, qos);

            if (participant == null)
            {
                throw new Exception("Could not create the participant");
            }

            DomainParticipantQos aux = new DomainParticipantQos();
            ReturnCode           ret = participant.GetQos(aux);

            aux.EntityFactory.AutoenableCreatedEntities = true;
            ret = participant.SetQos(aux);

            if (participant != null)
            {
                TestStructTypeSupport support = new TestStructTypeSupport();
                string     typeName           = support.GetTypeName();
                ReturnCode result             = support.RegisterType(participant, typeName);
                if (result != ReturnCode.Ok)
                {
                    throw new Exception("Could not register the type");
                }

                Topic     topic     = participant.CreateTopic("TopicName", typeName);
                Publisher publisher = participant.CreatePublisher();
                if (publisher == null)
                {
                    throw new Exception("Could not create the publisher");
                }

                DataWriter dw = publisher.CreateDataWriter(topic);
                if (dw == null)
                {
                    throw new Exception("Could not create the datawriter");
                }
                TestStructDataWriter dataWriter = new TestStructDataWriter(dw);
                Subscriber           subscriber = participant.CreateSubscriber();
                if (subscriber == null)
                {
                    throw new Exception("Could not create the subscribre");
                }

                MyDataListener listener = null;
                if (useListener)
                {
                    listener = new MyDataListener();
                }
                DataReader dataReader = subscriber.CreateDataReader(topic, listener, StatusKind.DataAvailableStatus);
                if (dataReader == null)
                {
                    throw new Exception("Could not create the datareader");
                }

                WaitSet         waitSet         = null;
                StatusCondition statusCondition = null;
                if (!useListener)
                {
                    waitSet         = new WaitSet();
                    statusCondition = dataReader.StatusCondition;
                    waitSet.AttachCondition(statusCondition);
                    statusCondition.EnabledStatuses = StatusKind.DataAvailableStatus;

                    new System.Threading.Thread(delegate()
                    {
                        ICollection <Condition> conditions = new List <Condition>();
                        Duration duration = new Duration
                        {
                            Seconds = Duration.InfiniteSeconds
                        };
                        waitSet.Wait(conditions, duration);

                        foreach (Condition cond in conditions)
                        {
                            if (cond == statusCondition && cond.TriggerValue)
                            {
                                StatusCondition sCond = (StatusCondition)cond;
                                StatusMask mask       = sCond.EnabledStatuses;
                                if ((mask & StatusKind.DataAvailableStatus) != 0)
                                {
                                    DataAvailable(dataReader);
                                }
                            }
                        }
                    }).Start();
                }

                TestStruct test = new TestStruct
                {
                    RawData = "Hello, I love you, won't you tell me your name?"
                };

                test.LongSequence.Add(20);
                test.LongSequence.Add(10);
                test.LongSequence.Add(0);

                test.StringSequence.Add("Hello,");
                test.StringSequence.Add("I love you");
                test.StringSequence.Add("won't you tell me your name?");

                test.LongDoubleType = 1.1;

                test.LongDoubleSequence.Add(1.1);
                test.LongDoubleSequence.Add(2.2);
                test.LongDoubleSequence.Add(3.3);

                test.LongArray[0, 0] = 1;
                test.LongArray[0, 1] = 2;
                test.LongArray[0, 2] = 3;
                test.LongArray[0, 3] = 4;
                test.LongArray[1, 0] = 1;
                test.LongArray[1, 1] = 2;
                test.LongArray[1, 2] = 3;
                test.LongArray[1, 3] = 4;
                test.LongArray[2, 0] = 1;
                test.LongArray[2, 1] = 2;
                test.LongArray[2, 2] = 3;
                test.LongArray[2, 3] = 4;

                test.StringArray[0, 0] = "Hello,";
                test.StringArray[0, 1] = "I love you,";
                test.StringArray[1, 0] = "won't you tell me";
                test.StringArray[1, 1] = "your name?";

                test.StructArray[0, 0] = new BasicTestStruct()
                {
                    Id = 0
                };
                test.StructArray[0, 1] = new BasicTestStruct()
                {
                    Id = 1
                };
                test.StructArray[1, 0] = new BasicTestStruct()
                {
                    Id = 2
                };
                test.StructArray[1, 1] = new BasicTestStruct()
                {
                    Id = 3
                };

                test.LongDoubleArray[0, 0] = 1.1;
                test.LongDoubleArray[0, 1] = 2.2;
                test.LongDoubleArray[1, 0] = 3.3;
                test.LongDoubleArray[1, 1] = 4.4;

                test.StructSequence.Add(new BasicTestStruct()
                {
                    Id = 1
                });

                test.StructSequence.Add(new BasicTestStruct()
                {
                    Id = 2
                });

                test.StructSequence.Add(new BasicTestStruct()
                {
                    Id = 3
                });

                result = dataWriter.Write(test);

                System.Threading.Thread.Sleep(1000);

                if (!useListener)
                {
                    waitSet.DetachCondition(statusCondition);
                }

                participant.DeleteContainedEntities();
                domainFactory.DeleteParticipant(participant);
            }

            participantService.Shutdown();
            OpenDDSharp.Ace.Fini();

            Console.WriteLine("Press ENTER to finish the test.");
            Console.ReadLine();
        }
예제 #11
0
        /// <summary>
        /// Runs the subscriber example.
        /// </summary>
        public static async Task RunSubscriber(int domainId = 0, int sampleCount = int.MaxValue, bool useXmlQos = true)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            //
            // A participant needs to be Disposed to release middleware resources.
            // The 'using' keyword indicates that it will be Disposed when this
            // scope ends.
            using DomainParticipant participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic = participant.CreateTopic <HelloWorld>("Example PartitionsExample_HelloWorld");

            // Configure the Subscriber's Partition QoS policy.
            SubscriberQos subscriberQos;

            if (useXmlQos)
            {
                // Retrieve the default Subscriber QoS, from USER_QOS_PROFILES.xml
                subscriberQos = QosProvider.Default.GetSubscriberQos();
            }
            else
            {
                subscriberQos = participant.DefaultSubscriberQos.WithPartition(p =>
                {
                    p.Add("ABC");
                    p.Add("X*Z");
                });
            }

            Subscriber subscriber = participant.CreateSubscriber(subscriberQos);

            Console.WriteLine(
                "Subscriber partition set to: "
                + string.Join(separator: ",", values: subscriber.Qos.Partition.Name));

            DataReaderQos readerQos;

            if (useXmlQos)
            {
                // Retrieve the default DataReader QoS, from USER_QOS_PROFILES.xml
                readerQos = QosProvider.Default.GetDataReaderQos();
            }
            else
            {
                readerQos = subscriber.DefaultDataReaderQos
                            .WithReliability(policy => policy.Kind = ReliabilityKind.Reliable)
                            .WithHistory(policy => policy.Kind     = HistoryKind.KeepAll)
                            .WithDurability(policy => policy.Kind  = DurabilityKind.TransientLocal);
            }

            DataReader <HelloWorld> reader = subscriber.CreateDataReader(topic, readerQos);

            // Take all samples as they are received. Stop after taking sampleCount samples.
            await foreach (var sample in reader.TakeAsync().Take(sampleCount))
            {
                if (sample.Info.ValidData)
                {
                    if (sample.Info.State.View == ViewState.New)
                    {
                        // When we receive a new instance because a partition
                        // update made it possible, the View state is
                        // ViewState.New
                        Console.WriteLine("Found new instance");
                    }

                    Console.WriteLine(sample.Data);
                }
            }
        }
        public void TestTakeInstance()
        {
            List <PublicationBuiltinTopicData> data = new List <PublicationBuiltinTopicData>();
            List <SampleInfo> infos = new List <SampleInfo>();
            ReturnCode        ret   = _dr.Read(data, infos);

            Assert.AreEqual(ReturnCode.NoData, ret);
            Assert.AreEqual(0, data.Count);
            Assert.AreEqual(0, infos.Count);

            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindRtpsUdpTransportConfig();

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            var topic = otherParticipant.CreateTopic(TestContext.TestName, typeName);

            Assert.IsNotNull(topic);

            var publisher = otherParticipant.CreatePublisher();

            Assert.IsNotNull(publisher);

            DataWriterQos dwQos = TestHelper.CreateNonDefaultDataWriterQos();

            dwQos.Ownership.Kind = OwnershipQosPolicyKind.SharedOwnershipQos;
            DataWriter dataWriter = publisher.CreateDataWriter(topic, dwQos);

            Assert.IsNotNull(dataWriter);

            Thread.Sleep(500);

            ret = _dr.ReadNextInstance(data, infos, InstanceHandle.HandleNil);
            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(1, data.Count);
            Assert.AreEqual(1, infos.Count);
            TestHelper.TestNonDefaultPublicationData(data.First());

            var handle = infos.First().InstanceHandle;

            data  = new List <PublicationBuiltinTopicData>();
            infos = new List <SampleInfo>();

            ret = _dr.TakeInstance(data, infos, handle);
            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(1, data.Count);
            Assert.AreEqual(1, infos.Count);
            TestHelper.TestNonDefaultPublicationData(data.First());

            ret = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, ret);

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
        /// <summary>
        /// Runs the publisher example.
        /// </summary>
        public static void RunPublisher(
            int domainId,
            int sampleCount,
            uint tokenBucketPeriodMs,
            CancellationToken cancellationToken)
        {
            // Create a custom flow controller configuration
            DomainParticipantQos participantQos = ConfigureFlowController(
                tokenBucketPeriodMs);

            // Start communicating in a domain, usually one participant per application
            using DomainParticipant participant =
                      DomainParticipantFactory.Instance.CreateParticipant(domainId, participantQos);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic =
                participant.CreateTopic <HelloWorld>("Example cfc");

            // Create a Publisher
            Publisher publisher = participant.CreatePublisher();

            // Create a writer with the QoS specified in the default profile
            // in USER_QOS_PROFILES.xml, which sets up the publish mode policy
            DataWriter <HelloWorld> writer = publisher.CreateDataWriter(topic);

            // Create a sample to write with a long payload
            var sample = new HelloWorld {
                str = new string('a', 999)
            };

            for (int count = 0;
                 count < sampleCount && !cancellationToken.IsCancellationRequested;
                 count++)
            {
                // Simulate a bursty writer by sending 10 samples at a time,
                // after sleeping for a period
                if (count % 10 == 0)
                {
                    Thread.Sleep(1000);
                }

                // Modify the data to be sent here
                sample.x = count;

                Console.WriteLine($"Writing x={sample.x}");

                // With asynchronous publish mode, the Write() puts the sample
                // in the queue but doesn't send it until the flow controller
                // indicates so.
                writer.Write(sample);
            }

            try
            {
                // Wait until all written samples have been actually published
                writer.WaitForAsynchronousPublishing(maxWait: Duration.FromSeconds(10));

                // And wait until the DataReader has acknowledged them
                writer.WaitForAcknowledgments(maxWait: Duration.FromSeconds(10));
            }
            catch (TimeoutException)
            {
                Console.WriteLine("Timed out waiting to publish all samples");
            }
        }
        private void RunExample(int domainId, string sensorId)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Uses TemperingApplication QoS profile to set participant name.
            var qosProvider    = new QosProvider("./qos_profiles.xml");
            var participantQos = qosProvider.GetDomainParticipantQos(
                "ChocolateFactoryLibrary::TemperingApplication");
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId, participantQos);

            // Create the topics
            Topic <Temperature> temperatureTopic =
                participant.CreateTopic <Temperature>("ChocolateTemperature");
            Topic <ChocolateLotState> lotStateTopic =
                participant.CreateTopic <ChocolateLotState>("ChocolateLotState");

            // Exercise #1.1: Create a Content-Filtered Topic that filters out
            // chocolate lot state unless the next_station = TEMPERING_CONTROLLER

            // A Publisher allows an application to create one or more DataWriters
            // Create Publisher with default QoS.
            Publisher publisher = participant.CreatePublisher();

            // Create DataWriter of Topic "ChocolateTemperature"
            // using ChocolateTemperatureProfile QoS profile for Streaming Data
            DataWriter <Temperature> temperatureWriter = publisher.CreateDataWriter(
                temperatureTopic,
                qos: qosProvider.GetDataWriterQos("ChocolateFactoryLibrary::ChocolateTemperatureProfile"));

            // Create DataWriter of Topic "ChocolateLotState"
            // using ChocolateLotStateProfile QoS profile for State Data
            DataWriter <ChocolateLotState> lotStateWriter = publisher.CreateDataWriter(
                lotStateTopic,
                qos: qosProvider.GetDataWriterQos("ChocolateFactoryLibrary::ChocolateLotStateProfile"));

            // A Subscriber allows an application to create one or more DataReaders
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // using ChocolateLotStateProfile QoS profile for State Data
            // Exercise #1.2: Change the DataReader's Topic to use a
            // Content-Filtered Topic
            DataReader <ChocolateLotState> lotStateReader = subscriber.CreateDataReader(
                lotStateTopic,
                qos: qosProvider.GetDataReaderQos("ChocolateFactoryLibrary::ChocolateLotStateProfile"),
                preEnableAction: reader => reader.RequestedIncompatibleQos += OnRequestedIncompatibleQos);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            statusCondition.Triggered +=
                _ => ProcessLot(lotStateReader, lotStateWriter);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            // Create a thread to periodically publish the temperature
            Console.WriteLine($"ChocolateTemperature Sensor with ID: {sensorId} starting");
            var temperatureTask = Task.Run(
                () => PublishTemperature(temperatureWriter, sensorId));

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(10));
            }

            temperatureTask.Wait();
        }
예제 #15
0
        public void TestGetKeyValue()
        {
            // Call GetKeyValue with HandleNil
            PublicationBuiltinTopicData data = default;
            SampleInfo info = new SampleInfo();
            ReturnCode ret  = _dr.GetKeyValue(ref data, InstanceHandle.HandleNil);

            Assert.AreEqual(ReturnCode.BadParameter, ret);

            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindRtpsUdpTransportConfig();

            Assert.IsTrue(_participant.WaitForParticipants(1, 20_000));

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            var topic = otherParticipant.CreateTopic(TestContext.TestName, typeName);

            Assert.IsNotNull(topic);

            var publisher = otherParticipant.CreatePublisher();

            Assert.IsNotNull(publisher);

            DataWriterQos dwQos = TestHelper.CreateNonDefaultDataWriterQos();

            dwQos.Ownership.Kind = OwnershipQosPolicyKind.SharedOwnershipQos;
            DataWriter dataWriter = publisher.CreateDataWriter(topic, dwQos);

            Assert.IsNotNull(dataWriter);

            int count = 200;

            ret = ReturnCode.NoData;
            while (ret != ReturnCode.Ok && count > 0)
            {
                Thread.Sleep(100);
                // Get an existing instance
                ret = _dr.ReadNextSample(ref data, info);
                count--;
            }
            Assert.AreEqual(ReturnCode.Ok, ret);
            TestHelper.TestNonDefaultPublicationData(data);

            PublicationBuiltinTopicData aux = default;

            ret = _dr.GetKeyValue(ref aux, info.InstanceHandle);
            Assert.AreEqual(ReturnCode.Ok, ret);
            for (int i = 0; i < 16; i++)
            {
                Assert.AreEqual(data.Key.Value[i], aux.Key.Value[i]);
            }

            ret = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, ret);

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
예제 #16
0
        static void Main(string[] args)
        {
            Ace.Init();

            DomainParticipantFactory dpf         = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSConfigFile", "rtps.ini");
            DomainParticipant        participant = dpf.CreateParticipant(42);

            if (participant == null)
            {
                throw new Exception("Could not create the participant");
            }

            MessageTypeSupport support = new MessageTypeSupport();
            ReturnCode         result  = support.RegisterType(participant, support.GetTypeName());

            if (result != ReturnCode.Ok)
            {
                throw new Exception("Could not register type: " + result.ToString());
            }

            Topic topic = participant.CreateTopic("MessageTopic", support.GetTypeName());

            if (topic == null)
            {
                throw new Exception("Could not create the message topic");
            }

            Subscriber subscriber = participant.CreateSubscriber();

            if (subscriber == null)
            {
                throw new Exception("Could not create the subscriber");
            }

            DataReader reader = subscriber.CreateDataReader(topic);

            if (reader == null)
            {
                throw new Exception("Could not create the message data reader");
            }
            MessageDataReader messageReader = new MessageDataReader(reader);

            while (true)
            {
                StatusMask mask = messageReader.StatusChanges;
                if ((mask & StatusKind.DataAvailableStatus) != 0)
                {
                    List <Message>    receivedData = new List <Message>();
                    List <SampleInfo> receivedInfo = new List <SampleInfo>();
                    result = messageReader.Take(receivedData, receivedInfo);

                    if (result == ReturnCode.Ok)
                    {
                        bool messageReceived = false;
                        for (int i = 0; i < receivedData.Count; i++)
                        {
                            if (receivedInfo[i].ValidData)
                            {
                                Console.WriteLine(receivedData[i].Content);
                                messageReceived = true;
                            }
                        }

                        if (messageReceived)
                        {
                            break;
                        }
                    }
                }

                System.Threading.Thread.Sleep(100);
            }

            Console.WriteLine("Press a key to exit...");
            Console.ReadKey();

            participant.DeleteContainedEntities();
            dpf.DeleteParticipant(participant);
            ParticipantService.Instance.Shutdown();

            Ace.Fini();
        }
예제 #17
0
        public void TestReadInstance()
        {
            List <SubscriptionBuiltinTopicData> data = new List <SubscriptionBuiltinTopicData>();
            List <SampleInfo> infos = new List <SampleInfo>();
            ReturnCode        ret   = _dr.Read(data, infos);

            Assert.AreEqual(ReturnCode.NoData, ret);
            Assert.AreEqual(0, data.Count);
            Assert.AreEqual(0, infos.Count);

            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindRtpsUdpTransportConfig();

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            var topic = otherParticipant.CreateTopic(TestContext.TestName, typeName);

            Assert.IsNotNull(topic);

            var subscriber = otherParticipant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReaderQos drQos      = TestHelper.CreateNonDefaultDataReaderQos();
            DataReader    dataReader = subscriber.CreateDataReader(topic, drQos);

            Assert.IsNotNull(dataReader);

            int count = 200;

            ret = ReturnCode.NoData;
            while (ret != ReturnCode.Ok && count > 0)
            {
                Thread.Sleep(100);
                ret = _dr.ReadNextInstance(data, infos, InstanceHandle.HandleNil);
                count--;
            }

            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(1, data.Count);
            Assert.AreEqual(1, infos.Count);
            TestHelper.TestNonDefaultSubscriptionData(data.First());

            var handle = infos.First().InstanceHandle;

            data  = new List <SubscriptionBuiltinTopicData>();
            infos = new List <SampleInfo>();

            ret = _dr.ReadInstance(data, infos, handle);
            Assert.AreEqual(ReturnCode.Ok, ret);
            Assert.AreEqual(1, data.Count);
            Assert.AreEqual(1, infos.Count);
            TestHelper.TestNonDefaultSubscriptionData(data.First());

            ret = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, ret);

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
예제 #18
0
        public void TestCreateDataWriter()
        {
            // Initialize entities
            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(_participant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            Topic topic = _participant.CreateTopic(nameof(TestCreateDataWriter), typeName);

            Assert.IsNotNull(topic);
            Assert.IsNull(topic.GetListener());
            Assert.AreEqual(nameof(TestCreateDataWriter), topic.Name);
            Assert.AreEqual(typeName, topic.TypeName);

            Publisher publisher = _participant.CreatePublisher();

            Assert.IsNotNull(publisher);

            // Test simplest overload
            DataWriter datawriter1 = publisher.CreateDataWriter(topic);

            Assert.IsNotNull(datawriter1);
            Assert.AreEqual(publisher, datawriter1.Publisher);
            Assert.IsNull(datawriter1.GetListener());

            DataWriterQos qos = new DataWriterQos();

            result = datawriter1.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataWriterQos(qos);

            // Test overload with QoS parameter
            qos = TestHelper.CreateNonDefaultDataWriterQos();
            DataWriter datawriter2 = publisher.CreateDataWriter(topic, qos);

            Assert.IsNotNull(datawriter2);
            Assert.AreEqual(publisher, datawriter2.Publisher);
            Assert.IsNull(datawriter2.GetListener());

            qos    = new DataWriterQos();
            result = datawriter2.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataWriterQos(qos);

            // Test overload with listener parameter
            MyDataWriterListener listener    = new MyDataWriterListener();
            DataWriter           datawriter3 = publisher.CreateDataWriter(topic, listener);

            Assert.IsNotNull(datawriter3);
            Assert.AreEqual(publisher, datawriter3.Publisher);
            MyDataWriterListener received = (MyDataWriterListener)datawriter3.GetListener();

            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataWriterQos();
            result = datawriter3.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataWriterQos(qos);

            // Test overload with listener and StatusMask parameters
            listener = new MyDataWriterListener();
            DataWriter datawriter4 = publisher.CreateDataWriter(topic, listener, StatusMask.AllStatusMask);

            Assert.IsNotNull(datawriter4);
            Assert.AreEqual(publisher, datawriter4.Publisher);
            received = (MyDataWriterListener)datawriter4.GetListener();
            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataWriterQos();
            result = datawriter4.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataWriterQos(qos);

            // Test overload with QoS and listener parameters
            qos      = TestHelper.CreateNonDefaultDataWriterQos();
            listener = new MyDataWriterListener();
            DataWriter datawriter5 = publisher.CreateDataWriter(topic, qos, listener);

            Assert.IsNotNull(datawriter5);
            Assert.AreEqual(publisher, datawriter5.Publisher);
            received = (MyDataWriterListener)datawriter5.GetListener();
            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataWriterQos();
            result = datawriter5.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataWriterQos(qos);

            // Test full call overload
            qos      = TestHelper.CreateNonDefaultDataWriterQos();
            listener = new MyDataWriterListener();
            DataWriter datawriter6 = publisher.CreateDataWriter(topic, qos, listener, StatusMask.AllStatusMask);

            Assert.IsNotNull(datawriter6);
            Assert.AreEqual(publisher, datawriter6.Publisher);
            received = (MyDataWriterListener)datawriter6.GetListener();
            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataWriterQos();
            result = datawriter6.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataWriterQos(qos);

            // Test with null parameter
            DataWriter nullDataWriter = publisher.CreateDataWriter(null);

            Assert.IsNull(nullDataWriter);

            // Test with wrong qos
            DataWriterQos dwQos = new DataWriterQos();

            dwQos.ResourceLimits.MaxSamples            = 1;
            dwQos.ResourceLimits.MaxSamplesPerInstance = 2;
            nullDataWriter = publisher.CreateDataWriter(topic, dwQos);
            Assert.IsNull(nullDataWriter);
        }
예제 #19
0
        private void RunExample(
            int domainId,
            int sampleCount,
            string sensorId)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateTemperature" with type Temperature
            // In this example we use a DynamicType defined in XML, which creates
            // a DynamicData topic.
            var provider = new QosProvider("../chocolate_factory.xml");
            Topic <DynamicData> topic = participant.CreateTopic(
                "ChocolateTemperature",
                provider.GetType("Temperature"));

            // Exercise #2.1: Add new Topic
            Topic <DynamicData> lotStateTopic = participant.CreateTopic(
                "ChocolateLotState",
                provider.GetType("ChocolateLotState"));

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateTemperature"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <DynamicData> writer = publisher.CreateDataWriter(topic);

            // Create a DynamicData sample for writing
            DynamicData sample = writer.CreateData();

            // Exercise #2.2: Add new DataWriter and data sample
            DataWriter <DynamicData> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);
            DynamicData lotStateSample = lotStateWriter.CreateData();

            Random rand = new Random();

            for (int count = 0; count < sampleCount && !shutdownRequested; count++)
            {
                // Modify the data to be written here
                sample.SetValue("sensor_id", sensorId);
                sample.SetValue("degrees", rand.Next(30, 33));

                Console.WriteLine($"Writing ChocolateTemperature, count {count}");
                writer.Write(sample);

                // Exercise #2.3 Write data with new ChocolateLotState DataWriter
                lotStateWriter.SetValue("lot_id", count % 100);
                // SetAnyValue performs type conversions. In this case it can
                // translate a string to the corresponding enumerator.
                lotStateWriter.SetAnyValue("lot_status", "WAITING");
                lotStateWriter.Write(lotStateSample);

                // Exercise #1.1: Change this to sleep 100 ms in between writing temperatures


                Thread.Sleep(4000);
            }
        }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState
            // In this example we use a DynamicType defined in XML, which creates
            // a DynamicData topic.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic(
                "ChocolateLotState",
                types.ChocolateLotState);
            // Exercise #4.1: Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic = participant.CreateTopic(
                "ChocolateTemperature",
                types.Temperature);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // DataReader QoS is configured in USER_QOS_PROFILES.xml
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Exercise #4.2: Add a DataReader for Temperature to this application
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(temperatureTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered += _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            WaitSet waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Exercise #4.3: Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
예제 #21
0
        public void TestOnPublicationLost()
        {
            ManualResetEventSlim evt = new ManualResetEventSlim(false);
            DomainParticipant    domainParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.INFOREPO_DOMAIN);

            Assert.IsNotNull(domainParticipant);
            domainParticipant.BindTcpTransportConfig();

            Publisher publisher = domainParticipant.CreatePublisher();

            Assert.IsNotNull(publisher);

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(domainParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            Topic topic = domainParticipant.CreateTopic("TestOnPublicationLostDisconnected", typeName);

            Assert.IsNotNull(topic);

            MyDataWriterListener listener = new MyDataWriterListener();
            DataWriter           writer   = publisher.CreateDataWriter(topic, listener);

            int count = 0;

            listener.PublicationLost += (w, s) =>
            {
                Assert.AreEqual(writer, w);
                Assert.AreEqual(1, s.SubscriptionHandles.Count());
                Assert.AreNotEqual(InstanceHandle.HandleNil, s.SubscriptionHandles.First());
                count++;
                evt.Set();
            };

            SupportProcessHelper supportProcess = new SupportProcessHelper(TestContext);
            Process process = supportProcess.SpawnSupportProcess(SupportTestKind.PublicationLostTest);

            try
            {
                // Wait for discovery
                bool found = writer.WaitForSubscriptions(1, 20000);
                Assert.IsTrue(found);
            }
            finally
            {
                supportProcess.KillProcess(process);
            }

            bool resp = evt.Wait(20000);

            Assert.IsTrue(resp);
            Assert.AreEqual(1, count);

            // Remove the listener to avoid extra messages
            result = writer.SetListener(null);
            Assert.AreEqual(ReturnCode.Ok, result);

            domainParticipant.DeleteContainedEntities();
            AssemblyInitializer.Factory.DeleteParticipant(domainParticipant);

            evt.Dispose();
        }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // Loads the QoS from the qos_profiles.xml file.
            var qosProvider = new QosProvider("./qos_profiles.xml");

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Load DomainParticipant QoS profile
            var participantQos = qosProvider.GetDomainParticipantQos(
                "ChocolateFactoryLibrary::MonitoringControlApplication");
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId, participantQos);

            // A Topic has a name and a datatype. Create a Topic with type
            // ChocolateLotState.  Topic name is a constant defined in the IDL file.
            Topic <ChocolateLotState> lotStateTopic =
                participant.CreateTopic <ChocolateLotState>("ChocolateLotState");
            // Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic =
                participant.CreateTopic <Temperature>("ChocolateTemperature");
            ContentFilteredTopic <Temperature> filteredTemperatureTopic =
                participant.CreateContentFilteredTopic(
                    name: "FilteredTemperature",
                    relatedTopic: temperatureTopic,
                    filter: new Filter(
                        expression: "degrees > %0 or degrees < %1",
                        parameters: new string[] { "32", "30" }));

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            var writerQos = qosProvider.GetDataWriterQos(
                "ChocolateFactoryLibrary::ChocolateLotStateProfile");
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic, writerQos);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // DataReader QoS is configured in USER_QOS_PROFILES.xml
            var readerQos = qosProvider.GetDataReaderQos(
                "ChocolateFactoryLibrary::ChocolateLotStateProfile");
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic, readerQos);

            // Add a DataReader for Temperature to this application
            readerQos = qosProvider.GetDataReaderQos(
                "ChocolateFactoryLibrary::ChocolateTemperatureProfile");
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(filteredTemperatureTopic, readerQos);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered +=
                _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }
예제 #23
0
        public void TestGetKeyValue()
        {
            ReturnCode        ret;
            DomainParticipant otherParticipant = null;
            Topic             topic            = null;

            try
            {
                // Call GetKeyValue with HandleNil
                TopicBuiltinTopicData data = default;
                SampleInfo            info = new SampleInfo();
                ret = _dr.GetKeyValue(ref data, InstanceHandle.HandleNil);
                Assert.AreEqual(ReturnCode.BadParameter, ret);

                otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.INFOREPO_DOMAIN);
                Assert.IsNotNull(otherParticipant);
                otherParticipant.BindRtpsUdpTransportConfig();

                TestStructTypeSupport support = new TestStructTypeSupport();
                string     typeName           = support.GetTypeName();
                ReturnCode result             = support.RegisterType(otherParticipant, typeName);
                Assert.AreEqual(ReturnCode.Ok, result);

                TopicQos qos = TestHelper.CreateNonDefaultTopicQos();
                topic = otherParticipant.CreateTopic(TestContext.TestName, typeName, qos);
                Assert.IsNotNull(topic);

                int count = 200;
                ret = ReturnCode.NoData;
                while (ret != ReturnCode.Ok && count > 0)
                {
                    Thread.Sleep(100);
                    // Get the for an existing instance
                    ret = _dr.ReadNextSample(ref data, info);
                    count--;
                }

                Assert.AreEqual(ReturnCode.Ok, ret);
                Assert.AreEqual(typeName, data.TypeName);
                Assert.IsNotNull(data.Key);
                TestHelper.TestNonDefaultTopicData(data);

                TopicBuiltinTopicData aux = default;
                ret = _dr.GetKeyValue(ref aux, info.InstanceHandle);
                Assert.AreEqual(ReturnCode.Ok, ret);
                for (int i = 0; i < 16; i++)
                {
                    Assert.AreEqual(data.Key.Value[i], aux.Key.Value[i]);
                }
            }
            finally
            {
                ret = otherParticipant.DeleteTopic(topic);
                Assert.AreEqual(ReturnCode.Ok, ret);
                ret = otherParticipant.DeleteContainedEntities();
                Assert.AreEqual(ReturnCode.Ok, ret);

                ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
                Assert.AreEqual(ReturnCode.Ok, ret);
            }
        }
예제 #24
0
        public void TestGetMatchedSubscriptionData()
        {
            // Initialize entities
            DataWriterQos dwQos = TestHelper.CreateNonDefaultDataWriterQos();

            dwQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            DataWriter writer = _publisher.CreateDataWriter(_topic, dwQos);

            Assert.IsNotNull(writer);

            // DCPSInfoRepo-based discovery generates Built-In Topic data once (inside the
            // info repo process) and therefore all known entities in the domain are
            // reflected in the Built-In Topics.  RTPS discovery, on the other hand, follows
            // the DDS specification and omits "local" entities from the Built-In Topics.
            // The definition of "local" means those entities belonging to the same Domain
            // Participant as the given Built-In Topic Subscriber.
            // https://github.com/objectcomputing/OpenDDS/blob/master/docs/design/RTPS

            // OPENDDS ISSUE: GetMatchedSubscriptions returns local entities but GetMatchedSubscriptionData doesn't
            // because is looking in the Built-in topic. If not found in the built-in, shouldn't try to look locally?
            // WORKAROUND: Create another particpant for the DataReader.
            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);

            Assert.IsNotNull(otherParticipant);
            otherParticipant.BindRtpsUdpTransportConfig();

            TestStructTypeSupport support = new TestStructTypeSupport();
            string     typeName           = support.GetTypeName();
            ReturnCode result             = support.RegisterType(otherParticipant, typeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            Topic otherTopic = otherParticipant.CreateTopic(nameof(TestGetMatchedSubscriptionData), typeName);

            Assert.IsNotNull(otherTopic);

            Subscriber subscriber = otherParticipant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReaderQos drQos  = TestHelper.CreateNonDefaultDataReaderQos();
            DataReader    reader = subscriber.CreateDataReader(otherTopic, drQos);

            Assert.IsNotNull(reader);

            // Wait for subscriptions
            bool found = writer.WaitForSubscriptions(1, 5000);

            Assert.IsTrue(found);

            // Get the matched subscriptions
            List <InstanceHandle> list = new List <InstanceHandle>();

            result = writer.GetMatchedSubscriptions(list);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(1, list.Count);

            // Get the matched subscription data
            SubscriptionBuiltinTopicData data = default;

            result = writer.GetMatchedSubscriptionData(list.First(), ref data);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultSubscriptionData(data);

            // Destroy the other participant
            result = otherParticipant.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, result);

            result = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, result);
        }
        private void RunExample(int domainId, string sensorId)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create Topics using the types
            // defined in chocolate_factory.xml
            var provider = new QosProvider("../chocolate_factory.xml");
            Topic <Temperature> temperatureTopic = participant.CreateTopic(
                "ChocolateTemperature",
                types.Temperature);
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic(
                "ChocolateLotState",
                types.ChocolateLotState);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // Create DataWriters of Topics "ChocolateTemperature" & "ChocolateLotState"
            // DataWriter QoS is configured in USER_QOS_PROFILES.xml
            DataWriter <Temperature> temperatureWriter =
                publisher.CreateDataWriter(temperatureTopic);
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // This DataReader reads data of type Temperature on Topic
            // "ChocolateTemperature". DataReader QoS is configured in
            // USER_QOS_PROFILES.xml
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            // Enable the 'data available' status.
            statusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate an event handler with the status condition.
            // This will run when the condition is triggered, in the context of
            // the dispatch call (see below)
            statusCondition.Triggered +=
                _ => ProcessLot(lotStateReader, lotStateWriter);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            // Create a thread to periodically publish the temperature
            Console.WriteLine($"ChocolateTemperature Sensor with ID: {sensorId} starting");
            var temperatureTask = Task.Run(
                () => PublishTemperature(temperatureWriter, sensorId));

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            temperatureTask.Wait();
        }
        /// <summary>
        /// Runs the subscriber example.
        /// </summary>
        public static async Task RunSubscriber(
            int domainId,
            int sampleCount,
            CancellationToken cancellationToken,
            bool useXmlQos = false)
        {
            // Start communicating in a domain, usually one participant per application
            // Load default QoS profile from USER_QOS_PROFILES.xml file
            using DomainParticipant participant =
                      DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <HelloWorld> topic =
                participant.CreateTopic <HelloWorld>("Example async");

            // Create a subscriber
            Subscriber subscriber = participant.CreateSubscriber();

            DataReaderQos readerQos;

            if (useXmlQos)
            {
                // Retrieve the DataReaderQos from the default profile in
                // USER_QOS_PROFILES.xml
                readerQos = QosProvider.Default.GetDataReaderQos();
            }
            else
            {
                // Configure the DataReaderQos in code, to the same effect as
                // the XML file.
                readerQos = subscriber.DefaultDataReaderQos
                            .WithReliability(policy => policy.Kind = ReliabilityKind.Reliable)
                            .WithHistory(policy => policy.Kind     = HistoryKind.KeepAll);
            }

            DataReader <HelloWorld> reader =
                subscriber.CreateDataReader(topic, readerQos);

            var beginTime = DateTime.Now;

            // TakeAsync provides an IAsyncEnumerable that returns new data
            // samples when they are available, awaiting as necessary. The
            // cancellation token allows stopping the loop.
            int samplesRead = 0;

            await foreach (var sample in reader
                           .TakeAsync()
                           .WithCancellation(cancellationToken))
            {
                if (sample.Info.ValidData)
                {
                    samplesRead++;
                    var elapsedTime = (DateTime.Now - beginTime).TotalSeconds;
                    Console.WriteLine($"At t={elapsedTime}s, got x={sample.Data.x}");

                    if (samplesRead == sampleCount)
                    {
                        break;
                    }
                }
            }
        }
예제 #27
0
        private void RunExample(int domainId, string stationKind)
        {
            if (!Enum.TryParse <StationKind>(stationKind, out var currentStation))
            {
                throw new ArgumentException("Invalid station");
            }

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Uses TemperingApplication QoS profile to set participant name.
            var qosProvider = new QosProvider("./qos_profiles.xml");

            // By specifying a default library, we can later refer to the
            // profiles without the library name
            qosProvider.DefaultLibrary = "ChocolateFactoryLibrary";

            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(
                domainId,
                qosProvider.GetDomainParticipantQos("IngredientApplication"));

            Topic <Temperature> temperatureTopic =
                participant.CreateTopic <Temperature>("ChocolateTemperature");
            Topic <ChocolateLotState> lotStateTopic =
                participant.CreateTopic <ChocolateLotState>("ChocolateLotState");

            ContentFilteredTopic <ChocolateLotState> filteredLotStateTopic =
                participant.CreateContentFilteredTopic(
                    name: "FilteredLot",
                    relatedTopic: lotStateTopic,
                    filter: new Filter(
                        expression: "next_station = %0",
                        parameters: new string[] { $"'{stationKind}'" }));

            Publisher publisher = participant.CreatePublisher();

            // Create DataWriter of Topic "ChocolateLotState"
            // using ChocolateLotStateProfile QoS profile for State Data
            DataWriter <ChocolateLotState> lotStateWriter = publisher.CreateDataWriter(
                lotStateTopic,
                qosProvider.GetDataWriterQos("ChocolateLotStateProfile"));

            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState", filtered by
            // next_station, and using ChocolateLotStateProfile QoS profile for
            // State Data.
            DataReader <ChocolateLotState> lotStateReader = subscriber.CreateDataReader(
                filteredLotStateTopic,
                qosProvider.GetDataReaderQos("ChocolateLotStateProfile"));

            // Monitor the DataAvailable status
            StatusCondition statusCondition = lotStateReader.StatusCondition;

            statusCondition.EnabledStatuses = StatusMask.DataAvailable;
            statusCondition.Triggered      +=
                _ => ProcessLot(currentStation, lotStateReader, lotStateWriter);
            var waitset = new WaitSet();

            waitset.AttachCondition(statusCondition);

            while (!shutdownRequested)
            {
                // Wait for ChocolateLotState
                Console.WriteLine("Waiting for lot");
                waitset.Dispatch(Duration.FromSeconds(10));
            }
        }
예제 #28
0
        public OpenDDSharpService()
        {
            _config = ServiceLocator.Current.GetInstance <IConfigurationService>();

            _disc = new RtpsDiscovery(RTPS_DISCOVERY)
            {
                ResendPeriod = new TimeValue {
                    Seconds = 1
                },
                SedpMulticast = true
            };

            ParticipantService.Instance.AddDiscovery(_disc);
            ParticipantService.Instance.DefaultDiscovery = RTPS_DISCOVERY;

            long   ticks      = DateTime.Now.Ticks;
            string configName = "openddsharp_rtps_interop_" + ticks.ToString();;
            string instName   = "internal_openddsharp_rtps_transport_" + ticks.ToString();;

            _tConfig = TransportRegistry.Instance.CreateConfig(configName);
            _inst    = TransportRegistry.Instance.CreateInst(instName, "rtps_udp");
            _rui     = new RtpsUdpInst(_inst);
            _tConfig.Insert(_inst);
            TransportRegistry.Instance.GlobalConfig = _tConfig;
            ParticipantService.Instance.SetRepoDomain(0, RTPS_DISCOVERY);

            _domainFactory = ParticipantService.Instance.GetDomainParticipantFactory("-DCPSDebugLevel", "10", "-ORBLogFile", "LogFile.log", "-ORBDebugLevel", "10");

            _participant = _domainFactory.CreateParticipant(0);
            if (_participant == null)
            {
                throw new Exception("Could not create the participant");
            }

            ShapeTypeTypeSupport support = new ShapeTypeTypeSupport();
            ReturnCode           result  = support.RegisterType(_participant, TYPE_NAME);

            if (result != ReturnCode.Ok)
            {
                throw new Exception("Could not register type: " + result.ToString());
            }

            _squareTopic = _participant.CreateTopic(SQUARE_TOPIC_NAME, TYPE_NAME);
            if (_squareTopic == null)
            {
                throw new Exception("Could not create square topic");
            }

            _circleTopic = _participant.CreateTopic(CIRCLE_TOPIC_NAME, TYPE_NAME);
            if (_circleTopic == null)
            {
                throw new Exception("Could not create circle topic");
            }

            _triangleTopic = _participant.CreateTopic(TRIANGLE_TOPIC_NAME, TYPE_NAME);
            if (_triangleTopic == null)
            {
                throw new Exception("Could not create triangle topic");
            }

            _publisher = _participant.CreatePublisher();
            if (_publisher == null)
            {
                throw new Exception("Could not create publisher");
            }

            _subscriber = _participant.CreateSubscriber();
            if (_subscriber == null)
            {
                throw new Exception("Could not create subscriber");
            }

            _shapeWaitSets = new List <ShapeWaitSet>();
            _shapeDynamics = new List <ShapeDynamic>();

            _cfCircleCount   = 0;
            _cfSquareCount   = 0;
            _cfTriangleCount = 0;
        }
        /// <summary>
        /// Runs the subscriber example.
        /// </summary>
        public static void RunSubscriber(
            int domainId    = 0,
            int sampleCount = int.MaxValue)
        {
            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // DomainParticipant QoS is configured in USER_QOS_PROFILES.xml
            //
            // A participant needs to be Disposed to release middleware resources.
            // The 'using' keyword indicates that it will be Disposed when this
            // scope ends.
            using DomainParticipant participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // A Topic has a name and a datatype.
            Topic <StockPrice> topic = participant.CreateTopic <StockPrice>("Example market_data");

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create a ContentFiltered Topic and specify the STRINGMATCH filter name
            // to use a built-in filter for matching multiple strings.
            // More information can be found in the example
            var symbolFilter = new Filter(
                expression: "Symbol MATCH 'A'",
                parameters: Array.Empty <string>(),
                name: Filter.StringMatchFilterName);

            ContentFilteredTopic <StockPrice> filteredTopic =
                participant.CreateContentFilteredTopic(
                    name: "Filtered Example market_data",
                    relatedTopic: topic,
                    filter: symbolFilter);

            // Create a reader for the content-filtered topic, and set a
            // handler for the DataAvailable event that simply prints the data.
            DataReader <StockPrice> reader = subscriber.CreateDataReader(
                filteredTopic,
                preEnableAction: reader =>
            {
                reader.DataAvailable += _ => PrintData(reader);
            });

            int t = 0;

            while (receivedSamples < sampleCount)
            {
                if (t == 3)
                {
                    // On t = 3 we add the symbol 'D' to the filter parameter
                    // to match 'A' and 'D'.
                    filteredTopic.AppendToExpressionParameter(0, "D");
                    Console.WriteLine("Changed filter to Symbol MATCH 'A,D'");
                }
                else if (t == 6)
                {
                    // On t = 6 we remove the symbol 'A' to the filter parameter
                    // to match only 'D'.
                    filteredTopic.RemoveFromExpressionParameter(0, "A");
                    Console.WriteLine("Changed filter to Symbol MATCH 'D'");
                }

                Thread.Sleep(4000);
                t++;
            }
        }
        private void RunExample(
            int domainId       = 0,
            uint lotsToProcess = 10)
        {
            // Exercise #1.1: Add QoS provider

            // A DomainParticipant allows an application to begin communicating in
            // a DDS domain. Typically there is one DomainParticipant per application.
            // Exercise #1.2: Load DomainParticipant QoS profile
            DomainParticipant participant = DomainParticipantFactory.Instance
                                            .CreateParticipant(domainId);

            // A Topic has a name and a datatype. Create a Topic named
            // "ChocolateLotState" with type ChocolateLotState.
            Topic <ChocolateLotState> lotStateTopic = participant.CreateTopic <ChocolateLotState>(
                CHOCOLATE_LOT_STATE_TOPIC.Value);
            // Add a Topic for Temperature to this application
            Topic <Temperature> temperatureTopic = participant.CreateTopic <Temperature>(
                CHOCOLATE_TEMPERATURE_TOPIC.Value);

            // A Publisher allows an application to create one or more DataWriters
            // Publisher QoS is configured in USER_QOS_PROFILES.xml
            Publisher publisher = participant.CreatePublisher();

            // This DataWriter writes data on Topic "ChocolateLotState"
            // Exercise #4.1: Load ChocolateLotState DataWriter QoS profile after
            // debugging incompatible QoS
            DataWriter <ChocolateLotState> lotStateWriter =
                publisher.CreateDataWriter(lotStateTopic);

            // A Subscriber allows an application to create one or more DataReaders
            // Subscriber QoS is configured in USER_QOS_PROFILES.xml
            Subscriber subscriber = participant.CreateSubscriber();

            // Create DataReader of Topic "ChocolateLotState".
            // Exercise #1.3: Update the lotStateReader and temperatureReader
            // to use correct QoS
            DataReader <ChocolateLotState> lotStateReader =
                subscriber.CreateDataReader(lotStateTopic);

            // Add a DataReader for Temperature to this application
            DataReader <Temperature> temperatureReader =
                subscriber.CreateDataReader(temperatureTopic);

            // Obtain the DataReader's Status Condition
            StatusCondition temperatureStatusCondition = temperatureReader.StatusCondition;

            temperatureStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            // Associate a handler with the status condition. This will run when the
            // condition is triggered, in the context of the dispatch call (see below)
            temperatureStatusCondition.Triggered += _ => MonitorTemperature(temperatureReader);

            // Do the same with the lotStateReader's StatusCondition
            StatusCondition lotStateStatusCondition = lotStateReader.StatusCondition;

            lotStateStatusCondition.EnabledStatuses = StatusMask.DataAvailable;

            int lotsProcessed = 0;

            lotStateStatusCondition.Triggered +=
                _ => lotsProcessed            += MonitorLotState(lotStateReader);

            // Create a WaitSet and attach the StatusCondition
            var waitset = new WaitSet();

            waitset.AttachCondition(lotStateStatusCondition);

            // Add the new DataReader's StatusCondition to the Waitset
            waitset.AttachCondition(temperatureStatusCondition);

            // Start publishing in a separate thread
            var startLotTask = Task.Run(() => PublishStartLot(lotStateWriter, lotsToProcess));

            while (!shutdownRequested && lotsProcessed < lotsToProcess)
            {
                waitset.Dispatch(Duration.FromSeconds(4));
            }

            startLotTask.Wait();
        }