rustorb-dds 0.1.0__cp39-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,567 @@
1
+ """rustorb-dds: DDS (the OMG Data Distribution Service) with its core in
2
+ Rust.
3
+
4
+ A topic's type is a class declared with :func:`struct` (see
5
+ :mod:`rustorb_dds.types`), or a :class:`DynamicType`, such as one
6
+ :meth:`DomainParticipant.discover_topic_type` learns from the network::
7
+
8
+ import rustorb_dds as dds
9
+
10
+ @dds.struct("HelloWorld::Greeting")
11
+ class Greeting:
12
+ index: dds.uint32
13
+ message: str
14
+
15
+ participant = dds.DomainParticipant(0)
16
+ topic = participant.create_topic("HelloWorldTopic", Greeting)
17
+ writer = participant.create_publisher().create_datawriter(topic)
18
+ writer.write(Greeting(1, "hello"))
19
+
20
+ reader = participant.create_subscriber().create_datareader(topic)
21
+ if reader.wait_for_data(5.0):
22
+ for s in reader.take():
23
+ print(s.data)
24
+ """
25
+
26
+ import dataclasses
27
+ import enum as _enum
28
+ import threading
29
+ import types as _types
30
+ import typing
31
+
32
+ from . import _native
33
+ from .types import * # noqa: F401,F403
34
+ from .types import __all__ as _types_all
35
+ from .types import spec_of, type_of
36
+
37
+ __version__ = "0.1.0"
38
+
39
+ __all__ = _types_all + [
40
+ "DomainParticipant", "Topic", "Publisher", "Subscriber", "DataWriter",
41
+ "DataReader", "Qos", "Sample", "SampleInfo", "StatusMask",
42
+ "DataWriterListener", "DataReaderListener", "Condition",
43
+ "GuardCondition", "StatusCondition", "ReadCondition", "WaitSet",
44
+ ]
45
+
46
+
47
+ class StatusMask(_enum.IntFlag):
48
+ """The communication statuses (DDS 2.2.4.1)."""
49
+
50
+ NONE = 0
51
+ INCONSISTENT_TOPIC = 1 << 0
52
+ OFFERED_DEADLINE_MISSED = 1 << 1
53
+ REQUESTED_DEADLINE_MISSED = 1 << 2
54
+ OFFERED_INCOMPATIBLE_QOS = 1 << 5
55
+ REQUESTED_INCOMPATIBLE_QOS = 1 << 6
56
+ SAMPLE_LOST = 1 << 7
57
+ SAMPLE_REJECTED = 1 << 8
58
+ DATA_ON_READERS = 1 << 9
59
+ DATA_AVAILABLE = 1 << 10
60
+ LIVELINESS_LOST = 1 << 11
61
+ LIVELINESS_CHANGED = 1 << 12
62
+ PUBLICATION_MATCHED = 1 << 13
63
+ SUBSCRIPTION_MATCHED = 1 << 14
64
+ ALL = 0x7FE7
65
+
66
+
67
+ @dataclasses.dataclass
68
+ class Qos:
69
+ """The QoS of a writer or reader; None leaves a policy at its
70
+ default. Times are in seconds.
71
+
72
+ - ``reliability``: ``"reliable"`` (a writer's default) or
73
+ ``"best_effort"`` (a reader's default); ``max_blocking_time``.
74
+ - ``history``: the depth of KEEP_LAST (1 by default), or
75
+ ``"keep_all"``.
76
+ - ``durability``: ``"volatile"`` (default), ``"transient_local"``.
77
+ - ``deadline``: the period.
78
+ - ``liveliness``: ``"automatic"`` (default),
79
+ ``"manual_by_participant"``, ``"manual_by_topic"``;
80
+ ``lease_duration`` (None: infinite).
81
+ - ``data_representation``: ``["xcdr"]``, ``["xcdr2"]``...
82
+ - ``user_data``: bytes.
83
+ - ``max_samples``, ``max_instances``, ``max_samples_per_instance``.
84
+ - ``autodispose_unregistered_instances`` (writers; True by default).
85
+ """
86
+
87
+ reliability: typing.Optional[str] = None
88
+ max_blocking_time: typing.Optional[float] = None
89
+ history: typing.Union[int, str, None] = None
90
+ durability: typing.Optional[str] = None
91
+ deadline: typing.Optional[float] = None
92
+ liveliness: typing.Optional[str] = None
93
+ lease_duration: typing.Optional[float] = None
94
+ data_representation: typing.Optional[typing.List[str]] = None
95
+ user_data: typing.Optional[bytes] = None
96
+ max_samples: typing.Optional[int] = None
97
+ max_instances: typing.Optional[int] = None
98
+ max_samples_per_instance: typing.Optional[int] = None
99
+ autodispose_unregistered_instances: typing.Optional[bool] = None
100
+
101
+ def _dict(self):
102
+ return {k: v for k, v in dataclasses.asdict(self).items() if v is not None}
103
+
104
+
105
+ def _qos(qos):
106
+ if qos is None:
107
+ return None
108
+ if isinstance(qos, Qos):
109
+ return qos._dict()
110
+ if isinstance(qos, dict):
111
+ return dict(qos)
112
+ raise TypeError("a QoS is a rustorb_dds.Qos or a dict")
113
+
114
+
115
+ def _status(d):
116
+ return _types.SimpleNamespace(**d)
117
+
118
+
119
+ @dataclasses.dataclass(frozen=True)
120
+ class SampleInfo:
121
+ """The information about a sample (DDS 2.2.2.5.5)."""
122
+
123
+ sample_state: str
124
+ view_state: str
125
+ instance_state: str
126
+ valid_data: bool
127
+ source_timestamp: typing.Optional[float]
128
+ instance_handle: str
129
+ publication_handle: str
130
+ sequence_number: int
131
+ disposed_generation_count: int
132
+ no_writers_generation_count: int
133
+ sample_rank: int
134
+ generation_rank: int
135
+ absolute_generation_rank: int
136
+
137
+
138
+ class Sample(typing.NamedTuple):
139
+ """A sample: ``data`` is None when the sample only tells a change of
140
+ the instance state (``info.valid_data`` is False)."""
141
+
142
+ data: typing.Any
143
+ info: SampleInfo
144
+
145
+
146
+ class DomainParticipant:
147
+ """A participant in the domain ``domain_id``. ``localhost`` keeps
148
+ its traffic on the loopback interface."""
149
+
150
+ def __init__(self, domain_id=0, localhost=False):
151
+ self._native = _native.DomainParticipant(domain_id, localhost)
152
+
153
+ @property
154
+ def domain_id(self):
155
+ return self._native.domain_id
156
+
157
+ @property
158
+ def guid(self):
159
+ return self._native.guid
160
+
161
+ def create_topic(self, name, type): # noqa: A002 - the DDS name
162
+ """A topic named ``name`` of ``type``: a class made with
163
+ :func:`struct` or :func:`union`, or a :class:`DynamicType`."""
164
+ spec = spec_of(type)
165
+ return Topic(self._native.create_topic(name, type_of(type)), spec)
166
+
167
+ def discover_topic_type(self, topic_name, timeout=5.0):
168
+ """The type remote endpoints of ``topic_name`` announce, fetched
169
+ with TypeLookup when needed, or None after ``timeout`` seconds."""
170
+ return self._native.discover_topic_type(topic_name, timeout)
171
+
172
+ def create_publisher(self, partition=None):
173
+ """A publisher in the partitions ``partition`` (a list of names,
174
+ with ``*`` and ``?`` wildcards)."""
175
+ qos = {"partition": list(partition)} if partition else None
176
+ return Publisher(self._native.create_publisher(qos), self)
177
+
178
+ def create_subscriber(self, partition=None):
179
+ """A subscriber in the partitions ``partition``."""
180
+ qos = {"partition": list(partition)} if partition else None
181
+ return Subscriber(self._native.create_subscriber(qos), self)
182
+
183
+ def assert_liveliness(self):
184
+ self._native.assert_liveliness()
185
+
186
+ def discovered_participants(self):
187
+ """The GUIDs of the remote participants discovered."""
188
+ return self._native.discovered_participants()
189
+
190
+
191
+ class Topic:
192
+ """A topic: its name and its type."""
193
+
194
+ def __init__(self, native, spec):
195
+ self._native = native
196
+ self._spec = spec
197
+
198
+ @property
199
+ def name(self):
200
+ return self._native.name
201
+
202
+ @property
203
+ def type_name(self):
204
+ return self._native.type_name
205
+
206
+ @property
207
+ def type(self): # noqa: A003 - the DDS name
208
+ """The :class:`DynamicType` of the topic."""
209
+ return self._native.type
210
+
211
+ def inconsistent_topic_status(self):
212
+ return _status(self._native.inconsistent_topic_status())
213
+
214
+
215
+ class Publisher:
216
+ def __init__(self, native, participant):
217
+ self._native = native
218
+ self.participant = participant
219
+
220
+ def create_datawriter(self, topic, qos=None, listener=None,
221
+ mask=StatusMask.ALL):
222
+ """A writer of ``topic`` with ``qos`` (a :class:`Qos` or dict)."""
223
+ e = DataWriter(None, topic)
224
+ native = self._native.create_datawriter(
225
+ topic._native, _qos(qos),
226
+ None if listener is None else _callback(e, listener), int(mask))
227
+ _created(e, native)
228
+ return e
229
+
230
+
231
+ class Subscriber:
232
+ def __init__(self, native, participant):
233
+ self._native = native
234
+ self.participant = participant
235
+
236
+ def create_datareader(self, topic, qos=None, listener=None,
237
+ mask=StatusMask.ALL):
238
+ """A reader of ``topic`` with ``qos`` (a :class:`Qos` or dict)."""
239
+ e = DataReader(None, topic)
240
+ native = self._native.create_datareader(
241
+ topic._native, _qos(qos),
242
+ None if listener is None else _callback(e, listener), int(mask))
243
+ _created(e, native)
244
+ return e
245
+
246
+
247
+ class DataWriterListener:
248
+ """Override the methods for the statuses to be told of; each is called
249
+ on a thread of the participant with the writer and the status."""
250
+
251
+ def on_publication_matched(self, writer, status):
252
+ pass
253
+
254
+ def on_offered_incompatible_qos(self, writer, status):
255
+ pass
256
+
257
+ def on_liveliness_lost(self, writer, status):
258
+ pass
259
+
260
+ def on_offered_deadline_missed(self, writer, status):
261
+ pass
262
+
263
+
264
+ class DataReaderListener:
265
+ """Override the methods for the statuses to be told of; each is called
266
+ on a thread of the participant with the reader (and the status)."""
267
+
268
+ def on_data_available(self, reader):
269
+ pass
270
+
271
+ def on_subscription_matched(self, reader, status):
272
+ pass
273
+
274
+ def on_requested_incompatible_qos(self, reader, status):
275
+ pass
276
+
277
+ def on_liveliness_changed(self, reader, status):
278
+ pass
279
+
280
+ def on_requested_deadline_missed(self, reader, status):
281
+ pass
282
+
283
+ def on_sample_lost(self, reader, status):
284
+ pass
285
+
286
+ def on_sample_rejected(self, reader, status):
287
+ pass
288
+
289
+
290
+ def _callback(entity, listener):
291
+ def call(event, status):
292
+ f = getattr(listener, "on_" + event, None)
293
+ if f is None:
294
+ return
295
+ with entity._lock:
296
+ if entity._native is None:
297
+ # Called while the entity is created: told once it is.
298
+ entity._early.append((f, status))
299
+ return
300
+ if status is None:
301
+ f(entity)
302
+ else:
303
+ f(entity, _status(status))
304
+
305
+ return call
306
+
307
+
308
+ def _created(entity, native):
309
+ """Sets the native entity of ``entity``, and calls its listener for
310
+ what happened while it was created."""
311
+ with entity._lock:
312
+ entity._native = native
313
+ early, entity._early = entity._early, []
314
+ for f, status in early:
315
+ if status is None:
316
+ f(entity)
317
+ else:
318
+ f(entity, _status(status))
319
+
320
+
321
+ class DataWriter:
322
+ """A writer. A sample is an instance of the topic's class (or a dict
323
+ of its members), or, for a :class:`DynamicType`, a dict."""
324
+
325
+ def __init__(self, native, topic):
326
+ self._native = native
327
+ self._lock = threading.Lock()
328
+ self._early = []
329
+ self.topic = topic
330
+ self._encode = topic._spec.encode
331
+
332
+ @property
333
+ def guid(self):
334
+ return self._native.guid
335
+
336
+ def write(self, sample, timestamp=None):
337
+ """Writes ``sample``; ``timestamp`` (seconds since the epoch) is
338
+ its source timestamp, now by default."""
339
+ self._native.write(self._encode(sample), timestamp)
340
+
341
+ def register_instance(self, sample):
342
+ """Registers the instance of the key of ``sample``; returns its
343
+ handle."""
344
+ return self._native.register_instance(self._encode(sample))
345
+
346
+ def unregister_instance(self, sample, timestamp=None):
347
+ self._native.unregister_instance(self._encode(sample), timestamp)
348
+
349
+ def dispose(self, sample, timestamp=None):
350
+ self._native.dispose(self._encode(sample), timestamp)
351
+
352
+ def lookup_instance(self, sample):
353
+ """The handle of the instance of the key of ``sample``, or None."""
354
+ return self._native.lookup_instance(self._encode(sample))
355
+
356
+ def wait_for_acknowledgments(self, timeout):
357
+ """Waits until the reliable readers acknowledged all the samples
358
+ written (``TimeoutError`` after ``timeout`` seconds)."""
359
+ self._native.wait_for_acknowledgments(timeout)
360
+
361
+ def wait_for_subscriptions(self, count=1, timeout=5.0):
362
+ """Waits until ``count`` readers match; False on timeout."""
363
+ return self._native.wait_for_subscriptions(count, timeout)
364
+
365
+ def matched_subscriptions(self):
366
+ return self._native.matched_subscriptions()
367
+
368
+ def assert_liveliness(self):
369
+ self._native.assert_liveliness()
370
+
371
+ def publication_matched_status(self):
372
+ return _status(self._native.publication_matched_status())
373
+
374
+ def offered_incompatible_qos_status(self):
375
+ return _status(self._native.offered_incompatible_qos_status())
376
+
377
+ def liveliness_lost_status(self):
378
+ return _status(self._native.liveliness_lost_status())
379
+
380
+ def offered_deadline_missed_status(self):
381
+ return _status(self._native.offered_deadline_missed_status())
382
+
383
+ def status_changes(self):
384
+ return StatusMask(self._native.status_changes())
385
+
386
+ @property
387
+ def status_condition(self):
388
+ return StatusCondition(self._native.status_condition())
389
+
390
+ def set_listener(self, listener, mask=StatusMask.ALL):
391
+ """Sets a :class:`DataWriterListener` for the statuses in
392
+ ``mask``; None clears it."""
393
+ if listener is None:
394
+ self._native.clear_listener()
395
+ else:
396
+ self._native.set_listener(_callback(self, listener), int(mask))
397
+
398
+
399
+ _ANY = None
400
+
401
+
402
+ class DataReader:
403
+ """A reader. Samples are instances of the topic's class or, for a
404
+ :class:`DynamicType`, plain values (dicts for structs)."""
405
+
406
+ def __init__(self, native, topic):
407
+ self._native = native
408
+ self._lock = threading.Lock()
409
+ self._early = []
410
+ self.topic = topic
411
+ self._decode = topic._spec.decode
412
+
413
+ @property
414
+ def guid(self):
415
+ return self._native.guid
416
+
417
+ def _samples(self, v):
418
+ return [Sample(None if d is None else self._decode(d), SampleInfo(**i))
419
+ for d, i in v]
420
+
421
+ def take(self, sample_states=_ANY, view_states=_ANY, instance_states=_ANY,
422
+ instance=None):
423
+ """Takes the samples in the given states (lists of state names:
424
+ ``"read"``/``"not_read"``, ``"new"``/``"not_new"``, ``"alive"``/
425
+ ``"not_alive_disposed"``/``"not_alive_no_writers"``; None for
426
+ any), or those of the ``instance`` handle."""
427
+ return self._samples(self._native.select(
428
+ True, sample_states, view_states, instance_states, instance))
429
+
430
+ def read(self, sample_states=_ANY, view_states=_ANY, instance_states=_ANY,
431
+ instance=None):
432
+ """Like :meth:`take`, leaving the samples in the reader."""
433
+ return self._samples(self._native.select(
434
+ False, sample_states, view_states, instance_states, instance))
435
+
436
+ def take_w_condition(self, condition):
437
+ return self._samples(self._native.select_w_condition(True, condition._native))
438
+
439
+ def read_w_condition(self, condition):
440
+ return self._samples(self._native.select_w_condition(False, condition._native))
441
+
442
+ def lookup_instance(self, sample):
443
+ """The handle of the instance of the key of ``sample``, or None."""
444
+ return self._native.lookup_instance(self.topic._spec.encode(sample))
445
+
446
+ def get_key_value(self, instance):
447
+ """A sample holding the key of the ``instance`` handle, or None."""
448
+ v = self._native.get_key_value(instance)
449
+ return None if v is None else self._decode(v)
450
+
451
+ def wait_for_data(self, timeout=5.0):
452
+ """Waits until there are samples to take; False on timeout."""
453
+ return self._native.wait_for_data(timeout)
454
+
455
+ def wait_for_publications(self, count=1, timeout=5.0):
456
+ """Waits until ``count`` writers match; False on timeout."""
457
+ return self._native.wait_for_publications(count, timeout)
458
+
459
+ def matched_publications(self):
460
+ return self._native.matched_publications()
461
+
462
+ def subscription_matched_status(self):
463
+ return _status(self._native.subscription_matched_status())
464
+
465
+ def requested_incompatible_qos_status(self):
466
+ return _status(self._native.requested_incompatible_qos_status())
467
+
468
+ def liveliness_changed_status(self):
469
+ return _status(self._native.liveliness_changed_status())
470
+
471
+ def requested_deadline_missed_status(self):
472
+ return _status(self._native.requested_deadline_missed_status())
473
+
474
+ def sample_lost_status(self):
475
+ return _status(self._native.sample_lost_status())
476
+
477
+ def sample_rejected_status(self):
478
+ return _status(self._native.sample_rejected_status())
479
+
480
+ def status_changes(self):
481
+ return StatusMask(self._native.status_changes())
482
+
483
+ @property
484
+ def status_condition(self):
485
+ return StatusCondition(self._native.status_condition())
486
+
487
+ def create_readcondition(self, sample_states=_ANY, view_states=_ANY,
488
+ instance_states=_ANY):
489
+ """A condition true while the reader holds samples in the given
490
+ states."""
491
+ return ReadCondition(self._native.create_readcondition(
492
+ sample_states, view_states, instance_states))
493
+
494
+ def set_listener(self, listener, mask=StatusMask.ALL):
495
+ """Sets a :class:`DataReaderListener` for the statuses in
496
+ ``mask``; None clears it."""
497
+ if listener is None:
498
+ self._native.clear_listener()
499
+ else:
500
+ self._native.set_listener(_callback(self, listener), int(mask))
501
+
502
+
503
+ class Condition:
504
+ """A condition a :class:`WaitSet` waits for."""
505
+
506
+ def __init__(self, native):
507
+ self._native = native
508
+
509
+ @property
510
+ def trigger_value(self):
511
+ return self._native.trigger_value
512
+
513
+ def __eq__(self, other):
514
+ return isinstance(other, Condition) and self._native == other._native
515
+
516
+ __hash__ = None
517
+
518
+
519
+ class GuardCondition(Condition):
520
+ """A condition the application triggers."""
521
+
522
+ def __init__(self):
523
+ super().__init__(_native.Condition.guard())
524
+
525
+ def set_trigger_value(self, value):
526
+ self._native.set_trigger_value(value)
527
+
528
+
529
+ class StatusCondition(Condition):
530
+ """True while a status in its enabled statuses has changed."""
531
+
532
+ @property
533
+ def enabled_statuses(self):
534
+ return StatusMask(self._native.enabled_statuses)
535
+
536
+ def set_enabled_statuses(self, mask):
537
+ self._native.set_enabled_statuses(int(mask))
538
+
539
+
540
+ class ReadCondition(Condition):
541
+ """True while its reader holds samples in its states."""
542
+
543
+
544
+ class WaitSet:
545
+ """Waits for conditions."""
546
+
547
+ def __init__(self):
548
+ self._native = _native.WaitSet()
549
+ self._conditions = []
550
+
551
+ def attach_condition(self, condition):
552
+ self._native.attach_condition(condition._native)
553
+ if condition not in self._conditions:
554
+ self._conditions.append(condition)
555
+
556
+ def detach_condition(self, condition):
557
+ self._native.detach_condition(condition._native)
558
+ self._conditions.remove(condition)
559
+
560
+ @property
561
+ def conditions(self):
562
+ return list(self._conditions)
563
+
564
+ def wait(self, timeout):
565
+ """Waits until a condition is true; returns those that are, or
566
+ raises ``TimeoutError`` after ``timeout`` seconds."""
567
+ return [self._conditions[i] for i in self._native.wait(timeout)]
Binary file