def replier_main(domain_id): global request_serviced participant = dds.DomainParticipant(domain_id) qos_provider = dds.QosProvider.default type_provider = dds.QosProvider('Primes.xml') request_type = type_provider.type("PrimeNumberRequest") reply_type = type_provider.type("PrimeNumberReply") status_type = type_provider.type("PrimeNumberCalculationStatus") def request_handler(request): global request_serviced request_serviced = True if (request["n"] <= 0 or request["primes_per_reply"] <= 0 or request["primes_per_reply"] > reply_type["primes"].type.bounds): error_reply = dds.DynamicData(reply_type) error_reply["status"] = status_type["REPLY_ERROR"] print("Error, requester asked for too many primes per reply") return error_reply else: print("Calculating prime numbers below {}...".format(request["n"])) n = request["n"] max_count = request["primes_per_reply"] primes = dds.Int32Seq() reply = dds.DynamicData(reply_type) for m in xrange(1, n + 1): if is_prime(m): primes.append(m) if len(primes) > max_count: reply["status"] = status_type["REPLY_ERROR"] print( "Error: too many calculated primes for a single reply" ) return reply reply["primes"] = primes reply["status"] = status_type["REPLY_COMPLETED"] print("DONE") return reply replier = rti.request.SimpleReplier( request_type, reply_type, participant, request_handler, service_name="PrimeCalculator", datawriter_qos=qos_provider.datawriter_qos_from_profile( "RequestReplyExampleProfiles::RequesterExampleProfile"), datareader_qos=qos_provider.datareader_qos_from_profile( "RequestReplyExampleProfiles::RequesterExampleProfile")) print( "Prime calculation replier started on domain {}...".format(domain_id)) while request_serviced: request_serviced = False time.sleep(20) print("Timed out waiting for requests")
def subscriber_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) wsqc_type = dds.QosProvider("waitset_cond.xml").type("wssc_lib", "Foo") topic = dds.DynamicData.Topic(participant, "Example Foo", wsqc_type) reader_qos = dds.QosProvider.default.datareader_qos reader = dds.DynamicData.DataReader(dds.Subscriber(participant), topic, reader_qos) # Get the StatusCondition associated with the reader and set the mask to get liveliness updates status_condition = dds.StatusCondition(reader) status_condition.enabled_statuses = dds.StatusMask.LIVELINESS_CHANGED # Create a ReadCondition to get any data read_condition = dds.ReadCondition(reader, dds.DataState.any_data) # Create WaitSet and attach conditions waitset = dds.WaitSet() waitset += status_condition waitset += read_condition count = Counter() while (sample_count == 0) or (count.value < sample_count): active = waitset.wait(4.0) # Check conditions after wait to see if anything triggered if status_condition in active: status_handler(reader) if read_condition in active: rc_handler(reader, count)
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) # Participant properties give access to the builtin readers participant.participant_reader.bind_listener( BuiltinParticipantListener(), dds.StatusMask.DATA_AVAILABLE ) participant.subscription_reader.bind_listener( BuiltinSubscriptionListener(), dds.StatusMask.DATA_AVAILABLE ) participant.enable() msg_type = dds.QosProvider("msg.xml").type("builtin_topics_lib", "msg") topic = dds.DynamicData.Topic(participant, "Example msg", msg_type) writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic) instance = dds.DynamicData(msg_type) # write samples in a loop, incrementing the 'x' field count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1) instance["x"] = count writer.write(instance, dds.InstanceHandle()) count += 1
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) # Participant properties give access to the builtin readers participant.participant_reader.bind_listener( BuiltinParticipantListener(), dds.StatusMask.data_available()) participant.subscription_reader.bind_listener( BuiltinSubscriptionListener(), dds.StatusMask.data_available()) msg_type = dds.QosProvider('msg.xml').type('builtin_topics_lib', 'msg') topic = dds.DynamicData.Topic(participant, 'Example msg', msg_type) writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic) instance = dds.DynamicData(msg_type) # write samples in a loop, incrementing the 'x' field count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1) instance['x'] = count writer.write(instance, dds.InstanceHandle()) count += 1 assert count == 5
def run_example(domain_id, sample_count): # A DomainParticipant allows an application to begin communicating in # a DDS domain. Typically there is one DomainParticipant per application. # Create a DomainParticipant with default Qos with dds.DomainParticipant(domain_id) as participant: # A QosProvider is used here to get the type from the file # HelloWorld.xml provider = dds.QosProvider(FILE) provider_type = provider.type("HelloWorld") # A Topic has a name and a datatype. Create a Topic named # "HelloWorld Topic" with type HelloWorld topic = dds.DynamicData.Topic( participant, "Example HelloWorld", provider_type ) # A Subscriber allows an application to create one or more DataReaders # Subscriber QoS is configured in USER_QOS_PROFILES.xml subscriber = dds.Subscriber(participant) # This DataReader will read data of type HelloWorld on Topic # "HelloWorld Topic". DataReader QoS is configured in # USER_QOS_PROFILES.xml reader = dds.DynamicData.DataReader(subscriber, topic) # Obtain the DataReader's Status Condition status_condition = dds.StatusCondition(reader) # Enable the 'data available' status. status_condition.enabled_statuses = dds.StatusMask.data_available() # Initialize samples_read to zero samples_read = 0 # Associate a handler with the status condition. This will run when the # condition is triggered, in the context of the dispatch call (see below) def handler(_): # condition argument is not used nonlocal samples_read nonlocal reader samples_read += process_data(reader) status_condition.set_handler(handler) # Create a WaitSet and attach the StatusCondition waitset = dds.WaitSet() waitset += status_condition # Catch control c interrupt try: while samples_read < sample_count: # Dispatch will call the handlers associated to the WaitSet conditions # when they activate print(f"Hello World subscriber sleeping for 4 seconds...") waitset.dispatch(dds.Duration(4)) # Wait up to 4s each time except KeyboardInterrupt: pass
def requester_main(domain_id, n, primes_per_reply): participant = dds.DomainParticipant(domain_id) qos_provider = dds.QosProvider.default type_provider = dds.QosProvider('Primes.xml') request_type = type_provider.type("PrimeNumberRequest") reply_type = type_provider.type("PrimeNumberReply") status_type = type_provider.type("PrimeNumberCalculationStatus") requester = request.Requester( request_type, reply_type, participant, service_name="PrimeCalculator", datawriter_qos=qos_provider.datawriter_qos_from_profile( "RequestReplyExampleProfiles::RequesterExampleProfile"), datareader_qos=qos_provider.datareader_qos_from_profile( "RequestReplyExampleProfiles::RequesterExampleProfile")) print("Waiting to discover replier on domain {}...".format(domain_id)) while requester.matched_replier_count == 0: time.sleep(0.1) prime_number_request = dds.DynamicData(request_type) prime_number_request["n"] = n prime_number_request["primes_per_reply"] = primes_per_reply print( "Sending a request to calculate the prime numbers <= {} in sequences of {} or fewer elements" .format(n, primes_per_reply)) request_id = requester.send_request(prime_number_request) max_wait = dds.Duration.from_seconds(20) in_progress = True while in_progress: if not requester.wait_for_replies(max_wait, related_request_id=request_id): raise dds.TimeoutError("Timed out waitinf for replies") for reply in (r.data for r in requester.take_replies(request_id) if r.info.valid): primes = reply["primes"] for prime in primes: print(prime) if reply["status"] != status_type["REPLY_IN_PROGRESS"]: in_progress = False if reply["status"] == status_type["REPLY_ERROR"]: raise RuntimeError("Error in replier") print("DONE")
def run_example(domain_id, sample_count, sensor_id): # A DomainParticipant allows an application to begin communicating in # a DDS domain. Typically there is one DomainParticipant per application. # Create a DomainParticipant with default Qos participant = dds.DomainParticipant(domain_id) # A Topic has a name and a datatype. Create a Topic named # "ChocolateTemperature" with type Temperature temperature_type = dds.QosProvider(FILE).type("Temperature") topic = dds.DynamicData.Topic(participant, "ChocolateTemperature", temperature_type) # A Subscriber allows an application to create one or more DataReaders # Subscriber QoS is configured in USER_QOS_PROFILES.xml subscriber = dds.Subscriber(participant) # This DataReader reads data of type Temperature on Topic # "ChocolateTemperature". DataReader QoS is configured in # USER_QOS_PROFILES.xml reader = dds.DynamicData.DataReader(subscriber, topic) # Obtain the DataReader's Status Condition status_condition = dds.StatusCondition(reader) # Enable the 'data available' status. status_condition.enabled_statuses = dds.StatusMask.data_available() # Associate a handler with the status condition. This will run when the # condition is triggered, in the context of the dispatch call (see below) samples_read = 0 def handler(_): nonlocal samples_read nonlocal reader samples_read += process_data(reader) status_condition.set_handler(handler) # Create a WaitSet and attach the StatusCondition waitset = dds.WaitSet() waitset += status_condition try: # Dispatch will call the handlers associated to the WaitSet conditions # when they activate while sample_count is None or samples_read < sample_count: print("ChocolateTemperature subcriber sleeping for 4 sec...") waitset.dispatch(dds.Duration(4)) # Wait up to 4s each time except KeyboardInterrupt: pass
def subscriber_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) ccf_type = dds.QosProvider("ccf.xml").type("ccf_lib", "Foo") topic = dds.DynamicData.Topic(participant, "Example ccf", ccf_type) # Register the custom filter with the Participant participant.register_contentfilter(ccf.CustomFilterType(), "CustomFilter") # Set a filter expression and the filter name, then create the CFT custom_filter = dds.Filter("%0 %1 x", ["2", "divides"]) custom_filter.name = "CustomFilter" topic = dds.DynamicData.ContentFilteredTopic( topic, "ContentFilteredTopic", custom_filter ) print("Filter: 2 divides x") reader = dds.DynamicData.DataReader(dds.Subscriber(participant), topic) reader.bind_listener(CcfListener(), dds.StatusMask.DATA_AVAILABLE) count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1) if count == 10: # Update the filter parameters after 10 seconds print( textwrap.dedent( """ ========================== Changing Filter Parameters Filter: 15 greater-than x ==========================""" ) ) topic.filter_parameters = ["15", "greater-than"] elif count == 20: # Update the filter again after 20 seconds print( textwrap.dedent( """ ========================== Changing Filter Parameters Filter: 3 divides x ==========================""" ) ) topic.filter_parameters = ["3", "divides"] count += 1
def replier_main(domain_id): participant = dds.DomainParticipant(domain_id) qos_provider = dds.QosProvider.default type_provider = dds.QosProvider('Primes.xml') request_type = type_provider.type("PrimeNumberRequest") reply_type = type_provider.type("PrimeNumberReply") status_type = type_provider.type("PrimeNumberCalculationStatus") replier = rti.request.Replier( request_type, reply_type, participant, service_name="PrimeCalculator", datawriter_qos=qos_provider.datawriter_qos_from_profile("RequestReplyExampleProfiles::RequesterExampleProfile"), datareader_qos=qos_provider.datareader_qos_from_profile("RequestReplyExampleProfiles::RequesterExampleProfile")) print("Prime calculation replier started on domain {}...".format(domain_id)) max_wait = dds.Duration.from_seconds(20) requests = replier.receive_requests(max_wait) while len(requests) > 0: for request in (sample for sample in requests if sample.info.valid): if (request.data["n"] <= 0 or request.data["primes_per_reply"] <= 0 or request.data["primes_per_reply"] > reply_type["primes"].type.bounds): error_reply = dds.DynamicData(reply_type) error_reply["status"] = status_type["REPLY_ERROR"] replier.send_reply(error_reply, request.info) else: print("Calculating prime numbers below {}...".format(request.data["n"])) n = request.data["n"] max_count = request.data["primes_per_reply"] primes = dds.Int32Seq() reply = dds.DynamicData(reply_type) for m in xrange(1, n + 1): if is_prime(m): primes.append(m) if len(primes) == max_count: reply["primes"] = primes reply["status"] = status_type["REPLY_IN_PROGRESS"] replier.send_reply(reply, request.info, final=False) primes.clear() reply["primes"] = primes reply["status"] = status_type["REPLY_COMPLETED"] replier.send_reply(reply, request.info) print("DONE") requests = replier.receive_requests(max_wait)
def subscriber_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) subscriber_qos = dds.QosProvider.default.subscriber_qos subscriber = dds.Subscriber(participant, subscriber_qos) coherent_type = dds.QosProvider("coherent.xml").type("coherent_lib", "coherent") topic = dds.DynamicData.Topic(participant, "Example coherent", coherent_type) datareader_qos = dds.QosProvider.default.datareader_qos reader = dds.DynamicData.DataReader(subscriber, topic, datareader_qos) reader.bind_listener(CoherentListener(), dds.StatusMask.data_available()) count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1)
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) wssc_type = dds.QosProvider("waitset_cond.xml").type("wssc_lib", "Foo") topic = dds.DynamicData.Topic(participant, "Example Foo", wssc_type) writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic) sample = dds.DynamicData(wssc_type) count = 0 while (sample_count == 0) or (count < sample_count): print("Writing Foo, count = {}".format(count)) sample["x"] = count writer.write(sample) count += 1 time.sleep(1)
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) cft_type = dds.QosProvider("cft.xml").type("cft_lib", "cft") topic = dds.DynamicData.Topic(participant, "Example cft", cft_type) writer_qos = dds.QosProvider.default.datawriter_qos writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic, writer_qos) sample = dds.DynamicData(cft_type) count = 0 while (sample_count == 0) or (count < sample_count): print("Writing cft, count={}".format(count)) sample["count"] = count sample["name"] = "ODD" if count % 2 == 1 else "EVEN" writer.write(sample) time.sleep(1) count += 1
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) # We can register the custom filter on the writer side participant.register_contentfilter(ccf.CustomFilterType(), "CustomFilter") ccf_type = dds.QosProvider("ccf.xml").type("ccf_lib", "Foo") topic = dds.DynamicData.Topic(participant, "Example ccf", ccf_type) writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic) instance = dds.DynamicData(ccf_type) count = 0 while (sample_count == 0) or (count < sample_count): print("Writing ccf, count={}".format(count)) instance["x"] = count writer.write(instance) time.sleep(1) count += 1
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) wsqc_type = dds.QosProvider("waitset_query_cond.xml").type( "wsqc_lib", "waitset_query_cond" ) topic = dds.DynamicData.Topic(participant, "Example waitset_query_cond", wsqc_type) writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic) instance = dds.DynamicData(wsqc_type) count = 0 while (sample_count == 0) or (count < sample_count): print("Writing waitset_query_cond, count = {}".format(count)) instance["x"] = count instance["name"] = "ODD" if count % 2 == 1 else "EVEN" writer.write(instance) count += 1 time.sleep(1)
def __init__(self, domain_id, sample_type): self.participant = create_participant(domain_id) reader_qos = self.participant.implicit_subscriber.default_datareader_qos reader_qos << dds.Durability.transient_local reader_qos << dds.Reliability.reliable() reader_qos << dds.History.keep_all writer_qos = self.participant.implicit_publisher.default_datawriter_qos writer_qos << dds.Durability.transient_local writer_qos << dds.Reliability.reliable() writer_qos << dds.History.keep_all if sample_type == "StringTopicType": self.topic = dds.StringTopicType.Topic(self.participant, "StringTopicType") self.reader = dds.StringTopicType.DataReader( self.participant, self.topic, reader_qos) self.writer = dds.StringTopicType.DataWriter( self.participant, self.topic, writer_qos) elif sample_type == "KeyedStringTopicType": self.topic = dds.KeyedStringTopicType.Topic( self.participant, "KeyedStringTopicType") self.reader = dds.KeyedStringTopicType.DataReader( self.participant, self.topic, reader_qos) self.writer = dds.KeyedStringTopicType.DataWriter( self.participant, self.topic, writer_qos) elif sample_type == "PerformanceTest": provider = dds.QosProvider( str(pathlib.Path(__file__).parent.absolute()) + "/../xml/PerfTest.xml") provider_type = provider.type("PerformanceTest") self.topic = dds.DynamicData.Topic(self.participant, "PerformanceTest", provider_type) self.reader = dds.DynamicData.DataReader( dds.Subscriber(self.participant), self.topic, reader_qos) self.writer = dds.DynamicData.DataWriter( dds.Publisher(self.participant), self.topic, writer_qos) else: raise Exception(sample_type + " not supported in test system")
def subscriber_main(domain_id, sample_count, participant_auth): participant_qos = dds.QosProvider.default.participant_qos resource_limits_qos = participant_qos.resource_limits max_participant_user_data = resource_limits_qos.participant_user_data_max_length # Set the participant auth string as user data bytes if len(participant_auth) > max_participant_user_data: raise ValueError("participant user data exceeds resource limits") else: participant_qos.user_data.value = bytearray(participant_auth.encode()) participant = dds.DomainParticipant(domain_id, participant_qos) participant.enable() msg_type = dds.QosProvider("msg.xml").type("builtin_topics_lib", "msg") topic = dds.DynamicData.Topic(participant, "Example msg", msg_type) reader = dds.DynamicData.DataReader(dds.Subscriber(participant), topic) reader.bind_listener(MsgListener(), dds.StatusMask.data_available()) count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1) count += 1
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) cft_type = dds.QosProvider("cft.xml").type("cft_lib", "cft") topic = dds.DynamicData.Topic(participant, "Example cft", cft_type) writer_qos = dds.QosProvider.default.datawriter_qos writer = dds.DynamicData.DataWriter(dds.Publisher(participant), topic, writer_qos) instance = dds.DynamicData(cft_type) handle = dds.InstanceHandle.nil() # Output "ones" digit of count as 'x' field count = 0 while (sample_count == 0) or (count < sample_count): instance["count"] = count instance["x"] = count % 10 print("Writing cft, count={}\tx={}".format(instance["count"], instance["x"])) writer.write(instance, handle) time.sleep(1) count += 1
def publisher_main(domain_id, sample_count): participant = dds.DomainParticipant(domain_id) publisher_qos = dds.QosProvider.default.publisher_qos publisher = dds.Publisher(participant, publisher_qos) coherent_type = dds.QosProvider("coherent.xml").type( "coherent_lib", "coherent") topic = dds.DynamicData.Topic(participant, "Example coherent", coherent_type) datawriter_qos = dds.QosProvider.default.datawriter_qos writer = dds.DynamicData.DataWriter(publisher, topic, datawriter_qos) sample = dds.DynamicData(coherent_type) sample["id"] = 0 handle = writer.register_instance(sample) num_samples = 7 count = 0 while (sample_count == 0) or (count < sample_count): # Use a context manager to scope the coherent set writes with dds.CoherentSet(publisher): print("Begin Coherent Changes") for i in xrange(num_samples): time.sleep(1) sample["field"] = chr(ord("a") + i) sample["value"] = random.randint(0, 10) print("Updating instance, {}->{}".format( sample["field"], sample["value"])) writer.write(sample, handle) count += 1 print("End Coherent Changes") writer.unregister_instance(handle)
def test_getters(): DEFAULT_PROFILE = "my_default_profile1" TEST_LIB = "my_test_library1" domain_participant_qos = dds.DomainParticipantQos() pub_qos = dds.PublisherQos() dw_qos = dds.DataWriterQos() sub_qos = dds.SubscriberQos() dr_qos = dds.DataWriterQos() topic_qos = dds.TopicQos() topic_a = "topic_A" topic_b = "topic_B" my_uri = LOCATION + "../xml/QosProviderTest_qos1.xml" qos_provider = dds.QosProvider(my_uri) my_other_profile_name = "my_other_profile1" assert qos_provider.default_library == TEST_LIB assert qos_provider.default_profile == DEFAULT_PROFILE assert qos_provider.default_profile_library == TEST_LIB domain_participant_qos = qos_provider.participant_qos assert domain_participant_qos.participant_name.name == "defaultParticipantName" pub_qos = qos_provider.publisher_qos assert pub_qos.entity_name.name == "defaultPublisherName" dw_qos = qos_provider.datawriter_qos assert dw_qos.entity_name.name == "defaultPublicationName" dw_qos = qos_provider.get_topic_datawriter_qos(topic_a) assert dw_qos.entity_name.name == "defaultPublicationNameA" dw_qos = qos_provider.get_topic_datawriter_qos(topic_b) assert dw_qos.entity_name.name == "defaultPublicationNameB" sub_qos = qos_provider.subscriber_qos assert sub_qos.entity_name.name == "defaultSubscriberName" dr_qos = qos_provider.datareader_qos assert dr_qos.entity_name.name == "defaultSubscriptionName" dr_qos = qos_provider.get_topic_datareader_qos(topic_a) assert dr_qos.entity_name.name == "defaultSubscriptionNameA" dr_qos = qos_provider.get_topic_datareader_qos(topic_b) assert dr_qos.entity_name.name == "defaultSubscriptionNameB" topic_qos = qos_provider.topic_qos assert topic_qos.resource_limits.max_samples == 100 topic_qos = qos_provider.get_topic_name_qos(topic_a) assert topic_qos.resource_limits.max_samples == 101 topic_qos = qos_provider.get_topic_name_qos(topic_b) assert topic_qos.resource_limits.max_samples == 102 # Start using my_other_profile_name domain_participant_qos = qos_provider.participant_qos_from_profile( my_other_profile_name) assert domain_participant_qos.participant_name.name == "otherParticipantName" pub_qos = qos_provider.publisher_qos_from_profile(my_other_profile_name) assert pub_qos.entity_name.name == "otherPublisherName" dw_qos = qos_provider.datawriter_qos_from_profile(my_other_profile_name) assert dw_qos.entity_name.name == "otherPublicationName" dw_qos = qos_provider.set_topic_datawriter_qos(my_other_profile_name, topic_a) assert dw_qos.entity_name.name == "otherPublicationNameA" dw_qos = qos_provider.set_topic_datawriter_qos(my_other_profile_name, topic_b) assert dw_qos.entity_name.name == "otherPublicationNameB" sub_qos = qos_provider.subscriber_qos_from_profile(my_other_profile_name) assert sub_qos.entity_name.name == "otherSubscriberName" dr_qos = qos_provider.datareader_qos_from_profile(my_other_profile_name) assert dr_qos.entity_name.name == "otherSubscriptionName" dr_qos = qos_provider.set_topic_datareader_qos(my_other_profile_name, topic_a) assert dr_qos.entity_name.name == "otherSubscriptionNameA" dr_qos = qos_provider.set_topic_datareader_qos(my_other_profile_name, topic_b) assert dr_qos.entity_name.name == "otherSubscriptionNameB" topic_qos = qos_provider.topic_qos_from_profile(my_other_profile_name) assert topic_qos.resource_limits.max_samples == 200 topic_qos = qos_provider.set_topic_name_qos(my_other_profile_name, topic_a) assert topic_qos.resource_limits.max_samples == 201 topic_qos = qos_provider.set_topic_name_qos(my_other_profile_name, topic_b) assert topic_qos.resource_limits.max_samples == 202
def test_invalid_creation(): with pytest.raises(dds.Error): dds.QosProvider("invalid_file.xml") with pytest.raises(dds.Error): dds.QosProvider(LOCATION + "../xml/InvalidXml.xml")
def test_string_uri_creation(): assert (len( dds.QosProvider(LOCATION + "../xml/XmlApplication.xml").qos_profile_libraries) == 4)
def subscriber_main(domain_id, sample_count, is_cft): participant = dds.DomainParticipant(domain_id) cft_type = dds.QosProvider("cft.xml").type("cft_lib", "cft") topic = dds.DynamicData.Topic(participant, "Example cft", cft_type) if is_cft: # Create a CFT that filters for incoming data within a range topic = dds.DynamicData.ContentFilteredTopic( topic, "ContentFilteredTopic", dds.Filter("x >= %0 AND x <= %1", ["1", "4"]) ) print( textwrap.dedent( """ ========================== Using CFT Filter: 1 <= x <= 4 ==========================""" ) ) else: # Filtering disabled by default print( textwrap.dedent( """ ========================== Using Normal Topic ==========================""" ) ) reader_qos = dds.QosProvider.default.datareader_qos reader = dds.DynamicData.DataReader(dds.Subscriber(participant), topic, reader_qos) reader.bind_listener(CftListener(), dds.StatusMask.DATA_AVAILABLE) count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1) if is_cft: if count == 10: # After 10 seconds, udpdate the filter range print( textwrap.dedent( """ ========================== Changing Filter Parameters Filter: 5 <= x <= 9 ==========================""" ) ) topic.filter_parameters = ["5", "9"] if count == 20: # After 20 seconds, update the filter again print( textwrap.dedent( """ ========================== Changing Filter Parameters Filter: 3 <= x <= 9 ==========================""" ) ) topic.filter_parameters = ["3", "9"] count += 1
else: print(" Received metadata") def publish_env(id, writer, kvp_type, env): sample = dds.DynamicData(kvp_type) sample["id"] = id for var, value in env.items(): sample["key"] = var sample["value"] = value writer.write(sample) if __name__ == "__main__": qos_provider = dds.QosProvider(QOS_URL) participant = qos_provider.create_participant_from_config(PARTICIPANT_NAME) my_type = qos_provider.type(qos_provider.type_libraries[0], KVP_TYPE_NAME) writer = dds.DynamicData.DataWriter.find_by_name(participant, WRITER_NAME) reader = dds.DynamicData.DataReader.find_by_name(participant, READER_NAME) reader.bind_listener(MyDataReaderListener(), dds.StatusMask.DATA_AVAILABLE) participant.ignore_participant(participant.instance_handle) id = random.randint(0, 2147483647) while True:
# obligation to maintain or support the software. RTI shall not be liable for # any incidental or consequential damages arising out of the use or inability # to use the software. # import rti.connextdds as dds import argparse # for arg parsing import pathlib # for finding the XML files import threading # for multithreading import time # for sleeping import random # to generate random data points FILE = str( pathlib.Path(__file__).parent.absolute()) + "/../chocolate_factory.xml" provider = dds.QosProvider(FILE) TEMPERATURE_TYPE = provider.type("Temperature") CHOCOLATE_LOT_TYPE = provider.type("ChocolateLotState") STATION_KIND_TYPE = provider.type("StationKind") LOT_STATUS_KIND_TYPE = provider.type("LotStatusKind") CHOCOLATE_LOT_STATE_TOPIC = "ChocolateLotState" CHOCOLATE_TEMPERATURE_TOPIC = "ChocolateTemperature" # Tempering application: # 1) Publishes the temperature # 2) Subscribes to the lot state # 3) After "processing" the lot, publishes the lot state
def all_test(count): # For testing assigning to a whole array at once perf_test_type = dds.QosProvider(FILE).type("PerformanceTest") sample = dds.DynamicData(perf_test_type) # By setting these to really high and low values, it ensures that we will have a # proper min and max value at the end min_time_all = float("inf") max_time_all = float("-inf") total_time_all = 0 full_lst = array.array("B", [25]) * 600000 # First test setter for i in range(0, count): start_all = time.time() sample.set_uint8_values("myOctSeq", full_lst) elapsed_all = time.time() - start_all min_time_all = min(min_time_all, elapsed_all) max_time_all = max(max_time_all, elapsed_all) total_time_all += elapsed_all if (i % math.ceil(count / 20)) == 0: print(".", end="", flush=True) print("") print("\tAssigning all at once setter from an array") average_all = total_time_all / count print(f"Average: {average_all} seconds\nMinimum: {min_time_all} seconds") print( f"Maximum: {max_time_all} seconds\nTotal: {total_time_all} seconds") min_time_all = float("inf") max_time_all = float("-inf") total_time_all = 0 full_lst = [25] * 600000 # First test setter for i in range(0, count): start_all = time.time() sample.set_uint8_values("myOctSeq", full_lst) elapsed_all = time.time() - start_all min_time_all = min(min_time_all, elapsed_all) max_time_all = max(max_time_all, elapsed_all) total_time_all += elapsed_all if (i % math.ceil(count / 20)) == 0: print(".", end="", flush=True) print("") print("\tAssigning all at once setter from a list") average_all = total_time_all / count print(f"Average: {average_all} seconds\nMinimum: {min_time_all} seconds") print( f"Maximum: {max_time_all} seconds\nTotal: {total_time_all} seconds") min_time_all = float("inf") max_time_all = float("-inf") total_time_all = 0 for i in range(0, count): start_all = time.time() lst = sample.get_uint8_values("myOctSeq") elapsed_all = time.time() - start_all min_time_all = min(min_time_all, elapsed_all) max_time_all = max(max_time_all, elapsed_all) total_time_all += elapsed_all if (i % math.ceil(count / 20)) == 0: print(".", end="", flush=True) print("") print("\tAssigning all at once getter") average_all = total_time_all / count print(f"Average: {average_all} seconds\nMinimum: {min_time_all} seconds") print( f"Maximum: {max_time_all} seconds\nTotal: {total_time_all} seconds")
def ind_test(count): perf_test_type = dds.QosProvider(FILE).type("PerformanceTest") # For testing assigning to an array element by element min_time_ind = float("inf") max_time_ind = float("-inf") total_time_ind = 0 # Here I fill the sequence once all the way through so that the space is # already allocated data = dds.OctetSeq(array.array("B", [25]) * 600000) for i in range(0, count): start_ind = time.time() for j in range(0, 600000): data[j] = 25 elasped_ind = time.time() - start_ind min_time_ind = min(min_time_ind, elasped_ind) max_time_ind = max(max_time_ind, elasped_ind) total_time_ind += elasped_ind if i % math.ceil(count / 20) == 0: print(".", end="", flush=True) print("") print("\tAssigning individually setter (OctetSeq)") average_ind = total_time_ind / count print(f"Average: {average_ind} seconds\nMinimum: {min_time_ind} seconds") print( f"Maximum: {max_time_ind} seconds\nTotal: {total_time_ind} seconds") min_time_ind = float("inf") max_time_ind = float("-inf") total_time_ind = 0 # Here I fill the sequence once all the way through so that the space is # already allocated data = memoryview(dds.OctetSeq(array.array("B", [25]) * 600000)) for i in range(0, count): start_ind = time.time() for j in range(0, 600000): data[j] = 25 elasped_ind = time.time() - start_ind min_time_ind = min(min_time_ind, elasped_ind) max_time_ind = max(max_time_ind, elasped_ind) total_time_ind += elasped_ind if i % math.ceil(count / 20) == 0: print(".", end="", flush=True) print("") print("\tAssigning individually setter (OctetSeq in memoryview)") average_ind = total_time_ind / count print(f"Average: {average_ind} seconds\nMinimum: {min_time_ind} seconds") print( f"Maximum: {max_time_ind} seconds\nTotal: {total_time_ind} seconds") min_time_ind = float("inf") max_time_ind = float("-inf") total_time_ind = 0 sample = dds.DynamicData(perf_test_type) # Here I fill the sequence once all the way through so that the space is # already allocated sample["myOctSeq"] = array.array("B", [25]) * 600000 for i in range(0, count): loan = sample.loan_value("myOctSeq") data = loan.data start_ind = time.time() for j in range(0, 600000): data.set_uint8(j, 25) elasped_ind = time.time() - start_ind loan.return_loan() min_time_ind = min(min_time_ind, elasped_ind) max_time_ind = max(max_time_ind, elasped_ind) total_time_ind += elasped_ind if i % math.ceil(count / 20) == 0: print(".", end="", flush=True) print("") print("\tAssigning individually setter (DynamicData)") average_ind = total_time_ind / count print(f"Average: {average_ind} seconds\nMinimum: {min_time_ind} seconds") print( f"Maximum: {max_time_ind} seconds\nTotal: {total_time_ind} seconds") min_time_ind = float("inf") max_time_ind = float("-inf") total_time_ind = 0 data = dds.OctetSeq(array.array("B", [25]) * 600000) for i in range(0, count): start_ind = time.time() for j in range(0, 600000): x = data[j] elasped_ind = time.time() - start_ind min_time_ind = min(min_time_ind, elasped_ind) max_time_ind = max(max_time_ind, elasped_ind) total_time_ind += elasped_ind if i % math.ceil(count / 20) == 0: print(".", end="", flush=True) print("") print("\tAssigning individually getter (OctetSeq)") average_ind = total_time_ind / count print(f"Average: {average_ind} seconds\nMinimum: {min_time_ind} seconds") print( f"Maximum: {max_time_ind} seconds\nTotal: {total_time_ind} seconds") min_time_ind = float("inf") max_time_ind = float("-inf") total_time_ind = 0 data = memoryview(dds.OctetSeq(array.array("B", [25]) * 600000)) for i in range(0, count): start_ind = time.time() for j in range(0, 600000): x = data[j] elasped_ind = time.time() - start_ind min_time_ind = min(min_time_ind, elasped_ind) max_time_ind = max(max_time_ind, elasped_ind) total_time_ind += elasped_ind if i % math.ceil(count / 20) == 0: print(".", end="", flush=True) print("") print("\tAssigning individually getter (OctetSeq in memoryview)") average_ind = total_time_ind / count print(f"Average: {average_ind} seconds\nMinimum: {min_time_ind} seconds") print( f"Maximum: {max_time_ind} seconds\nTotal: {total_time_ind} seconds") min_time_ind = float("inf") max_time_ind = float("-inf") total_time_ind = 0 sample = dds.DynamicData(perf_test_type) sample["myOctSeq"] = array.array("B", [25]) * 600000 for i in range(0, count): start_ind = time.time() loan = sample.loan_value("myOctSeq") data = loan.data for j in range(0, 600000): x = data.get_uint8(j) loan.return_loan() elasped_ind = time.time() - start_ind min_time_ind = min(min_time_ind, elasped_ind) max_time_ind = max(max_time_ind, elasped_ind) total_time_ind += elasped_ind if i % math.ceil(count / 20) == 0: print(".", end="", flush=True) print("") print("\tAssigning individually getter (DynamicData)") average_ind = total_time_ind / count print(f"Average: {average_ind} seconds\nMinimum: {min_time_ind} seconds") print( f"Maximum: {max_time_ind} seconds\nTotal: {total_time_ind} seconds")
def _create_qos_provider(self, profile_file): profile_file_url = "file://{}".format(profile_file) logger.debug("dds profile file: {}", profile_file_url) return dds.QosProvider(profile_file_url)
def run_example(domain_id, sample_count, sensor_id): # 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 participant = dds.DomainParticipant(domain_id) # A Topic has a name and a datatype. Create a Topic named # "ChocolateTemperature" with type Temperature provider = dds.QosProvider(FILE) temperature_type = provider.type("Temperature") lot_status_kind_type = provider.type("LotStatusKind") topic = dds.DynamicData.Topic( participant, "ChocolateTemperature", temperature_type ) # Exercise #2.1: Add a new Topic lot_state_type = provider.type("ChocolateLotState") lot_state_topic = dds.DynamicData.Topic( participant, "ChocolateLotState", lot_state_type ) # A Publisher allows an application to create one or more DataWriters # Publisher QoS is configured in USER_QOS_PROFILES.xml publisher = dds.Publisher(participant) # This DataWriter writes data on Topic "ChocolateTemperature" # DataWriter QoS is configured in USER_QOS_PROFILES.xml writer = dds.DynamicData.DataWriter(publisher, topic) # Create data sample for writing temperature_sample = dds.DynamicData(temperature_type) # Exercise #2.2: Add new DataWriter and data sample lot_state_writer = dds.DynamicData.DataWriter(publisher, lot_state_topic) lot_state_sample = dds.DynamicData(lot_state_type) i = 0 try: while sample_count is None or i < sample_count: # Modify the data to be written here temperature_sample["sensor_id"] = sensor_id # Generate a number x where 30 <= x <= 32 temperature_sample["degrees"] = random.randint(30, 32) # Exercise #2.3: Write data with new ChocolateLotState DataWriter # Note: We're adding a writer but no reader, this exercise can be # viewed using rtiddsspy lot_state_sample["lot_id"] = i % 100 lot_state_sample["lot_status"] = lot_status_kind_type[ "PROCESSING" ].ordinal lot_state_writer.write(lot_state_sample) print(f"Writing ChocolateTemperature, count {i}") writer.write(temperature_sample) # Exercise 1.1: Change this to sleep 100 ms in between writing # temperatures time.sleep(4) i += 1 except KeyboardInterrupt: pass
# works of the Software solely for use with RTI products. The Software is # provided "as is", with no warranty of any type, including any warranty for # fitness for any purpose. RTI is under no obligation to maintain or support # the Software. RTI shall not be liable for any incidental or consequential # damages arising out of the use or inability to use the software. # import rti.connextdds as dds import utils import pytest import pathlib import time FILE = str( pathlib.Path(__file__).parent.absolute()) + "/../xml/PerformanceTester.xml" PROVIDER = dds.QosProvider(FILE) # A type with an x and a y value COORD_TYPE = PROVIDER.type("NonPrimitiveType") def test_sample_creation(): s1 = dds.DynamicData(COORD_TYPE) s1["x"] = 1 s1["y"] = 2 my_dict = {"x": 1, "y": 2} s2 = dds.DynamicData(COORD_TYPE, my_dict) assert s1 == s2
def subscriber_main(domain_id, sample_count, is_cft): participant = dds.DomainParticipant(domain_id) cft_type = dds.QosProvider("cft.xml").type("cft_lib", "cft") topic = dds.DynamicData.Topic(participant, "Example cft", cft_type) if is_cft: # Use a stringmatch CFT str_filter = dds.Filter("name MATCH %0", ["SOME_STRING"]) str_filter.name = dds.Filter.stringmatch_filter_name topic = dds.DynamicData.ContentFilteredTopic(topic, "ContentFilteredTopic", str_filter) # Initial filter is a simple name match print( textwrap.dedent(""" ========================== Using ContentFilteredTopic name MATCH %0 ==========================""")) else: # Default topic does not use a CFT print( textwrap.dedent(""" ========================== Using Normal Topic ==========================""")) reader_qos = dds.QosProvider.default.datareader_qos reader = dds.DynamicData.DataReader(dds.Subscriber(participant), topic, reader_qos) reader.bind_listener(CftListener(), dds.StatusMask.DATA_AVAILABLE) # Change the filter if is_cft: print('Now setting a new filter: name MATCH "EVEN"') topic.append_to_expression_parameter(0, "EVEN") count = 0 while (sample_count == 0) or (count < sample_count): time.sleep(1) if is_cft: if count == 10: # Change the filter again after 10 seconds print( textwrap.dedent(""" ========================== Changing Filter Parameters Append 'ODD' filter ==========================""")) topic.append_to_expression_parameter(0, "ODD") if count == 20: # Change the filter one more time after 20 seconds print( textwrap.dedent(""" ========================== Changing Filter Parameters Remove 'EVEN' filter ==========================""")) topic.remove_from_expression_parameter(0, "EVEN") count += 1