예제 #1
0
		public DomainParticipantTransportSource(DomainParticipant participant, string senderTopic, string receiverTopic)
		{
			_participant = participant;

			var senderTopicQos = new TopicQos();
			participant.get_default_topic_qos(senderTopicQos);

			var receiverTopicQos = new TopicQos();
			participant.get_default_topic_qos(receiverTopicQos);

			_sender = participant.create_topic(senderTopic, BytesTypeSupport.TYPENAME, senderTopicQos, null, StatusMask.STATUS_MASK_NONE);
			_receiver = participant.create_topic(receiverTopic, BytesTypeSupport.TYPENAME, receiverTopicQos, null, StatusMask.STATUS_MASK_NONE);

			var writerQos = new DataWriterQos();
			//writerQos.publish_mode.kind = PublishModeQosPolicyKind.ASYNCHRONOUS_PUBLISH_MODE_QOS;
			writerQos.publish_mode.flow_controller_name = FlowController.FIXED_RATE_FLOW_CONTROLLER_NAME;

			participant.get_default_datawriter_qos(writerQos);
			
			var readerQos = new DataReaderQos();
			participant.get_default_datareader_qos(readerQos);

			_writer = participant.create_datawriter(_sender, writerQos, null, StatusMask.STATUS_MASK_NONE);
			_reader = participant.create_datareader(_receiver, readerQos, this, StatusMask.STATUS_MASK_ALL);
		}
예제 #2
0
        public void TestRead()
        {
            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    reader = subscriber.CreateDataReader(topic, drQos);

            Assert.IsNotNull(reader);

            int count = 200;

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

            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);
        }
예제 #3
0
        /// <summary>
        /// This operation creates a new IDomainParticipant which will join the domain
        /// identified by domainId, with the desired DomainParticipantQos and attaches
        /// the specified IDomainParticipantListener to it and uses the given communication
        /// StatusKind mask.
        /// </summary>
        /// <remarks>
        /// <i><b>Identifying the Domain</b></i><br>
        /// The IDomainParticipant will attach to the Domain that is specified by the
        /// domainId parameter. This parameter consists of an integer specified in the Id tag
        /// in the configuration file. Note that to make multiple connections to a Domain (create
        /// multiple Participants for the same Domain) within a single process, all of the
        /// Participants must use the same identification (i.e. all use the same domain Id).
        ///
        /// The constant DDS.DomainId.Default can be used for this parameter. If this is done
        /// the value of Id tag from the configuration file specified by the environment variable
        /// called OSPL_URI will be used.
        ///
        /// It is recommended to use this domain Id in conjunction with the OSPL_URI
        /// environment variable instead of hard-coding a domain Id into your application,
        /// since this gives you much more flexibility in the deployment phase of your product.<br>
        /// See also Section 1.3.2.1, The OSPL_URI environment variable, in the Deployment
        /// Guide.
        ///
        /// <i><b>Communication Status</b></i><br>
        /// For each communication status, the StatusChangedFlag flag is initially set to
        /// false. It becomes true whenever that communication status changes. For each
        /// communication status activated in the mask , the associated
        /// IDomainParticipantListener operation is invoked and the communication
        /// status is reset to false , as the listener implicitly accesses the status which is passed
        /// as a parameter to that operation. The fact that the status is reset prior to calling the
        /// listener means that if the application calls the Get<status_name>Status from
        /// inside the listener it will see the status already reset.
        ///
        /// The following statuses are applicable to the IDomainParticipant
        /// - DDS.StatusKind InconsistentTopic (propagated)
        /// - DDS.StatusKind OfferedDeadlineMissed (propagated)
        /// - DDS.StatusKind RequestedDeadlineMissed (propagated)
        /// - DDS.StatusKind OfferedIncompatibleQos (propagated)
        /// - DDS.StatusKind RequestedIncompatibleQos (propagated)
        /// - DDS.StatusKind SampleLost (propagated)
        /// - DDS.StatusKind SampleRejected (propagated)
        /// - DDS.StatusKind DataOnReaders (propagated)
        /// - DDS.StatusKind DataAvailable (propagated)
        /// - DDS.StatusKind LivelinessLost (propagated)
        /// - DDS.StatusKind LivelinessChanged (propagated)
        /// - DDS.StatusKind PublicationMatched (propagated)
        /// - DDS.StatusKind SubscriptionMatched (propagated)
        ///
        /// Be aware that the PublicationMatched and SubscriptionMatched
        /// statuses are not applicable when the infrastructure does not have the
        /// information available to determine connectivity. This is the case when OpenSplice
        /// is configured not to maintain discovery information in the Networking Service. (See
        /// the description for the NetworkingService/Discovery/enabled property in
        /// the Deployment Manual for more information about this subject.) In this case the
        /// operation will return NULL.
        ///
        /// Status bits are declared as a constant and can be used by the application in an OR
        /// operation to create a tailored mask. The special constant 0 can
        /// be used to indicate that the created entity should not respond to any of its available
        /// statuses. The DDS will therefore attempt to propagate these statuses to its factory.
        ///
        /// <i><b>Status Propagation</b></i><br>
        /// The Data Distribution Service will trigger the most specific and relevant Listener.<br>
        /// In other words, in case a communication status is also activated on the Listener of
        /// a contained entity, the Listener on that contained entity is invoked instead of the
        /// IDomainParticipantListener. This means that a status change on a contained
        /// entity only invokes the IDomainParticipantListener if the contained entity
        /// itself does not handle the trigger event generated by the status change.
        ///
        /// The statuses DataOnReaders and DataAvailable are
        /// “Read Communication Statuses” and are an exception to all other plain
        /// communication statuses: they have no corresponding status structure that can be
        /// obtained with a Get<status_name>Status operation and they are mutually
        /// exclusive. When new information becomes available to a IDataReader, the Data
        /// Distribution Service will first look in an attached and activated
        /// ISubscriberListener or IDomainParticipantListener (in that order) for the
        /// DataOnReaders. In case the DataOnReaders can not be
        /// handled, the Data Distribution Service will look in an attached and activated
        /// IDataReaderListener, ISubscriberListener or IDomainParticipantListener for
        /// the DataAvailable (in that order).
        /// </remarks>
        /// @param domainId The ID of the Domain to which the IDomainParticipant is joined.
        ///                 This should be the ID as specified in the configuration file.
        /// @param qos      a DomainParticipantQos for the new IDomainParticipant. When
        ///                 this set of QosPolicy settings is inconsistent, no
        ///                 IDomainParticipant is created.
        /// @param listener A IDomainParticipantListener instance which will be attached to
        ///                 the new IDomainParticipant. It is permitted to use null as the
        ///                 value of the listener: this behaves as a IDomainParticipantListener
        ///                 whose operations perform no action.
        /// @param mask     A bit-mask in which each bit enables the invocation of the
        ///                 IDomainParticipantListener for a certain status.
        /// @return The newly created IDomainParticipant. In case of an error a null is returned.
        public IDomainParticipant CreateParticipant(
            DomainId domainId,
            DomainParticipantQos qos,
            IDomainParticipantListener listener,
            StatusKind mask)
        {
            DomainParticipant participant = null;
            ReturnCode        result;

            ReportStack.Start();
            result = QosManager.checkQos(qos);
            if (result == DDS.ReturnCode.Ok)
            {
                if (domainId != DDS.DomainId.Invalid)
                {
                    lock (singleton_lock)
                    {
                        participant = new OpenSplice.DomainParticipant();
                        result      = participant.init(domainId, qos);
                        if (result == ReturnCode.Ok)
                        {
                            result = participant.SetListener(listener, mask);
                        }
                        else
                        {
                            participant = null;
                        }

                        if (result == ReturnCode.Ok)
                        {
                            participantList.Add(participant);
                            if (myQos.EntityFactory.AutoenableCreatedEntities)
                            {
                                result = participant.Enable();
                            }
                        }
                    }
                }
                else
                {
                    ReportStack.Report(DDS.ReturnCode.BadParameter,
                                       "DomainParticipant is using an invalid domain identifier (" + domainId + ").");
                }
            }

            if (result != ReturnCode.Ok && participant != null)
            {
                // Ignore result because we prefer the original error.
                DeleteParticipant(participant);
                participant = null;
            }

            ReportStack.Flush(null, result != ReturnCode.Ok);
            return(participant);
        }
예제 #4
0
        public void TestTakeNextSample()
        {
            PublicationBuiltinTopicData data = default;
            SampleInfo infos = new SampleInfo();
            ReturnCode ret   = _dr.TakeNextSample(ref data, infos);

            Assert.AreEqual(ReturnCode.NoData, 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);
                ret = _dr.TakeNextSample(ref data, infos);
                count--;
            }

            Assert.AreEqual(ReturnCode.Ok, ret);
            TestHelper.TestNonDefaultPublicationData(data);

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

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
        /// <summary>
        /// The Main function runs the Qos printing example.
        /// </summary>
        public static void Main(string[] args)
        {
            using DomainParticipant participant = DomainParticipantFactory.Instance.CreateParticipant(0);
            Topic <HelloWorld> topic     = participant.CreateTopic <HelloWorld>("Example QosPrintingExample_HelloWorld");
            Publisher          publisher = participant.CreatePublisher();

            // In order to demonstrate a possible use-case for the Qos printing APIs
            // we create a DataWriter which is a combination of policies set in
            // the XML file, and of policies set in code.
            DataWriterQos writerQos = QosProvider.Default.GetDataWriterQos()
                                      .WithReliability(policy => policy.Kind = ReliabilityKind.BestEffort);
            DataWriter <HelloWorld> writer = publisher.CreateDataWriter(topic, writerQos);


            // The Qos we have obtained from the XML file inherits from the
            // Generic.StrictReliable built-in profile. It also explicitly sets
            // the Durability Qos policy. We have also explicitly set (in code)
            // the Reliability Qos (overriding the ReliabilityKind set in the
            // built-in profile). Using the Qos printing APIs we can check what
            // is the final Qos in use by an entity.
            Console.WriteLine("Printing DataWriterQos to stdout");
            Console.WriteLine("Press enter to continue");
            Console.ReadLine();
            Console.WriteLine(writer.Qos);

            // The output can be configured using QosPrintFormat
            QosPrintFormat format = new QosPrintFormat
            {
                Indent       = 1,
                IsStandalone = true
            };

            Console.WriteLine("Printing formatted DataWriterQos to stdout");
            Console.WriteLine("Press enter to continue");
            Console.ReadLine();
            Console.WriteLine(writer.Qos.ToString(format));

            // By default, only the differences with respect to the documented
            // QoS default (the default values as stated in the API reference)
            // are printed. This behavior can be overridden by passing another
            // QoS object to use as the baseQos to ToString.
            Console.WriteLine("Printing DataWriterQos differences with respect to \"BuiltinQosLib::Generic.StrictReliable\" to stdout");
            Console.WriteLine("Press enter to continue");
            Console.ReadLine();
            Console.WriteLine(writer.Qos.ToString(
                                  baseQos: QosProvider.Default.GetDataWriterQos("BuiltinQosLib::Generic.StrictReliable")));

            // To print all the Qos policies (not just the differences), call
            // ToString with sentinel QosPrintAll.Value
            Console.WriteLine("Printing entire DataWriterQos object to stdout");
            Console.WriteLine("Press enter to continue");
            Console.ReadLine();
            Console.WriteLine(writer.Qos.ToString(baseQos: QosPrintAll.Value));
        }
예제 #6
0
        public void TestLookupInstance()
        {
            SubscriptionBuiltinTopicData data = default;
            SampleInfo info = new SampleInfo();

            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;
            ReturnCode 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);
            TestHelper.TestNonDefaultSubscriptionData(data);

            // Lookup for an existing instance
            var handle = _dr.LookupInstance(data);

            Assert.AreNotEqual(InstanceHandle.HandleNil, handle);

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

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
예제 #7
0
        /// <summary>
        /// Main function, receiving structured command-line arguments
        /// via the System.Console.DragonFruit package.
        /// For example: dotnet run -- --domain-id 54 --sample-count 5
        /// </summary>
        /// <param name="domainId">The domain ID to create the DomainParticipant</param>
        /// <param name="sampleCount">The number of data samples to receive before exiting</param>
        public static void Main(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. Create dynamically-typed
            // Topic named "HelloWorld Topic" with the type definition of
            // "HelloWorld" in hello_world.xml. To get the type we use a QosProvider
            var provider = new QosProvider("../hello_world.xml");
            Topic <DynamicData> topic = participant.CreateTopic(
                "Example HelloWorld",
                provider.GetType("HelloWorld"));

            // 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)
            {
                // Dispatch will call the handlers associated to the WaitSet
                // conditions when they activate
                Console.WriteLine("HelloWorld subscriber sleeping for 4 sec...");
                waitset.Dispatch(Duration.FromSeconds(4));
            }
        }
        public void TestTakeInstance()
        {
            List <TopicBuiltinTopicData> data  = new List <TopicBuiltinTopicData>();
            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.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.ReadNextInstance(data, infos, InstanceHandle.HandleNil);
            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());

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

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
예제 #9
0
        public void TestLookupInstance()
        {
            ReturnCode        ret;
            DomainParticipant otherParticipant = null;
            Topic             topic            = null;

            try
            {
                TopicBuiltinTopicData data = default;
                SampleInfo            info = new SampleInfo();

                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.ReadNextSample(ref data, info);
                    count--;
                }

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

                // Lookup for an existing instance
                var handle = _dr.LookupInstance(data);
                Assert.AreNotEqual(InstanceHandle.HandleNil, handle);
            }
            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>
        /// Creates a DomainParticipant, Topic, Publisher and DataWriters<Temperature>.
        /// </summary>
        public PublisherApplication(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 Publisher
            PublisherQos publisherQos = null;

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

            publisher = participant.CreatePublisher(publisherQos);

            // Create a DataWriter for each topic
            DataWriterQos writerQos = null;

            if (useXmlQos)
            {
                // Retrieve the DataWriter QoS, from USER_QOS_PROFILES.xml
                writerQos = QosProvider.Default.GetDataWriterQos();
            }
            else
            {
                // Set the DataWriter QoS programatically, to the same effect
                writerQos = publisher.DefaultDataWriterQos
                            .WithReliability(policy => policy.Kind = ReliabilityKind.Reliable)
                            .WithHistory(policy => policy.Kind     = HistoryKind.KeepAll);
            }

            alarmWriter       = publisher.CreateDataWriter(alarmTopic, writerQos);
            heartRateWriter   = publisher.CreateDataWriter(heartRateTopic, writerQos);
            temperatureWriter = publisher.CreateDataWriter(temperatureTopic, writerQos);
        }
예제 #11
0
        public bool Initialize(Parameters parameters)
        {
            this.parameters = parameters;
            if (!ParseConfig())
            {
                return(false);
            }

            string baseProfile = parameters.QosLibrary + "::BaseProfileQos";
            string pingProfile = parameters.QosLibrary + "::ThroughputQos";
            string pongProfile = parameters.QosLibrary + "::ThroughputQos";

            var qosProvider    = new QosProvider(parameters.QosFile);
            var participantQos = GetParticipantQos(baseProfile);

            if (parameters.LatencyTest)
            {
                pongSemaphore = new Semaphore(0, 1);
            }

            if (SecureUseSecure)
            {
                // validate arguments
                if (!ValidateSecureArgs())
                {
                    Console.Error.WriteLine("Failure validating arguments");
                    return(false);
                }
                ConfigureSecurePlugin(ref participantQos);
            }

            participant = DomainParticipantFactory.Instance.CreateParticipant(parameters.Domain, participantQos);
            if (participant == null)
            {
                Console.Error.Write("Problem creating participant.\n");
                return(false);
            }

            publisher = participant.CreatePublisher(qosProvider.GetPublisherQos(pingProfile));
            if (publisher == null)
            {
                Console.Error.WriteLine("Problem creating publisher.");
                return(false);
            }
            subscriber = participant.CreateSubscriber(qosProvider.GetSubscriberQos(pongProfile));
            if (subscriber == null)
            {
                Console.Error.WriteLine("Problem creating subscriber.");
                return(false);
            }
            return(true);
        }
예제 #12
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);
        }
예제 #13
0
        public void TestInitialize()
        {
            _participant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN);
            Assert.IsNotNull(_participant);
            _participant.BindRtpsUdpTransportConfig();
            _subscriber = _participant.GetBuiltinSubscriber();
            Assert.IsNotNull(_subscriber);

            _dataReader = _subscriber.LookupDataReader(SubscriptionBuiltinTopicDataDataReader.BUILT_IN_SUBSCRIPTION_TOPIC);
            Assert.IsNotNull(_dataReader);

            _dr = new SubscriptionBuiltinTopicDataDataReader(_dataReader);
        }
예제 #14
0
        /// <summary>
        /// Creates a DomainParticipant, Topic, Publisher and DataWriter.
        /// </summary>
        public ShapeTypePublisher(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);

            Publisher publisher = participant.CreatePublisher();

            writer = publisher.CreateDataWriter(topic);
        }
        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
        private static void BindRtpsUdpTransportConfig(DomainParticipant participant)
        {
            long   ticks      = DateTime.Now.Ticks;
            string configName = "openddsharp_rtps_interop_" + ticks.ToString();
            string instName   = "internal_openddsharp_rtps_transport_" + ticks.ToString();

            TransportConfig config = TransportRegistry.Instance.CreateConfig(configName);
            TransportInst   inst   = TransportRegistry.Instance.CreateInst(instName, "rtps_udp");
            RtpsUdpInst     rui    = new RtpsUdpInst(inst);

            config.Insert(inst);

            TransportRegistry.Instance.BindConfig(configName, participant);
        }
        public void TestInitialize()
        {
            _participant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.INFOREPO_DOMAIN);
            Assert.IsNotNull(_participant);
            _participant.BindTcpTransportConfig();

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

            _dataReader = _subscriber.LookupDataReader(TopicBuiltinTopicDataDataReader.BUILT_IN_TOPIC_TOPIC);
            Assert.IsNotNull(_dataReader);

            _dr = new TopicBuiltinTopicDataDataReader(_dataReader);
        }
예제 #18
0
        private static void BindRtpsUdpTransportConfig(DomainParticipant participant)
        {
            string guid       = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            string configName = "openddsharp_rtps_interop_" + guid;
            string instName   = "internal_openddsharp_rtps_transport_" + guid;

            TransportConfig config = TransportRegistry.Instance.CreateConfig(configName);
            TransportInst   inst   = TransportRegistry.Instance.CreateInst(instName, "rtps_udp");
            RtpsUdpInst     rui    = new RtpsUdpInst(inst);

            config.Insert(rui);

            TransportRegistry.Instance.BindConfig(configName, participant);
        }
        public void TestRead()
        {
            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.Read(data, infos);
            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);
        }
예제 #20
0
        /// <summary>
        /// Runs the publisher example.
        /// </summary>
        public static void RunPublisher(int domainId, int sampleCount, bool useXmlConfig = 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 <StockPrice> topic = participant.CreateTopic <StockPrice>("Example market_data");

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

            DataWriterQos writerQos;

            if (useXmlConfig)
            {
                // Gets the default DataWriterQos defined in USER_QOS_PROFILES.xml
                writerQos = QosProvider.Default.GetDataWriterQos();
            }
            else
            {
                // Creates the DataWriterQos programmatically to the same effect
                // as the one defined in XML.
                writerQos = publisher.DefaultDataWriterQos.WithMultiChannel(
                    CreateMultiChannelQosPolicy());
            }

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

            var sample = new StockPrice();

            for (int count = 0; count < sampleCount; count++)
            {
                // Update the symbol and price
                char symbol = (char)('A' + (count % 26));
                sample.Symbol = symbol.ToString();
                sample.Price  = count;

                writer.Write(sample);

                Thread.Sleep(100);
            }
        }
        public void TestGetKeyValue()
        {
            // Call GetKeyValue with HandleNil
            TopicBuiltinTopicData 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.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);

            // Get the for an existing instance
            ret = _dr.ReadNextSample(ref data, info);
            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 < 3; 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);
        }
        public void TestLookupInstance()
        {
            PublicationBuiltinTopicData data = default;
            SampleInfo info = new SampleInfo();

            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);

            ReturnCode ret = _dr.ReadNextSample(ref data, info);

            Assert.AreEqual(ReturnCode.Ok, ret);

            // Lookup for an existing instance
            var handle = _dr.LookupInstance(data);

            Assert.AreNotEqual(InstanceHandle.HandleNil, handle);

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

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
예제 #23
0
        public ReturnCode DeleteParticipant(IDomainParticipant a_participant)
        {
            ReturnCode result = ReturnCode.BadParameter;

            DomainParticipant participant = a_participant as DomainParticipant;

            if (participant != null)
            {
                result = OpenSplice.Gapi.DomainParticipantFactory.delete_participant(
                    GapiPeer,
                    participant.GapiPeer);
            }

            return(result);
        }
예제 #24
0
 public void RegisterParticipant(DomainParticipant participant)
 {
     lock (this)
     {
         DomainParticipantImpl part = participant as DomainParticipantImpl;
         if (part != null)
         {
             participants.Add(part.ParticipantGuid, part);
             if (!participantsInDomains.ContainsKey(part.DomainId))
                 participantsInDomains.Add(part.DomainId, new SortedSet<DomainParticipantImpl>());
             participantsInDomains[part.DomainId].Add(part);
             NotifyParticipantChanges(DiscoveryDomainParticipantEventReason.NEW_PARTICIPANT, participant);
         }
     }
 }
예제 #25
0
 public void UnregisterParticipant(DomainParticipant participant)
 {
     lock (this)
     {
         DomainParticipantImpl part = participant as DomainParticipantImpl;
         if (part != null)
         {
             participants.Remove(part.ParticipantGuid);
             participantsInDomains[part.DomainId].Remove(part);
             if (participantsInDomains[part.DomainId].Count == 0)
                 participantsInDomains.Remove(part.DomainId);
             NotifyParticipantChanges(DiscoveryDomainParticipantEventReason.DELETED_PARTICIPANT, participant);
         }
     }
 }
예제 #26
0
        /// <summary>
        /// Creates a DomainParticipant, Topic, Publisher and DataWriter<HelloWorld>.
        /// </summary>
        public HelloWorldPublisher(int domainId)
        {
            // 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>(
                "Example InstanceStatisticsExample_HelloWorld");

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

            // Create a DataWriter, loading QoS profile from USER_QOS_PROFILES.xml
            writer = publisher.CreateDataWriter(topic);
        }
예제 #27
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);
            }
        }
예제 #28
0
        /// <summary>
        /// Creates a DomainParticipant, Topic, Publisher and DataWriter.
        /// </summary>
        public HelloWorldPublisher(
            int domainId,
            string expectedPassword,
            string topicName)
        {
            // Save the expected password. We will only communicate with
            // subscriptions that send this password via discovery.
            this.expectedPassword = expectedPassword;

            // Configure the participant QoS to increase the user data max length
            DomainParticipantQos participantQos =
                DomainParticipantFactory.Instance.DefaultParticipantQos
                .WithResourceLimits(policy => policy.ParticipantUserDataMaxLength = 1024);

            // Create the participant
            participant = DomainParticipantFactory.Instance.CreateParticipant(
                domainId,
                qos: participantQos,
                preEnableAction: p =>
            {
                // The preEnableAction is executed right before the participant
                // is enabled and communication starts. By looking up the
                // built-in discovery readers here we ensure that
                // that they will receive all the discovery information.
                participantReader = p.BuiltinSubscriber
                                    .LookupDataReader <ParticipantBuiltinTopicData>(
                    Subscriber.ParticipantBuiltinTopicName);

                // The DataAvailable event is called when another participant
                // is discovered and before this participant has started
                // communicating with it
                participantReader.DataAvailable += OnNewParticipant;

                subscriptionReader = p.BuiltinSubscriber
                                     .LookupDataReader <SubscriptionBuiltinTopicData>(
                    Subscriber.SubscriptionBuiltinTopicName);

                subscriptionReader.DataAvailable += OnNewSubscription;
            }
                );

            // Create a topic, a publisher and a writer
            Topic <HelloWorld> topic     = participant.CreateTopic <HelloWorld>(topicName);
            Publisher          publisher = participant.CreatePublisher();

            writer = publisher.CreateDataWriter(topic);
        }
예제 #29
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);
        }
예제 #30
0
        private static void TestOnSubscriptionLostDisconnected()
        {
            DomainParticipantFactory dpf         = ParticipantService.Instance.GetDomainParticipantFactory();
            DomainParticipant        participant = dpf.CreateParticipant(INFOREPO_DOMAIN);

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

            Publisher publisher = participant.CreatePublisher();

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

            TestStructTypeSupport support = new TestStructTypeSupport();
            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("TestOnSubscriptionLostDisconnected", typeName);

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

            DataWriter writer = publisher.CreateDataWriter(topic);

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

            while (true)
            {
                System.Threading.Thread.Sleep(100);
            }
        }
예제 #31
0
        public void TestTakeInstance()
        {
            List <ParticipantBuiltinTopicData> data = new List <ParticipantBuiltinTopicData>();
            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);

            DomainParticipantQos qos = new DomainParticipantQos();

            qos.UserData.Value = new byte[] { 0x42 };
            DomainParticipant otherParticipant = AssemblyInitializer.Factory.CreateParticipant(AssemblyInitializer.RTPS_DOMAIN, qos);

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

            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);
            Assert.AreEqual(1, data.First().UserData.Value.Count());
            Assert.AreEqual(0x42, data.First().UserData.Value.First());

            var handle = infos.First().InstanceHandle;

            data  = new List <ParticipantBuiltinTopicData>();
            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(1, data.First().UserData.Value.Count());
            Assert.AreEqual(0x42, data.First().UserData.Value.First());

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

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
        /// <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;
                    }
                }
            }
        }
예제 #33
0
        public void TestTakeNextSample()
        {
            SubscriptionBuiltinTopicData data = default;
            SampleInfo infos = new SampleInfo();
            ReturnCode ret   = _dr.TakeNextSample(ref data, infos);

            Assert.AreEqual(ReturnCode.NoData, ret);

            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);

            Thread.Sleep(500);

            ret = _dr.TakeNextSample(ref data, infos);
            Assert.AreEqual(ReturnCode.Ok, ret);
            TestHelper.TestNonDefaultSubscriptionData(data);

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

            ret = AssemblyInitializer.Factory.DeleteParticipant(otherParticipant);
            Assert.AreEqual(ReturnCode.Ok, ret);
        }
예제 #34
0
        private void NotifyParticipantChanges(DiscoveryDomainParticipantEventReason reason, DomainParticipant participant)
        {
            log.DebugFormat("The information about DomainParticipants has changed. Reason {0}, Participant {1}", reason, participant);
            if (ParticipantDiscovery != null)
            {
                DiscoveryDomainParticipantEventArgs dpea = new DiscoveryDomainParticipantEventArgs()
                {
                    Reason = reason,
                    Participant = participant

                };
                ParticipantDiscovery(this, dpea);
            }
        }