コード例 #1
0
        private ShapeWaitSet CreateSquareReader()
        {
            DataReaderQos qos = GetDataReaderQos();

            ITopicDescription topic = null;

            if (_config.ReaderFilterConfig.Enabled)
            {
                string filter = _config.ReaderFilterConfig.FilterKind == FilterKind.Inside ? FILTER_INSIDE : FILTER_OUTSIDE;
                topic = _participant.CreateContentFilteredTopic("CFSquare" + (++_cfSquareCount),
                                                                _squareTopic, filter,
                                                                _config.ReaderFilterConfig.X0.ToString(),
                                                                _config.ReaderFilterConfig.X1.ToString(),
                                                                _config.ReaderFilterConfig.Y0.ToString(),
                                                                _config.ReaderFilterConfig.Y1.ToString());
            }
            else
            {
                topic = _squareTopic;
            }

            DataReader reader = _subscriber.CreateDataReader(topic, qos);

            if (reader == null)
            {
                throw new Exception("Could not create square data reader");
            }

            ShapeTypeDataReader squareDataReader = new ShapeTypeDataReader(reader);

            return(new ShapeWaitSet(squareDataReader, SquareTopicDataAvailable));
        }
コード例 #2
0
        public void TestGetPublicationMatchedStatus()
        {
            // Initialize entities
            DataWriterQos qos = new DataWriterQos();

            qos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos;
            DataWriter writer = _publisher.CreateDataWriter(_topic, qos);

            Assert.IsNotNull(writer);

            // If not datareaders are created should return the default status
            PublicationMatchedStatus status = default;
            ReturnCode result = writer.GetPublicationMatchedStatus(ref status);

            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, status.CurrentCount);
            Assert.AreEqual(0, status.CurrentCountChange);
            Assert.AreEqual(0, status.TotalCount);
            Assert.AreEqual(0, status.TotalCountChange);
            Assert.AreEqual(InstanceHandle.HandleNil, status.LastSubscriptionHandle);

            // Create a not compatible reader
            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReaderQos drQos = new DataReaderQos();

            drQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            DataReader reader = subscriber.CreateDataReader(_topic, drQos);

            Assert.IsNotNull(reader);

            // Wait for discovery and check the status
            System.Threading.Thread.Sleep(100);

            result = writer.GetPublicationMatchedStatus(ref status);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, status.CurrentCount);
            Assert.AreEqual(0, status.CurrentCountChange);
            Assert.AreEqual(0, status.TotalCount);
            Assert.AreEqual(0, status.TotalCountChange);
            Assert.AreEqual(InstanceHandle.HandleNil, status.LastSubscriptionHandle);

            // Create a compatible reader
            DataReader otherReader = subscriber.CreateDataReader(_topic);

            Assert.IsNotNull(otherReader);

            // Wait for discovery and check the status
            System.Threading.Thread.Sleep(100);

            result = writer.GetPublicationMatchedStatus(ref status);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(1, status.CurrentCount);
            Assert.AreEqual(1, status.CurrentCountChange);
            Assert.AreEqual(1, status.TotalCount);
            Assert.AreEqual(1, status.TotalCountChange);
            Assert.AreEqual(otherReader.InstanceHandle, status.LastSubscriptionHandle);
        }
コード例 #3
0
        public void TestGetMatchedSubscriptions()
        {
            // Initialize entities
            DataWriterQos qos = new DataWriterQos();

            qos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos;
            DataWriter writer = _publisher.CreateDataWriter(_topic, qos);

            Assert.IsNotNull(writer);

            // Test matched subscriptions without any match
            List <InstanceHandle> list = new List <InstanceHandle>
            {
                InstanceHandle.HandleNil,
            };
            ReturnCode result = writer.GetMatchedSubscriptions(list);

            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, list.Count);

            // Create a not compatible reader
            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReaderQos drQos = new DataReaderQos();

            drQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            DataReader reader = subscriber.CreateDataReader(_topic, drQos);

            Assert.IsNotNull(reader);

            // Wait for discovery and check the matched subscriptions
            System.Threading.Thread.Sleep(100);

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

            // Create a compatible reader
            DataReader otherReader = subscriber.CreateDataReader(_topic);

            Assert.IsNotNull(otherReader);

            // Wait for discovery and check the matched subscriptions
            System.Threading.Thread.Sleep(100);

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

            // Test with null parameter
            result = writer.GetMatchedSubscriptions(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);
        }
コード例 #4
0
        public void TestDeleteContainedEntities()
        {
            // 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(TestDeleteContainedEntities), typeName);

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

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            // Call DeleteContainedEntities in an empty subscriber
            result = subscriber.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, result);

            // Create a DataReader in the subscriber
            DataReader dataReader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(subscriber);

            // Try to delete the publisher without delete the datareader
            result = _participant.DeleteSubscriber(subscriber);
            Assert.AreEqual(ReturnCode.PreconditionNotMet, result);

            // Call DeleteContainedEntities and remove the subscriber again
            result = subscriber.DeleteContainedEntities();
            Assert.AreEqual(ReturnCode.Ok, result);

            result = _participant.DeleteSubscriber(subscriber);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Create a DataReader with null parameter
            DataReader nullDataReader = subscriber.CreateDataReader(null);

            Assert.IsNull(nullDataReader);

            // Create DataReader with incorrect qos
            DataReaderQos drQos = new DataReaderQos();

            drQos.ResourceLimits.MaxSamples            = 1;
            drQos.ResourceLimits.MaxSamplesPerInstance = 2;
            nullDataReader = subscriber.CreateDataReader(topic, drQos);
            Assert.IsNull(nullDataReader);
        }
コード例 #5
0
        public void TestLookupDataReader()
        {
            // 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(TestLookupDataReader), typeName);

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

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            Subscriber otherSubscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(otherSubscriber);

            // Create a DataReader and lookup in the subscribers
            DataReader datareader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(datareader);
            Assert.AreEqual(subscriber, datareader.Subscriber);
            Assert.IsNull(datareader.GetListener());

            DataReader received = subscriber.LookupDataReader(nameof(TestLookupDataReader));

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

            received = otherSubscriber.LookupDataReader(nameof(TestLookupDataReader));
            Assert.IsNull(received);

            // Create other DataReader in the same topic and lookup again
            DataReader otherDatareader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(otherDatareader);
            Assert.AreEqual(subscriber, otherDatareader.Subscriber);
            Assert.IsNull(otherDatareader.GetListener());

            received = subscriber.LookupDataReader(nameof(TestLookupDataReader));
            Assert.IsNotNull(received);
            Assert.IsTrue(datareader == received || otherDatareader == received);

            received = otherSubscriber.LookupDataReader(nameof(TestLookupDataReader));
            Assert.IsNull(received);
        }
コード例 #6
0
        public void TestInitialize()
        {
            _participant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);
            Assert.IsNotNull(_participant);
            _participant.BindRtpsUdpTransportConfig();

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

            Assert.AreEqual(ReturnCode.Ok, result);

            _topic = _participant.CreateTopic(TestContext.TestName, typeName);
            Assert.IsNotNull(_topic);
            Assert.IsNull(_topic.Listener);
            Assert.AreEqual(TestContext.TestName, _topic.Name);
            Assert.AreEqual(typeName, _topic.TypeName);

            _subscriber = _participant.CreateSubscriber();
            Assert.IsNotNull(_subscriber);

            _publisher = _participant.CreatePublisher();
            Assert.IsNotNull(_publisher);

            _writer = _publisher.CreateDataWriter(_topic);
            Assert.IsNotNull(_writer);
            _dataWriter = new TestStructDataWriter(_writer);

            DataReaderQos qos = new DataReaderQos();

            qos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            _reader = _subscriber.CreateDataReader(_topic, qos);
            Assert.IsNotNull(_reader);
        }
コード例 #7
0
        public void TestWaitForAcknowledgments()
        {
            // Initialize entities
            DataWriter writer = _publisher.CreateDataWriter(_topic);

            Assert.IsNotNull(writer);
            TestStructDataWriter dataWriter = new TestStructDataWriter(writer);

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReaderQos drQos = new DataReaderQos();

            drQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            DataReader reader = subscriber.CreateDataReader(_topic);

            Assert.IsNotNull(reader);

            // Write some instances and wait for acknowledgments
            for (int i = 0; i < 10; i++)
            {
                ReturnCode result = dataWriter.Write(new TestStruct
                {
                    Id = i,
                });
                Assert.AreEqual(ReturnCode.Ok, result);

                result = dataWriter.WaitForAcknowledgments(new Duration {
                    Seconds = 5
                });
                Assert.AreEqual(ReturnCode.Ok, result);
            }
        }
コード例 #8
0
        /// <summary>
        /// Creates a DomainParticipant, Topic, Subscriber and DataReader<HelloWorld>.
        /// </summary>
        public HelloWorldSubscriber(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 subscriber
            Subscriber subscriber = participant.CreateSubscriber();

            // Create a DataReader, loading QoS profile from USER_QOS_PROFILES.xml.
            reader = subscriber.CreateDataReader(topic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = reader.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 += ProcessData;

            // Create a WaitSet and attach the StatusCondition
            waitset.AttachCondition(statusCondition);
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: diamond2nv/Tesis
        public override void RunExample(string[] args)
        {
            base.RunExample(args);

            DomainParticipantFactory factory = DomainParticipantFactory.GetInstance(Bootstrap.CreateInstance());
            DomainParticipant        dp      = factory.CreateParticipant();

            // Implicitly create TypeSupport and register type:
            Topic <Greeting> tp = dp.CreateTopic <Greeting>("Greetings Topic");

            // Create the publisher
            Publisher pub = dp.CreatePublisher();

            /* DataWriter<Greeting> dw = pub.CreateDataWriter(tp);
             *
             */

            DataWriter <Greeting> dw = pub.CreateDataWriter <Greeting>(tp,
                                                                       pub.GetDefaultDataWriterQos(), null, null);
            // Create the subscriber
            Subscriber sub = dp.CreateSubscriber();
            DataReaderListener <Greeting> ls = new MyListener();
            /*DataReader<Greeting> dr = sub.CreateDataReader(tp);*/

            DataReader <Greeting> dr = sub.CreateDataReader <Greeting>(tp,
                                                                       sub.GetDefaultDataReaderQos(),
                                                                       ls,
                                                                       null);

            /*
             * // Now Publish some piece of data
             * Greeting data = new Greeting("Hello, World with DDS.");
             * Console.WriteLine("Sending data:\"{0}\"", data.Value);
             * dw.Write(data);
             * //and check that the reader has this data
             * dr.WaitForHistoricalData(10, TimeUnit.SECONDS);
             *
             */
            int i = 0;

            // Now Publish some piece of data
            //Greeting data = new Greeting("Hola Mundo"+ i.ToString());


            for (i = 0; i < 1; i++)
            {
                Greeting data = new Greeting("Hola Mundo" + i.ToString());

                Console.WriteLine("Sending data:\"{0}\"", data.Value);
                dw.Write(data);
                dr.WaitForHistoricalData(1500, TimeUnit.MILLISECONDS);
            }


            //and check that the reader has this data
            //dr.WaitForHistoricalData(10000, TimeUnit.SECONDS);

            dp.Close();
        }
コード例 #10
0
        public IMessagingReader CreateReader(string topicName, IMessagingCallback callback)
        {
            DataReader <T> reader = null;

            if (parameters.CftSet && topicName == THROUGHPUT_TOPIC_NAME.Value)
            {
                reader = subscriber.CreateDataReader <T>(
                    CreateCft(
                        topicName,
                        participant.CreateTopic <T>(topicName)),
                    GetReaderQos(topicName));
            }
            else
            {
                // Rti.Config.Logger.Instance.SetVerbosity(Rti.Config.Verbosity.Warning);
                reader = subscriber.CreateDataReader <T>(
                    participant.CreateTopic <T>(topicName),
                    GetReaderQos(topicName));
            }

            if (callback != null)
            {
                reader.DataAvailable += _ =>
                {
                    // This is the equivalent of the On_data_available function.
                    using var samples = reader.Take();
                    foreach (var sample in samples)
                    {
                        if (sample.Info.ValidData)
                        {
                            callback.ProcessMessage(dataTypeHelper.SampleToMessage(sample.Data));
                        }
                    }
                };
                reader.StatusCondition.EnabledStatuses = StatusMask.DataAvailable;
            }
            else
            {
                reader.StatusCondition.EnabledStatuses = StatusMask.None;
            }
            return(new RTIReader <T>(
                       reader,
                       dataTypeHelper.Clone(),
                       parameters));
        }
コード例 #11
0
        public void TestInitialize()
        {
            _participant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);
            Assert.IsNotNull(_participant);
            _participant.BindRtpsUdpTransportConfig();

            AthleteTypeSupport athleteSupport  = new AthleteTypeSupport();
            string             athleteTypeName = athleteSupport.GetTypeName();
            ReturnCode         result          = athleteSupport.RegisterType(_participant, athleteTypeName);

            Assert.AreEqual(ReturnCode.Ok, result);

            _athleteTopic = _participant.CreateTopic("AthleteTopic", athleteTypeName);
            Assert.IsNotNull(_athleteTopic);
            Assert.IsNull(_athleteTopic.Listener);
            Assert.AreEqual("AthleteTopic", _athleteTopic.Name);
            Assert.AreEqual(athleteTypeName, _athleteTopic.TypeName);

            ResultTypeSupport resultSupport  = new ResultTypeSupport();
            string            resultTypeName = resultSupport.GetTypeName();

            result = resultSupport.RegisterType(_participant, resultTypeName);
            Assert.AreEqual(ReturnCode.Ok, result);

            _resultTopic = _participant.CreateTopic("ResultTopic", resultTypeName);
            Assert.IsNotNull(_resultTopic);
            Assert.IsNull(_resultTopic.Listener);
            Assert.AreEqual("ResultTopic", _resultTopic.Name);
            Assert.AreEqual(resultTypeName, _resultTopic.TypeName);

            _subscriber = _participant.CreateSubscriber();
            Assert.IsNotNull(_subscriber);

            _publisher = _participant.CreatePublisher();
            Assert.IsNotNull(_publisher);

            _athleteWriter = _publisher.CreateDataWriter(_athleteTopic);
            Assert.IsNotNull(_athleteWriter);
            _athleteDataWriter = new AthleteDataWriter(_athleteWriter);
            Assert.IsNotNull(_athleteDataWriter);

            _resultWriter = _publisher.CreateDataWriter(_resultTopic);
            Assert.IsNotNull(_resultWriter);
            _resultDataWriter = new ResultDataWriter(_resultWriter);
            Assert.IsNotNull(_resultDataWriter);

            DataReaderQos qos = new DataReaderQos();

            qos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            _reader = _subscriber.CreateDataReader(_athleteTopic, qos);
            Assert.IsNotNull(_reader);
        }
コード例 #12
0
        public void TestGetOfferedDeadlineMissedStatus()
        {
            // Initialize entities
            DataWriterQos qos = new DataWriterQos();

            qos.Deadline.Period = new Duration
            {
                Seconds = 1,
            };
            DataWriter writer = _publisher.CreateDataWriter(_topic, qos);

            Assert.IsNotNull(writer);
            TestStructDataWriter dataWriter = new TestStructDataWriter(writer);

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReader reader = subscriber.CreateDataReader(_topic);

            Assert.IsNotNull(reader);

            // Wait for discovery and write an instance
            bool found = writer.WaitForSubscriptions(1, 1000);

            Assert.IsTrue(found);

            dataWriter.Write(new TestStruct
            {
                Id = 1,
            });

            // After half second deadline should not be lost yet
            System.Threading.Thread.Sleep(500);

            OfferedDeadlineMissedStatus status = default;
            ReturnCode result = writer.GetOfferedDeadlineMissedStatus(ref status);

            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, status.TotalCount);
            Assert.AreEqual(0, status.TotalCountChange);
            Assert.AreEqual(InstanceHandle.HandleNil, status.LastInstanceHandle);

            // After one second and a half one deadline should be lost
            System.Threading.Thread.Sleep(1000);

            result = writer.GetOfferedDeadlineMissedStatus(ref status);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(1, status.TotalCount);
            Assert.AreEqual(1, status.TotalCountChange);
            Assert.AreNotEqual(InstanceHandle.HandleNil, status.LastInstanceHandle);
        }
コード例 #13
0
        public void TestDeleteDataReader()
        {
            // 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(TestDeleteDataReader), typeName);

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

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            Subscriber otherSubscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(otherSubscriber);

            // Create a DataReader and try to delete it with another subscriber
            DataReader datareader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(datareader);
            Assert.AreEqual(subscriber, datareader.Subscriber);
            Assert.IsNull(datareader.GetListener());

            DataReaderQos qos = new DataReaderQos();

            result = datareader.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataReaderQos(qos);

            result = otherSubscriber.DeleteDataReader(datareader);
            Assert.AreEqual(ReturnCode.PreconditionNotMet, result);

            // Delete the datareader with the correct subscriber
            result = subscriber.DeleteDataReader(datareader);
            Assert.AreEqual(ReturnCode.Ok, result);

            // Try to remove it again
            result = subscriber.DeleteDataReader(datareader);
            Assert.AreEqual(ReturnCode.Error, result);

            // Test with null parameter
            result = subscriber.DeleteDataReader(null);
            Assert.AreEqual(ReturnCode.Ok, result);
        }
コード例 #14
0
        /// <summary>
        /// Creates a DomainParticipant, Topic, Subscriber and DataReader<ShapeType>.
        /// </summary>
        public ShapeTypeSubscriber(int domainId, string typeSource = "build")
        {
            participant = DomainParticipantFactory.Instance.CreateParticipant(domainId);

            // Get the ShapeType definition using one of the available options
            DynamicType type = ShapeTypeHelper.GetShapeType(typeSource);

            Topic <DynamicData> topic = participant.CreateTopic("Square", type);

            Subscriber subscriber = participant.CreateSubscriber();

            reader = subscriber.CreateDataReader(topic);
        }
コード例 #15
0
        private void RunExample(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
            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"));

            // 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 <DynamicData> reader = subscriber.CreateDataReader(topic);

            // Obtain the DataReader's Status Condition
            StatusCondition statusCondition = reader.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)
            int samplesRead = 0;

            statusCondition.Triggered += _ => samplesRead += ProcessData(reader);

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

            waitset.AttachCondition(statusCondition);
            while (samplesRead < sampleCount && !shutdownRequested)
            {
                // Dispatch will call the handlers associated to the WaitSet
                // conditions when they activate
                Console.WriteLine("ChocolateTemperature subscriber sleeping for 4 sec...");
                waitset.Dispatch(Duration.FromSeconds(4));
            }
        }
コード例 #16
0
        public void TestInitialize()
        {
            _participant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);
            Assert.IsNotNull(_participant);
            _participant.BindRtpsUdpTransportConfig();

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

            Assert.AreEqual(ReturnCode.Ok, result);

            _topic = _participant.CreateTopic(TestContext.TestName, typeName);
            Assert.IsNotNull(_topic);
            Assert.IsNull(_topic.GetListener());
            Assert.AreEqual(TestContext.TestName, _topic.Name);
            Assert.AreEqual(typeName, _topic.TypeName);

            SubscriberQos sQos = new SubscriberQos();

            sQos.EntityFactory.AutoenableCreatedEntities = false;
            sQos.Presentation.OrderedAccess  = true;
            sQos.Presentation.CoherentAccess = true;
            sQos.Presentation.AccessScope    = PresentationQosPolicyAccessScopeKind.InstancePresentationQos;
            _subscriber = _participant.CreateSubscriber(sQos);
            Assert.IsNotNull(_subscriber);

            PublisherQos pQos = new PublisherQos();

            pQos.EntityFactory.AutoenableCreatedEntities = false;
            pQos.Presentation.OrderedAccess  = true;
            pQos.Presentation.CoherentAccess = true;
            pQos.Presentation.AccessScope    = PresentationQosPolicyAccessScopeKind.InstancePresentationQos;
            _publisher = _participant.CreatePublisher(pQos);
            Assert.IsNotNull(_publisher);

            _listener = new MyDataWriterListener();
            _writer   = _publisher.CreateDataWriter(_topic, _listener);
            Assert.IsNotNull(_writer);
            _dataWriter = new TestStructDataWriter(_writer);

            DataReaderQos qos = new DataReaderQos();

            qos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            _reader = _subscriber.CreateDataReader(_topic, qos);
            Assert.IsNotNull(_reader);
        }
コード例 #17
0
        public void TestGetOfferedIncompatibleQosStatus()
        {
            // Initialize entities
            DataWriterQos qos = new DataWriterQos();

            qos.Reliability.Kind = ReliabilityQosPolicyKind.BestEffortReliabilityQos;
            DataWriter writer = _publisher.CreateDataWriter(_topic, qos);

            Assert.IsNotNull(writer);

            // If not matched readers should retur the default status
            OfferedIncompatibleQosStatus status = default;
            ReturnCode result = writer.GetOfferedIncompatibleQosStatus(ref status);

            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, status.TotalCount);
            Assert.AreEqual(0, status.TotalCountChange);
            Assert.IsNotNull(status.Policies);
            Assert.AreEqual(0, status.Policies.Count);
            Assert.AreEqual(0, status.LastPolicyId);

            // Create a not compatible reader
            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReaderQos drQos = new DataReaderQos();

            drQos.Reliability.Kind = ReliabilityQosPolicyKind.ReliableReliabilityQos;
            DataReader reader = subscriber.CreateDataReader(_topic, drQos);

            Assert.IsNotNull(reader);

            // Wait for discovery and check the status
            System.Threading.Thread.Sleep(100);

            status = default;
            result = writer.GetOfferedIncompatibleQosStatus(ref status);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(1, status.TotalCount);
            Assert.AreEqual(1, status.TotalCountChange);
            Assert.AreEqual(11, status.LastPolicyId);
            Assert.IsNotNull(status.Policies);
            Assert.AreEqual(1, status.Policies.Count);
            Assert.AreEqual(1, status.Policies.First().Count);
            Assert.AreEqual(11, status.Policies.First().PolicyId);
        }
コード例 #18
0
        private static void TestOnInconsistentTopic()
        {
            DomainParticipantFactory dpf         = ParticipantService.Instance.GetDomainParticipantFactory();
            DomainParticipant        participant = dpf.CreateParticipant(RTPS_DOMAIN);

            if (participant == null)
            {
                throw new ApplicationException("Failed to create the participant.");
            }

            BindRtpsUdpTransportConfig(participant);

            Subscriber subscriber = participant.CreateSubscriber();

            if (subscriber == null)
            {
                throw new ApplicationException("Failed to create the subscriber.");
            }

            AthleteTypeSupport support  = new AthleteTypeSupport();
            string             typeName = support.GetTypeName();
            ReturnCode         result   = support.RegisterType(participant, typeName);

            if (result != ReturnCode.Ok)
            {
                throw new ApplicationException("Failed to register the type." + result.ToString());
            }

            Topic topic = participant.CreateTopic(nameof(TestOnInconsistentTopic), typeName);

            if (topic == null)
            {
                throw new ApplicationException("Failed to create the topic.");
            }

            DataReader reader = subscriber.CreateDataReader(topic);

            if (reader == null)
            {
                throw new ApplicationException("Failed to create the reader.");
            }

            while (true)
            {
                System.Threading.Thread.Sleep(100);
            }
        }
コード例 #19
0
        private static void TestOnPublicationLostDisconnected()
        {
            DomainParticipantFactory dpf         = ParticipantService.Instance.GetDomainParticipantFactory();
            DomainParticipant        participant = dpf.CreateParticipant(INFOREPO_DOMAIN);

            if (participant == null)
            {
                throw new InvalidOperationException("Failed to create the participant.");
            }
            BindTcpTransportConfig(participant);

            Subscriber subscriber = participant.CreateSubscriber();

            if (subscriber == null)
            {
                throw new InvalidOperationException("Failed to create the subscriber.");
            }

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

            if (result != ReturnCode.Ok)
            {
                throw new InvalidOperationException("Failed to register the type." + result.ToString());
            }

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

            if (topic == null)
            {
                throw new InvalidOperationException("Failed to create the topic.");
            }

            DataReader reader = subscriber.CreateDataReader(topic);

            if (reader == null)
            {
                throw new InvalidOperationException("Failed to create the reader.");
            }

            while (true)
            {
                System.Threading.Thread.Sleep(100);
            }
        }
コード例 #20
0
        /// <summary>
        /// Runs the subscriber example.
        /// </summary>
        public static async Task RunSubscriber(
            int domainId,
            int sampleCount,
            CancellationToken cancellationToken)
        {
            // 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 cfc");

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

            // Create a DataReader with the default QoS profile defined in
            // USER_QOS_PROFILES.xml
            DataReader <HelloWorld> reader = subscriber.CreateDataReader(topic);

            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;
                    }
                }
            }
        }
コード例 #21
0
        /// <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);
        }
コード例 #22
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);
        }
コード例 #23
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++;
            }
        }
コード例 #24
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));
            }
        }
コード例 #25
0
        /// <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;
        }
コード例 #26
0
        public void TestSetDefaultDataReaderQos()
        {
            // 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(TestSetDefaultDataReaderQos), typeName);

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

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            // Creates a non-default QoS, set it an check it
            DataReaderQos qos = TestHelper.CreateNonDefaultDataReaderQos();

            result = subscriber.SetDefaultDataReaderQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);

            qos    = new DataReaderQos();
            result = subscriber.GetDefaultDataReaderQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataReaderQos(qos);

            DataReader reader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(reader);

            qos    = new DataReaderQos();
            result = reader.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataReaderQos(qos);

            // Put back the default QoS and check it
            qos    = new DataReaderQos();
            result = subscriber.SetDefaultDataReaderQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);

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

            DataReader otherReader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(otherReader);

            qos    = TestHelper.CreateNonDefaultDataReaderQos();
            result = otherReader.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataReaderQos(qos);

            // Create an inconsistent QoS and try to set it
            qos = TestHelper.CreateNonDefaultDataReaderQos();
            qos.TimeBasedFilter.MinimumSeparation = new Duration
            {
                Seconds     = 5,
                NanoSeconds = 5
            };
            result = subscriber.SetDefaultDataReaderQos(qos);
            Assert.AreEqual(ReturnCode.InconsistentPolicy, result);

            // Test SetDefaultDataReaderQos with null parametr
            result = subscriber.SetDefaultDataReaderQos(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);
        }
コード例 #27
0
        public void TestCreateDataReaderr()
        {
            // 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(TestCreateDataReaderr), typeName);

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

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            // Test simplest overload
            DataReader datareader1 = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(datareader1);
            Assert.AreEqual(subscriber, datareader1.Subscriber);
            Assert.IsNull(datareader1.GetListener());

            DataReaderQos qos = new DataReaderQos();

            result = datareader1.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataReaderQos(qos);

            // Test overload with QoS parameter
            qos = TestHelper.CreateNonDefaultDataReaderQos();
            DataReader datareader2 = subscriber.CreateDataReader(topic, qos);

            Assert.IsNotNull(datareader2);
            Assert.AreEqual(subscriber, datareader2.Subscriber);
            Assert.IsNull(datareader2.GetListener());

            qos    = new DataReaderQos();
            result = datareader2.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataReaderQos(qos);

            // Test overload with listener parameter
            MyDataReaderListener listener    = new MyDataReaderListener();
            DataReader           datareader3 = subscriber.CreateDataReader(topic, listener);

            Assert.IsNotNull(datareader3);
            Assert.AreEqual(subscriber, datareader3.Subscriber);
            MyDataReaderListener received = (MyDataReaderListener)datareader3.GetListener();

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

            qos    = new DataReaderQos();
            result = datareader3.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataReaderQos(qos);

            // Test overload with listener and StatusMask parameters
            listener = new MyDataReaderListener();
            DataReader datareader4 = subscriber.CreateDataReader(topic, listener, StatusMask.AllStatusMask);

            Assert.IsNotNull(datareader4);
            Assert.AreEqual(subscriber, datareader4.Subscriber);
            received = (MyDataReaderListener)datareader4.GetListener();
            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataReaderQos();
            result = datareader4.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestDefaultDataReaderQos(qos);

            // Test overload with QoS and listener parameters
            qos      = TestHelper.CreateNonDefaultDataReaderQos();
            listener = new MyDataReaderListener();
            DataReader datareader5 = subscriber.CreateDataReader(topic, qos, listener);

            Assert.IsNotNull(datareader5);
            Assert.AreEqual(subscriber, datareader5.Subscriber);
            received = (MyDataReaderListener)datareader5.GetListener();
            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataReaderQos();
            result = datareader5.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataReaderQos(qos);

            // Test full call overload
            qos      = TestHelper.CreateNonDefaultDataReaderQos();
            listener = new MyDataReaderListener();
            DataReader datareader6 = subscriber.CreateDataReader(topic, qos, listener, StatusMask.AllStatusMask);

            Assert.IsNotNull(datareader6);
            Assert.AreEqual(subscriber, datareader6.Subscriber);
            received = (MyDataReaderListener)datareader6.GetListener();
            Assert.IsNotNull(received);
            Assert.AreEqual(listener, received);

            qos    = new DataReaderQos();
            result = datareader6.GetQos(qos);
            Assert.AreEqual(ReturnCode.Ok, result);
            TestHelper.TestNonDefaultDataReaderQos(qos);
        }
コード例 #28
0
        public void TestBeginEndAccess()
        {
            // OpenDDS Issue: Coherent sets for PRESENTATION QoS not Currently implemented on RTPS.
            // Just prepare the unit test for the moment.

            // 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(TestNotifyDataReaders), typeName);

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

            Topic otherTopic = _participant.CreateTopic("Other" + nameof(TestNotifyDataReaders), typeName);

            Assert.IsNotNull(otherTopic);
            Assert.IsNull(otherTopic.GetListener());
            Assert.AreEqual("Other" + nameof(TestNotifyDataReaders), otherTopic.Name);
            Assert.AreEqual(typeName, otherTopic.TypeName);

            PublisherQos pubQos = new PublisherQos();

            pubQos.Presentation.AccessScope    = PresentationQosPolicyAccessScopeKind.GroupPresentationQos;
            pubQos.Presentation.CoherentAccess = true;
            pubQos.Presentation.OrderedAccess  = true;
            Publisher publisher = _participant.CreatePublisher(pubQos);

            Assert.IsNotNull(publisher);

            DataWriter writer = publisher.CreateDataWriter(topic);

            Assert.IsNotNull(writer);
            TestStructDataWriter dataWriter = new TestStructDataWriter(writer);

            DataWriter otherWriter = publisher.CreateDataWriter(otherTopic);

            Assert.IsNotNull(otherWriter);
            TestStructDataWriter otherDataWriter = new TestStructDataWriter(otherWriter);

            SubscriberQos subQos = new SubscriberQos();

            subQos.Presentation.AccessScope    = PresentationQosPolicyAccessScopeKind.GroupPresentationQos;
            subQos.Presentation.CoherentAccess = true;
            subQos.Presentation.OrderedAccess  = true;
            MySubscriberListener listener = new MySubscriberListener();

            listener.DataOnReaders += (sub) =>
            {
                result = sub.BeginAccess();
                Assert.AreEqual(ReturnCode.Ok, result);

                List <DataReader> list = new List <DataReader>();
                result = sub.GetDataReaders(list);

                // Here we should check that we received two DataReader
                // read the data of each one and confirm tha the group coherent access
                // is working as expected.

                result = sub.EndAccess();
                Assert.AreEqual(ReturnCode.Ok, result);
            };

            Subscriber subscriber = _participant.CreateSubscriber(subQos, listener);

            Assert.IsNotNull(subscriber);

            DataReader reader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(reader);
            TestStructDataReader dataReader = new TestStructDataReader(reader);

            DataReader otherReader = subscriber.CreateDataReader(otherTopic);

            Assert.IsNotNull(otherReader);
            TestStructDataReader otherDataReader = new TestStructDataReader(otherReader);

            // Call EndAccess without calling first BeginAccess
            result = subscriber.EndAccess();
            Assert.AreEqual(ReturnCode.PreconditionNotMet, result);

            // Publish a samples in both topics
            result = publisher.BeginCoherentChanges();
            Assert.AreEqual(ReturnCode.Ok, result);

            result = dataWriter.Write(new TestStruct
            {
                Id = 1
            });
            Assert.AreEqual(ReturnCode.Ok, result);

            result = otherDataWriter.Write(new TestStruct
            {
                Id = 1
            });
            Assert.AreEqual(ReturnCode.Ok, result);

            result = publisher.EndCoherentChanges();
            Assert.AreEqual(ReturnCode.Ok, result);

            // Give some time to the subscriber to process the messages
            System.Threading.Thread.Sleep(500);
        }
コード例 #29
0
        public void TestGetDataReaders()
        {
            // 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(TestNotifyDataReaders), typeName);

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

            Topic otherTopic = _participant.CreateTopic("Other" + nameof(TestNotifyDataReaders), typeName);

            Assert.IsNotNull(otherTopic);
            Assert.IsNull(otherTopic.GetListener());
            Assert.AreEqual("Other" + nameof(TestNotifyDataReaders), otherTopic.Name);
            Assert.AreEqual(typeName, otherTopic.TypeName);

            Publisher publisher = _participant.CreatePublisher();

            Assert.IsNotNull(publisher);

            DataWriter writer = publisher.CreateDataWriter(topic);

            Assert.IsNotNull(writer);
            TestStructDataWriter dataWriter = new TestStructDataWriter(writer);

            DataWriter otherWriter = publisher.CreateDataWriter(otherTopic);

            Assert.IsNotNull(otherWriter);
            TestStructDataWriter otherDataWriter = new TestStructDataWriter(otherWriter);

            Subscriber subscriber = _participant.CreateSubscriber();

            Assert.IsNotNull(subscriber);

            DataReader reader = subscriber.CreateDataReader(topic);

            Assert.IsNotNull(reader);
            TestStructDataReader dataReader = new TestStructDataReader(reader);

            DataReader otherReader = subscriber.CreateDataReader(otherTopic);

            Assert.IsNotNull(otherReader);
            TestStructDataReader otherDataReader = new TestStructDataReader(otherReader);

            // Check that the GetDataReaders without sending any sample
            List <DataReader> list = new List <DataReader>();

            result = subscriber.GetDataReaders(list);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, list.Count);

            // Publish in the topic and check again
            result = dataWriter.Write(new TestStruct
            {
                Id = 1
            });
            Assert.AreEqual(ReturnCode.Ok, result);

            System.Threading.Thread.Sleep(100);

            result = subscriber.GetDataReaders(list);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(1, list.Count);

            // Publish in the otherTopic and check again
            result = otherDataWriter.Write(new TestStruct
            {
                Id = 1
            });
            Assert.AreEqual(ReturnCode.Ok, result);

            System.Threading.Thread.Sleep(100);

            result = subscriber.GetDataReaders(list, SampleStateKind.NotReadSampleState | SampleStateKind.ReadSampleState, ViewStateMask.AnyViewState, InstanceStateMask.AnyInstanceState);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(2, list.Count);

            // Take from both DataReaders and check again
            List <TestStruct> received    = new List <TestStruct>();
            List <SampleInfo> sampleInfos = new List <SampleInfo>();

            result = dataReader.Take(received, sampleInfos);
            Assert.AreEqual(ReturnCode.Ok, result);

            result = otherDataReader.Take(received, sampleInfos);
            Assert.AreEqual(ReturnCode.Ok, result);

            result = subscriber.GetDataReaders(list);
            Assert.AreEqual(ReturnCode.Ok, result);
            Assert.AreEqual(0, list.Count);

            // Test GetDataReaders with null parameter
            result = subscriber.GetDataReaders(null);
            Assert.AreEqual(ReturnCode.BadParameter, result);
        }
コード例 #30
0
        public void TestNotifyDataReaders()
        {
            // 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(TestNotifyDataReaders), typeName);

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

            Publisher publisher = _participant.CreatePublisher();

            Assert.IsNotNull(publisher);

            DataWriter writer = publisher.CreateDataWriter(topic);

            Assert.IsNotNull(writer);
            TestStructDataWriter dataWriter = new TestStructDataWriter(writer);

            int subscriberReceived = 0;
            int readerReceived     = 0;

            // Create the Subscriber and the DataReader with the corresponding listeners
            MySubscriberListener subListener = new MySubscriberListener();

            subListener.DataOnReaders += (sub) =>
            {
                subscriberReceived++;
                if (subscriberReceived % 2 == 0)
                {
                    sub.NotifyDataReaders();
                }
            };
            Subscriber subscriber = _participant.CreateSubscriber(subListener);

            Assert.IsNotNull(subscriber);

            MyDataReaderListener readListener = new MyDataReaderListener();

            readListener.DataAvailable += (read) =>
            {
                readerReceived++;
            };
            DataReader reader = subscriber.CreateDataReader(topic, readListener);

            Assert.IsNotNull(reader);

            System.Threading.Thread.Sleep(100);

            // Publish instances
            for (int i = 0; i < 10; i++)
            {
                dataWriter.Write(new TestStruct
                {
                    Id        = i,
                    ShortType = (short)i
                });

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

            System.Threading.Thread.Sleep(100);

            // Check the received instances
            Assert.AreEqual(10, subscriberReceived);
            Assert.AreEqual(5, readerReceived);
        }