Пример #1
0
def test_find_extensions():
    p_qos = dds.DomainParticipantQos()
    p_qos << dds.EntityName("MyParticipant1")
    assert p_qos.participant_name.name == "MyParticipant1"

    p1 = dds.DomainParticipant(DOMAIN_ID, p_qos)
    assert p1.qos.participant_name.name == "MyParticipant1"

    p_qos << dds.EntityName("MyParticipant2")
    p2 = dds.DomainParticipant(DOMAIN_ID, p_qos)

    assert dds.DomainParticipant.find("MyParticipant1") == p1
    assert dds.DomainParticipant.find("MyParticipant2") == p2
    assert dds.DomainParticipant.find("MyParticipant3") == None
Пример #2
0
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 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
Пример #4
0
def test_data_reader_writer():
    with dds.DomainParticipant(0) as participant:
        topic = dds.StringTopicType.Topic(participant, "pub_sub_example")
        # Create qos for both, add reliable and keep all
        writer_qos = participant.implicit_publisher.default_datawriter_qos
        writer_qos << dds.Reliability.reliable()
        writer_qos << dds.History.keep_all()
        writer_qos << dds.Durability.transient_local()

        # Create the reader qos
        reader_qos = participant.implicit_subscriber.default_datareader_qos
        reader_qos << dds.Reliability.reliable()
        reader_qos << dds.History.keep_all()
        reader_qos << dds.Durability.transient_local()
        writer = dds.StringTopicType.DataWriter(participant.implicit_publisher,
                                                topic, writer_qos)
        reader = dds.StringTopicType.DataReader(
            participant.implicit_subscriber, topic, reader_qos)
        # Need to have reader check for writer and vice versa here
        # writer.wait_for_acknowledgments(1000)
        count = 0

        for i in range(1, 6):
            writer.write("Hello World " + str(i))
        while len(reader.read()) < 5:
            time.sleep(0.001)
        for x, y in reader.read():
            count += 1
            assert x == f"Hello World {count}"

        assert count == 5
Пример #5
0
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
Пример #6
0
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)
Пример #7
0
def test_sending_dict():
    s1 = dds.DynamicData(COORD_TYPE)
    s1["x"] = 1
    s1["y"] = 2

    my_dict = {"x": 1, "y": 2}
    with dds.DomainParticipant(0) as participant:
        topic = dds.DynamicData.Topic(participant, "dictionary_test",
                                      COORD_TYPE)
        # Create qos for both, add reliable and keep all
        writer_qos = participant.implicit_publisher.default_datawriter_qos
        writer_qos << dds.Reliability.reliable()
        writer_qos << dds.History.keep_all()
        writer_qos << dds.Durability.transient_local()

        # Create the reader qos
        reader_qos = participant.implicit_subscriber.default_datareader_qos
        reader_qos << dds.Reliability.reliable()
        reader_qos << dds.History.keep_all()
        reader_qos << dds.Durability.transient_local()
        writer = dds.DynamicData.DataWriter(participant.implicit_publisher,
                                            topic, writer_qos)
        reader = dds.DynamicData.DataReader(participant.implicit_subscriber,
                                            topic, reader_qos)

        writer.write(my_dict)
        while len(reader.read()) < 1:
            time.sleep(0.001)
        for s2 in reader.take():
            print(s2.data)
            print(type(s2.data))
            # Makes for easy debugging
            assert type(s2.data) == type(s1)
            assert s2.data == s1
Пример #8
0
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
Пример #9
0
def test_set_qos_exception():
    p = dds.DomainParticipant(DOMAIN_ID, dds.DomainParticipantQos())
    qos = p.qos
    d = dds.Duration(77)
    db = dds.Database()
    db.shutdown_cleanup_period = d
    qos << db
    with pytest.raises(dds.ImmutablePolicyError):
        p.qos = qos
Пример #10
0
def test_participant_creation_w_qos():
    user_data_values = [10, 11, 12, 13, 14, 15]
    qos = dds.DomainParticipantQos()
    qos.user_data.value = user_data_values
    qos.database.shutdown_cleanup_period = dds.Duration.from_milliseconds(100)
    p = dds.DomainParticipant(DOMAIN_ID, qos)
    retrieved_qos = p.qos
    assert retrieved_qos.user_data.value == user_data_values
    assert (
        retrieved_qos.database.shutdown_cleanup_period
        == dds.Duration.from_milliseconds(100)
    )
Пример #11
0
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")
Пример #12
0
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
Пример #13
0
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
Пример #14
0
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)
Пример #15
0
def test_retain_for_listener(set_after):
    listener = dds.NoOpDomainParticipantListener()
    if set_after:
        p = utils.create_participant()
        p.bind_listener(listener, dds.StatusMask.none())
    else:
        p = dds.DomainParticipant(DOMAIN_ID, dds.DomainParticipantQos(), listener)

    def inner():
        with dds.DomainParticipant.find(DOMAIN_ID) as new_p:
            assert new_p != None
            new_p.bind_listener(None, dds.StatusMask.none())

    inner()
    assert dds.DomainParticipant.find(DOMAIN_ID) == None
Пример #16
0
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)
Пример #18
0
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)

    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)
Пример #20
0
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
Пример #21
0
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
Пример #22
0
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
Пример #23
0
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 __init__(self, domain_id, use_dynamic_data, use_qos_object,
                 use_custom_topic, use_replier_cft, use_pub_sub_args,
                 use_callback_funcs, use_simple_replier):
        qos = dds.DomainParticipantQos()
        qos.database.shutdown_cleanup_period = dds.Duration.from_milliseconds(
            100)
        self._participant = dds.DomainParticipant(domain_id, qos)
        if use_dynamic_data:
            self._type = get_keyed_string_dynamic_type()
            self.create_data_fnc = create_dynamic_rr_data
            self.parse_data_fnc = parse_dynamic_rr_data
            self.copy_sample_fnc = copy_dynamic_sample
            create_topic_func = create_dynamic_topic
        else:
            self._type = type_cls = dds.KeyedStringTopicType
            self.create_data_fnc = create_rr_data
            self.parse_data_fnc = parse_rr_data
            self.copy_sample_fnc = copy_sample
            create_topic_func = create_topic

        service_name = 'Test'

        if use_qos_object:
            request_writer_qos = request.Requester.default_writer_qos
            request_reader_qos = request.Replier.default_reader_qos
            reply_writer_qos = request.Replier.default_writer_qos
            reply_reader_qos = request.Requester.default_reader_qos
        else:
            request_writer_qos = request_reader_qos = reply_writer_qos = reply_reader_qos = None

        if use_custom_topic:
            # Test with custom Topic object
            request_topic = create_topic_func(self._participant, 'TestRequest')
            # Test with custom string Topic name
            reply_topic = 'TestReply'
        else:
            request_topic = reply_topic = None

        if use_replier_cft:
            replier_filter = dds.Filter("NOT (key MATCH 'filtered')")
            request_reader_topic = create_topic_func(
                self._participant,
                'TestRequest') if request_topic is None else request_topic
            if isinstance(self._type, dds.DynamicType):
                request_reader_topic = dds.DynamicData.ContentFilteredTopic(
                    request_reader_topic, 'request_cft', replier_filter)
            else:
                request_reader_topic = dds.KeyedStringTopicType.ContentFilteredTopic(
                    request_reader_topic, 'request_cft', replier_filter)
        else:
            request_reader_topic = request_topic

        if use_pub_sub_args:
            publisher = dds.Publisher(self._participant)
            subscriber = dds.Subscriber(self._participant)
        else:
            publisher = subscriber = None

        self._cb = use_callback_funcs
        self._request_queue = queue.Queue()
        self._reply_queue = queue.Queue()
        if use_callback_funcs:

            def replier_callback(replier):
                for sample in (s for s in replier.take_requests()
                               if s.info.valid):
                    self._request_queue.put(self.copy_sample_fnc(sample))

            def requester_callback(requester):
                for sample in (s for s in requester.take_replies()
                               if s.info.valid):
                    self._reply_queue.put(self.copy_sample_fnc(sample))
        else:
            replier_callback = requester_callback = None

        self._requester = request.Requester(self._type, self._type,
                                            self._participant, service_name,
                                            request_topic, reply_topic,
                                            request_writer_qos,
                                            reply_reader_qos, publisher,
                                            subscriber, requester_callback)

        self._simple = use_simple_replier
        if use_simple_replier:

            def simple_replier_callback(request):
                key, value = self.parse_data_fnc(request)
                reply = self.create_data_fnc(key, value + ' reply')
                return reply

            self._replier = request.SimpleReplier(
                self._type, self._type, self._participant,
                simple_replier_callback, service_name, request_reader_topic,
                reply_topic, reply_writer_qos, request_reader_qos, publisher,
                subscriber)
        else:
            self._replier = request.Replier(self._type, self._type,
                                            self._participant, service_name,
                                            request_reader_topic, reply_topic,
                                            reply_writer_qos,
                                            request_reader_qos, publisher,
                                            subscriber, replier_callback)
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
Пример #26
0
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
Пример #27
0
def test_participant_creation_failure():
    qos = dds.DomainParticipantQos()
    qos.resource_limits.type_object_max_serialized_length = -2
    with pytest.raises(dds.Error):
        dds.DomainParticipant(0, qos)
Пример #28
0
def test_participant_creation_w_listener():
    l = dds.NoOpDomainParticipantListener()
    p = dds.DomainParticipant(DOMAIN_ID, dds.DomainParticipantQos(), l)
    assert p.listener == l
    p.close()
Пример #29
0
def test_participant_default_creation():
    p = dds.DomainParticipant(DOMAIN_ID)
    assert p.domain_id == DOMAIN_ID
Пример #30
0
def test_participant_creation_w_default_qos():
    p = dds.DomainParticipant(DOMAIN_ID, dds.DomainParticipantQos())
    assert p.domain_id == DOMAIN_ID
    event_count = p.qos.event.max_count
    assert event_count == dds.Event().max_count