eclipse-cyclonedds / cyclonedds-python

Other
59 stars 47 forks source link

Examples of populating and publishing a sequence data type #168

Closed smnrgrs closed 1 year ago

smnrgrs commented 1 year ago

Are there any examples of how to populate and publish a sequence of some data type using Python? I have been searching but failed to find anything. Thanks.

thijsmie commented 1 year ago

Hi @smnrgrs,

The Python Sequence type doesn't put many restrictions on what you can use to populate it. As long as it has a predefined lenght and is iterable you can use it. In technical terms: it should implement __len__ and __iter__. A good example is a python list, which has a length and is iterable! Let's do a quick example:

from cyclonedds import idl, domain, topic, pub
from cyclonedds.idl.types import sequence
from dataclasses import dataclass

@dataclass
class SequenceHolder:
    seq: sequence[int]

participant = domain.DomainParticipant()
topic = topic.Topic(participant, "test", SequenceHolder)
writer = pub.DataWriter(participant, topic)

writer.write(SequenceHolder(seq=[0,1,2]))
# or even:
writer.write(SequenceHolder(seq=list(range(3))))

I hope that helps!

smnrgrs commented 1 year ago

Thanks for taking the time to reply. My IDL looks something like this:

        @nested
        struct Property_t
        {
            string key;
            string value;
        };
        typedef sequence<Property_t> SeqProperty_t;

        @nested
        struct PropertySet_t
        {
            string key;
            SeqProperty_t properties;
        };

Would you expect any issues trying to publish these nested sequences?

thijsmie commented 1 year ago

Hi @smnrgrs,

That can work just fine. It translates to the following python via idlc -l py file.idl:

@dataclass
@annotate.final
@annotate.nested
class Property_t(idl.IdlStruct, typename="Property_t"):
    key: str
    value: str

SeqProperty_t = types.typedef['SeqProperty_t', types.sequence[Property_t]]

@dataclass
@annotate.final
@annotate.nested
class PropertySet_t(idl.IdlStruct, typename="PropertySet_t"):
    key: str
    properties: SeqProperty_t

You can write these types just as easily as integer lists:

from cyclonedds import  domain, topic, pub

participant = domain.DomainParticipant()
topic = topic.Topic(participant, "test", PropertySet_t)
writer = pub.DataWriter(participant, topic)

writer.write(PropertySet_t(
  key="a_collection_key",
  properties=[
    Property_t(key="something", value="something"),
    Property_t(key="antother", value="something"),
  ]
))
smnrgrs commented 1 year ago

Great, thanks