Esempio n. 1
0
def test_clear_all_members():
    data = dds.DynamicData(PRIMITIVES)
    data["myLong"] = 3
    data["myDouble"] = 7.7
    assert data["myLong"] == 3
    assert data["myDouble"] == 7.7

    data.clear_all_members()
    assert data["myLong"] == 0
    assert data["myDouble"] == 0.0

    data = dds.DynamicData(COMPLEX)
    data["myLongSeq"] = list(range(1, 11))
    data["myLongArray"] = array.array("i", range(1, 11))

    for i in range(0, 10):
        assert data[f"myLongSeq[{i}]"] == i + 1
        assert data[f"myLongArray[{i}]"] == i + 1

    member = data.loan_value("myLongSeq")
    member.data.clear_all_members()
    member.return_loan()
    member = data.loan_value("myLongArray")
    member.data.clear_all_members()
    member.return_loan()

    assert len(data["myLongSeq"]) == 0
    for i in range(0, 10):
        assert data[f"myLongArray[{i}]"] == 0
Esempio n. 2
0
    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
Esempio n. 3
0
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 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 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
Esempio n. 6
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
Esempio n. 7
0
def uvn_info(agent):
    uvn_info = dds.DynamicData(agent.participant.types["uvn_info"])
    uvn_info["id.address"] = agent.registry.address
    uvn_info["cells"] = agent.summarize_peers()
    uvn_info["cell_sites"] = agent.summarize_peer_sites()
    if agent.registry.latest_deployment:
        uvn_info["deployment_id"] = agent.registry.latest_deployment.id
        uvn_info["backbone_subnet.address.value"] = ip.ipv4_to_bytes(
            agent.registry.backbone_subnet.network_address)
        uvn_info["backbone_subnet.mask"] = ip.ipv4_netmask_to_cidr(
            agent.registry.backbone_subnet.netmask)
    else:
        uvn_info["deployment_id"] = UvnDefaults["registry"][
            "deployment_bootstrap"]
    if agent.registry.router_subnet:
        uvn_info["router_subnet.address.value"] = ip.ipv4_to_bytes(
            agent.registry.router_subnet.network_address)
        # uvn_info["router_subnet.mask"] = ip.ipv4_netmask_to_cidr(
        #     agent.registry.router_subnet.netmask)
        uvn_info["router_subnet.mask"] = agent.registry.router_subnet.prefixlen
    if agent.registry.backbone_subnet:
        uvn_info["backbone_subnet.address.value"] = ip.ipv4_to_bytes(
            agent.registry.backbone_subnet.network_address)
        uvn_info["backbone_subnet.mask"] = ip.ipv4_netmask_to_cidr(
            agent.registry.backbone_subnet.netmask)

    logger.debug("publishing uvn info:\n{}", uvn_info)
    agent.participant.writer("uvn_info").write(uvn_info)
Esempio n. 8
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
Esempio n. 9
0
def test_clear_member():
    data = dds.DynamicData(COMPLEX)
    data["myOptional"] = 3
    assert data["myOptional"] == 3
    data.clear_optional_member("myOptional")
    assert not data.member_exists("myOptional")

    data["myString"] = "aStringValue"
    assert data["myString"] == "aStringValue"
    data.clear_member(3)
    assert data["myString"] == ""

    data["myStringSeq"] = ["one", "two", "three", "four"]
    assert data["myStringSeq[1]"] == "two"
    data.clear_member(4)
    assert len(data["myStringSeq"]) == 0

    data["myLongSeq"] = list(range(1, 11))
    assert data.get_values(0) == dds.Int32Seq(list(range(1, 11)))
    data.clear_member("myLongSeq")
    assert len(data["myLongSeq"]) == 0

    data["myLongSeq"] = list(range(1, 11))
    assert data.get_values(0) == dds.Int32Seq(list(range(1, 11)))

    seq_member = data.loan_value("myLongSeq")
    seq_member.data.clear_member(3)
    seq_member.return_loan()

    values = data.get_values(0)
    for i in range(0, 10):
        if i == 3:
            assert 0 == values[i]
        else:
            assert i + 1 == values[i]
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)
Esempio n. 11
0
 def _get_peer_backbone_ports(self, cell_name):
     ports = []
     if self.registry.latest_deployment:
         cell_cfg = self.registry.latest_deployment.cell_config(cell_name)
         for bbone in cell_cfg.backbone:
             ipaddr = dds.DynamicData(self.participant.types["ip_address"])
             ipaddr["value"] = ip.ipv4_to_bytes(bbone.addr_local)
             ports.append(ipaddr)
     return ports
Esempio n. 12
0
def deployment(agent, deployment_id, cell_name, installer):
    installer = pathlib.Path(installer)
    with installer.open("rb") as input:
        cell_pkg = dds.DynamicData(agent.participant.types["deployment"])
        cell_pkg["cell.name"] = cell_name
        cell_pkg["cell.uvn.address"] = agent.registry.address
        cell_pkg["id"] = deployment_id
        cell_pkg["package"] = input.read()
        logger.info("pushing installer {} to cell {} [size: {} KB]",
                    installer.name, cell_name,
                    len(list(cell_pkg["package"])) / 1024.0)
        agent.participant.writer("deployment").write(cell_pkg)
Esempio n. 13
0
 def _get_peer_backbone_ports(self, cell_name):
     ports = []
     if self.registry.deployed_cell_config:
         for bbone in self.registry.deployed_cell_config.backbone:
             for p in bbone.peers:
                 if p.name != cell_name:
                     continue
                 ipaddr = dds.DynamicData(
                     self.participant.types["ip_address"])
                 ipaddr["value"] = ip.ipv4_to_bytes(p.addr_remote)
                 ports.append(ipaddr)
     return ports
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")
Esempio n. 15
0
 def summarize_cell_sites(self):
     sites = []
     if self.registry.deployed_cell:
         for s in self._local_sites:
             cell_site = dds.DynamicData(self.participant.types["cell_site"])
             cell_site["cell"] = self.registry.deployed_cell.id.n
             cell_site["nic"] = s["nic"]
             cell_site["subnet.address.value"] = ip.ipv4_to_bytes(s["subnet"].network_address)
             cell_site["subnet.mask"] = ip.ipv4_netmask_to_cidr(s["subnet"].netmask)
             cell_site["endpoint.value"] = ip.ipv4_to_bytes(s["address"])
             cell_site["gw.value"] = ip.ipv4_to_bytes(self._default_gw)
             sites.append(cell_site)
     return sites
Esempio n. 16
0
 def summarize_peer_sites(self):
     sites = []
     for p in self._peers:
         for s in p._remote_sites:
             cell_site = dds.DynamicData(self.participant.types["cell_site"])
             cell_site["cell"] = p.cell.id.n
             cell_site["nic"] = s.nic
             cell_site["subnet.address.value"] = ip.ipv4_to_bytes(s.subnet.network_address)
             cell_site["subnet.mask"] = ip.ipv4_netmask_to_cidr(s.subnet.netmask)
             cell_site["endpoint.value"] = ip.ipv4_to_bytes(s.endpoint)
             cell_site["gw.value"] = ip.ipv4_to_bytes(s.gw)
             sites.append(cell_site)
     return sites
Esempio n. 17
0
 def summarize_peers(self):
     peers = []
     for p in self._peers:
         ports = self._get_peer_backbone_ports(p.cell.id.name)
         if not ports:
             continue
         if len(ports) > 3:
             raise ValueError(f"too many ports: {ports}")
         peer = dds.DynamicData(self.participant.types["cell_peer"])
         peer["name"] = p.cell.id.name
         peer["n"] = p.cell.id.n
         peer["backbone_ports"] = ports
         peers.append(peer)
     return peers
Esempio n. 18
0
def test_union():
    test_union = dds.DynamicData(UNION)
    simple = dds.DynamicData(SIMPLE)
    simple["key"] = 10
    simple["value"] = 20
    test_union["red_green"] = simple

    assert test_union.discriminator_value == ENUM_TYPE["RED"]
    member_value = test_union.get_value(test_union.discriminator_value)

    assert member_value.get_value(0) == 10
    assert member_value.get_value(1) == 20

    with pytest.raises(dds.InvalidArgumentError):
        test_union.get_value("blue")

    test_union["blue"] = 123
    assert test_union.discriminator_value == ENUM_TYPE["BLUE"]
    assert 123 == test_union.get_value(test_union.discriminator_value)

    test_union.clear_member("blue")
    assert test_union.discriminator_value == ENUM_TYPE["BLUE"]
    assert 0 == test_union.get_value(test_union.discriminator_value)
Esempio n. 19
0
 def summarize_nameserver_entries(self):
     entries = []
     for e in self._get_published_nameserver_entries():
         dns_rec = e["record"]
         dns_host = dds.DynamicData(self.participant.types["dns_rec"])
         dns_host["hostname"] = dns_rec.hostname
         dns_host["address.value"] = ip.ipv4_to_bytes(dns_rec.address)
         dns_host["tags"] = list(dns_rec.tags)
         entries.append(dns_host)
         logger.activity("publishing dns entry: {}/{} {}",
             dns_host["hostname"],
             ".".join(map(str, dns_host["address.value"])),
             list(dns_host["tags"]))
     return entries
Esempio n. 20
0
def test_dynamic_data_buffer_numpy():
    np = pytest.importorskip("numpy")
    data = dds.DynamicData(COMPLEX)
    my_array_unidim = np.array([1, 2, 3, 4, 5, 6], np.int32)
    my_array_multidim = np.reshape(np.array([1, 2, 3, 4, 5, 6], np.int32),
                                   (2, 3))
    my_array_short = np.array([1, 2, 3, 4, 5, 6], np.int16)

    data["myLongSeq"] = my_array_unidim
    assert data["myLongSeq[2]"] == 3

    with pytest.raises(TypeError):
        data["myLongSeq"] = my_array_multidim

    with pytest.raises(TypeError):
        data["myLongSeq"] = my_array_short
def publish_temperature(writer, sensor_id):

    # Create temperature sample for writing
    temperature = dds.DynamicData(TEMPERATURE_TYPE)
    try:
        while True:
            # Modify the data to be written here
            temperature["sensor_id"] = sensor_id
            temperature["degrees"] = random.randint(
                30, 32)  # Random value between 30 and 32

            writer.write(temperature)

            time.sleep(0.1)

    except KeyboardInterrupt:
        pass
Esempio n. 22
0
def test_multidim_array():
    data = dds.DynamicData(COMPLEX)

    for i in range(2):
        for j in range(2):
            for k in range(2):
                data[f"myMultiDimArray[{i}, {j}, {k}]"] = i * j * k
                assert (data[f"myMultiDimArray[{i},{j},{k}]"] == i * j * k)

    with pytest.raises(dds.InvalidArgumentError):
        my_val = data[f"myMultiDimArray[0][0][0]"]

    info = data.member_info("myMultiDimArray")
    assert (info.element_count == 8)

    info = data.member_info("myMultiDimArray[0,0,1]")
    assert (info.index == 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)
Esempio n. 24
0
def dns_entries(agent):
    dns_db = dds.DynamicData(agent.participant.types["dns_db"])
    dns_db["cell.name"] = (agent.registry.deployed_cell.id.name
                           if agent.registry.deployed_cell else
                           agent.registry.address)
    dns_db["cell.uvn.address"] = agent.registry.address
    # This fails 1 out of 9 times for yet to identify reasons
    # dns_db["entries"] = agent.summarize_nameserver_entries()
    # This seems to be always working
    for i, e in enumerate(agent._get_published_nameserver_entries()):
        dns_rec = e["record"]
        with dns_db.loan_value("entries") as entries:
            with entries.data.loan_value(i) as d:
                d.data[f"hostname"] = dns_rec.hostname
                d.data[f"address.value"] = ip.ipv4_to_bytes(dns_rec.address)
                d.data[f"tags"] = dns_rec.tags
    agent.participant.writer("dns").write(dns_db)
    logger.info("[dns] pushed {} records", len(dns_db["entries"]))
    return dns_db
Esempio n. 25
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
Esempio n. 26
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
Esempio n. 27
0
def cell_info(agent, cell, cell_cfg):
    cell_info = dds.DynamicData(agent.participant.types["cell_info"])
    cell_info["id.name"] = cell.id.name
    cell_info["id.uvn.address"] = agent.registry.address
    cell_info["pid"] = os.getpid()
    cell_info["status"] = agent._status.value()
    cell_info["peers"] = agent.summarize_peers()
    sites = agent.summarize_cell_sites()
    sites.extend(agent.summarize_peer_sites())
    cell_info["routed_sites"] = sites
    if agent.registry.deployment_id is not None:
        cell_info["deployment_id"] = agent.registry.deployment_id
    if agent._ts_created:
        cell_info["ts_created"] = int(agent._ts_created.millis())
    if agent._ts_loaded:
        cell_info["ts_loaded"] = int(agent._ts_loaded.millis())
    if agent._ts_started:
        cell_info["ts_started"] = int(agent._ts_started.millis())
    logger.debug("publishing cell info:\n{}", cell_info)
    agent.participant.writer("cell_info").write(cell_info)
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)
Esempio n. 29
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
Esempio n. 30
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)