1use std::sync::Arc;
4use std::time::{Duration, Instant};
5
6use rustorb_rtps::sedp::EndpointData;
7use rustorb_rtps::{Guid, SampleIdentity, Time, entity_kind};
8use rustorb_typesupport::{ByteOrder, Encoding};
9
10use crate::condition::StatusCondition;
11use crate::error::{Error, Result};
12use crate::instance::InstanceHandle;
13use crate::listener::{DataWriterListener, PublisherEntity, PublisherListener};
14use crate::loan::{LoanCheck, PlainType, WriteInner, WriteLoan};
15use crate::participant::{Shared, WriteOp, WriterEvent, WriterListener, WriterState};
16use crate::qos::{
17 DataWriterQos, DurabilityKind, PublisherQos, data_representation, duration_to_rtps,
18};
19use crate::status::{
20 DeadlineMissedStatus, IncompatibleQosStatus, LivelinessLostStatus, MatchedStatus, StatusMask,
21};
22use crate::topic::Topic;
23use crate::typed::SampleType;
24
25#[derive(Clone)]
27pub struct Publisher {
28 shared: Arc<Shared>,
29 entity: Arc<PublisherEntity>,
30}
31
32impl std::fmt::Debug for Publisher {
33 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34 f.debug_struct("Publisher").finish_non_exhaustive()
35 }
36}
37
38impl Publisher {
39 pub(crate) fn new(shared: Arc<Shared>, entity: Arc<PublisherEntity>) -> Self {
40 Publisher { shared, entity }
41 }
42
43 pub fn qos(&self) -> &PublisherQos {
45 &self.entity.qos
46 }
47
48 pub fn set_listener(&self, listener: impl PublisherListener + 'static, mask: StatusMask) {
53 *self
54 .entity
55 .listener
56 .lock()
57 .unwrap_or_else(|e| e.into_inner()) = Some((Arc::new(listener), mask));
58 }
59
60 pub fn clear_listener(&self) {
62 *self
63 .entity
64 .listener
65 .lock()
66 .unwrap_or_else(|e| e.into_inner()) = None;
67 }
68
69 pub fn create_datawriter<T>(&self, topic: &Topic<T>) -> Result<DataWriter<T>> {
72 self.create_datawriter_with_qos(topic, DataWriterQos::default())
73 }
74
75 pub fn create_datawriter_with_qos<T>(
87 &self,
88 topic: &Topic<T>,
89 qos: DataWriterQos,
90 ) -> Result<DataWriter<T>> {
91 self.create(topic, qos, None, |_| {})
92 }
93
94 pub(crate) fn create_datawriter_with<T>(
97 &self,
98 topic: &Topic<T>,
99 qos: DataWriterQos,
100 f: impl FnOnce(&mut EndpointData),
101 ) -> Result<DataWriter<T>> {
102 self.create(topic, qos, None, f)
103 }
104
105 pub fn create_datawriter_with_listener<T: 'static>(
109 &self,
110 topic: &Topic<T>,
111 qos: DataWriterQos,
112 listener: impl DataWriterListener<T> + 'static,
113 mask: StatusMask,
114 ) -> Result<DataWriter<T>> {
115 let encoding = encoding_of(&qos)?;
116 let l = writer_listener(encoding, topic.samples.clone(), listener);
117 self.create(topic, qos, Some((l, mask)), |_| {})
118 }
119
120 fn create<T>(
121 &self,
122 topic: &Topic<T>,
123 qos: DataWriterQos,
124 listener: Option<(WriterListener, StatusMask)>,
125 f: impl FnOnce(&mut EndpointData),
126 ) -> Result<DataWriter<T>> {
127 let keyed = topic.samples.keyed();
128 let kind = if keyed {
129 entity_kind::USER_WRITER_WITH_KEY
130 } else {
131 entity_kind::USER_WRITER_NO_KEY
132 };
133 let encoding = encoding_of(&qos)?;
134 let guid = self.shared.new_guid(kind)?;
135 let type_name = topic.type_name();
136 let mut data = EndpointData::writer(guid, topic.name(), type_name);
137 data.type_information = self.shared.type_information(type_name)?;
138 data.data_representation = qos.data_representation.clone();
139 data.reliability = qos.reliability.to_rtps();
140 data.durability = qos.durability;
141 if qos.durability >= DurabilityKind::Transient {
142 data.durability_service = Some(qos.durability_service.to_rtps());
143 }
144 data.deadline = duration_to_rtps(qos.deadline);
145 data.liveliness = qos.liveliness.to_rtps();
146 data.user_data = qos.user_data.clone();
147 data.data_tags = qos.data_tags.clone();
148 data.partitions = self.entity.qos.partition.clone();
149 f(&mut data);
150 self.shared.add_writer(
151 data,
152 qos,
153 topic.samples.key_ops(),
154 listener,
155 self.entity.clone(),
156 )?;
157 Ok(DataWriter {
158 shared: self.shared.clone(),
159 guid,
160 encoding,
161 owned: true,
162 samples: topic.samples.clone(),
163 loan: Arc::default(),
164 })
165 }
166}
167
168pub struct DataWriter<T> {
175 pub(crate) shared: Arc<Shared>,
176 pub(crate) guid: Guid,
177 encoding: Encoding,
179 owned: bool,
182 samples: Arc<dyn SampleType<T>>,
183 #[cfg_attr(not(feature = "shm"), allow(dead_code))]
185 loan: Arc<LoanCheck>,
186}
187
188impl<T> std::fmt::Debug for DataWriter<T> {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 f.debug_struct("DataWriter")
191 .field("guid", &self.guid)
192 .field("type_name", &self.samples.type_name())
193 .finish()
194 }
195}
196
197impl<T> DataWriter<T> {
198 pub fn guid(&self) -> Guid {
200 self.guid
201 }
202
203 pub fn write(&self, sample: &T) -> Result<()> {
217 self.write_w_timestamp(sample, Time::now())
218 }
219
220 pub fn write_w_timestamp(&self, sample: &T, timestamp: Time) -> Result<()> {
222 self.write_w_params(
223 sample,
224 &WriteParams {
225 source_timestamp: Some(timestamp),
226 ..WriteParams::default()
227 },
228 )
229 .map(|_| ())
230 }
231
232 pub fn write_w_params(&self, sample: &T, params: &WriteParams) -> Result<SampleIdentity> {
236 self.write_mapped(sample, params, |p| p)
237 }
238
239 pub(crate) fn write_mapped(
242 &self,
243 sample: &T,
244 params: &WriteParams,
245 map: impl FnOnce(Vec<u8>) -> Vec<u8>,
246 ) -> Result<SampleIdentity> {
247 let payload = self
248 .samples
249 .to_payload(sample, self.encoding, ByteOrder::NATIVE)?;
250 let payload = map(payload);
251 let sequence_number = self.shared.write(
252 self.guid,
253 self.samples.instance_of(sample)?,
254 WriteOp::Value(
255 payload.into(),
256 params.related_sample_identity,
257 params.directed_to,
258 ),
259 params.source_timestamp.unwrap_or_else(Time::now),
260 )?;
261 Ok(SampleIdentity {
262 writer_guid: self.guid,
263 sequence_number,
264 })
265 }
266
267 pub fn register_instance(&self, instance: &T) -> Result<InstanceHandle> {
271 let h = self.samples.instance_of(instance)?;
272 self.shared.register_instance(&self.guid, h)?;
273 Ok(h)
274 }
275
276 pub fn unregister_instance(&self, instance: &T) -> Result<()> {
284 self.unregister_instance_w_timestamp(instance, Time::now())
285 }
286
287 pub fn unregister_instance_w_timestamp(&self, instance: &T, timestamp: Time) -> Result<()> {
290 let dispose = self.shared.autodispose_of(&self.guid);
291 self.shared
292 .write(
293 self.guid,
294 self.samples.instance_of(instance)?,
295 WriteOp::Lifecycle {
296 dispose,
297 unregister: true,
298 },
299 timestamp,
300 )
301 .map(|_| ())
302 }
303
304 pub fn dispose(&self, instance: &T) -> Result<()> {
308 self.dispose_w_timestamp(instance, Time::now())
309 }
310
311 pub fn dispose_w_timestamp(&self, instance: &T, timestamp: Time) -> Result<()> {
313 self.shared
314 .write(
315 self.guid,
316 self.samples.instance_of(instance)?,
317 WriteOp::Lifecycle {
318 dispose: true,
319 unregister: false,
320 },
321 timestamp,
322 )
323 .map(|_| ())
324 }
325
326 pub fn lookup_instance(&self, instance: &T) -> Option<InstanceHandle> {
329 let h = self.samples.instance_of(instance).ok()?;
330 let g = self.shared.lock_any();
331 g.writers
332 .get(&self.guid)
333 .filter(|w| w.instances.contains_key(&h))
334 .map(|_| h)
335 }
336
337 pub fn wait_for_acknowledgments(&self, max_wait: Duration) -> Result<()> {
342 self.shared.wait_for_acknowledgments(&self.guid, max_wait)
343 }
344
345 pub fn matched_subscriptions(&self) -> Vec<Guid> {
347 let g = self.shared.lock_any();
348 g.writers
349 .get(&self.guid)
350 .map(|w| w.matched.iter().copied().collect())
351 .unwrap_or_default()
352 }
353
354 pub fn offered_incompatible_qos_status(&self) -> IncompatibleQosStatus {
358 self.status(StatusMask::OFFERED_INCOMPATIBLE_QOS, |w| {
359 w.incompatible.take()
360 })
361 }
362
363 fn status<R: Default>(&self, k: StatusMask, f: impl FnOnce(&mut WriterState) -> R) -> R {
365 let mut g = self.shared.lock_any();
366 g.writers
367 .get_mut(&self.guid)
368 .map(|w| {
369 w.changes = w.changes & !k;
370 f(w)
371 })
372 .unwrap_or_default()
373 }
374
375 pub fn publication_matched_status(&self) -> MatchedStatus {
378 self.status(StatusMask::PUBLICATION_MATCHED, |w| w.matched_status.take())
379 }
380
381 pub fn set_listener(&self, listener: impl DataWriterListener<T> + 'static, mask: StatusMask)
385 where
386 T: 'static,
387 {
388 let l = writer_listener(self.encoding, self.samples.clone(), listener);
389 let before = {
391 let mut g = self.shared.lock_any();
392 g.writers
393 .get_mut(&self.guid)
394 .and_then(|w| w.listener.replace((l, mask)))
395 };
396 drop(before);
397 }
398
399 pub fn clear_listener(&self) {
401 let before = {
402 let mut g = self.shared.lock_any();
403 g.writers
404 .get_mut(&self.guid)
405 .and_then(|w| w.listener.take())
406 };
407 drop(before);
408 }
409
410 pub fn status_changes(&self) -> StatusMask {
413 let g = self.shared.lock_any();
414 g.writers
415 .get(&self.guid)
416 .map_or(StatusMask::NONE, |w| w.changes)
417 }
418
419 pub fn status_condition(&self) -> StatusCondition {
421 StatusCondition::new(self.shared.clone(), self.guid)
422 }
423
424 pub fn assert_liveliness(&self) -> Result<()> {
429 self.shared.assert_writer_liveliness(&self.guid)
430 }
431
432 pub fn liveliness_lost_status(&self) -> LivelinessLostStatus {
436 self.status(StatusMask::LIVELINESS_LOST, |w| w.liveliness_lost.take())
437 }
438
439 pub fn offered_deadline_missed_status(&self) -> DeadlineMissedStatus {
443 self.status(StatusMask::OFFERED_DEADLINE_MISSED, |w| {
444 w.deadlines.missed.take()
445 })
446 }
447
448 pub fn wait_for_subscriptions(&self, count: usize, timeout: Duration) -> bool {
451 let deadline = Instant::now() + timeout;
452 loop {
453 if self.matched_subscriptions().len() >= count {
454 return true;
455 }
456 if Instant::now() >= deadline {
457 return false;
458 }
459 std::thread::sleep(Duration::from_millis(10));
460 }
461 }
462}
463
464impl<T: PlainType> DataWriter<T> {
465 pub fn loan_sample(&self) -> Result<WriteLoan<T>> {
486 #[cfg(feature = "shm")]
487 if let Some(header) = self.plain_header()
488 && std::mem::align_of::<T>() <= 8
489 && let Some(pool) = self
490 .shared
491 .writer_pool(&self.guid, 4 + std::mem::size_of::<T>())?
492 && let Some(mut slot) = pool
493 .acquire()
494 .or_else(|| self.shared.wait_for_slot(&self.guid, &pool))
495 {
496 slot.bytes_mut()[..4].copy_from_slice(&header);
497 return Ok(WriteLoan {
498 inner: WriteInner::Shared(slot, std::marker::PhantomData),
499 });
500 }
501 Ok(WriteLoan::heap())
502 }
503
504 pub fn write_loaned(&self, sample: WriteLoan<T>) -> Result<()> {
506 self.write_loaned_w_timestamp(sample, Time::now())
507 }
508
509 pub fn write_loaned_w_timestamp(&self, sample: WriteLoan<T>, timestamp: Time) -> Result<()> {
511 let h = self.samples.instance_of(&sample)?;
512 let payload = match sample.inner {
513 #[cfg(feature = "shm")]
514 WriteInner::Shared(slot, _) => {
515 let len = 4 + std::mem::size_of::<T>();
516 if self.loan.verified() {
517 crate::instance::Payload::Loaned(slot.publish(len))
518 } else {
519 let serialized = self.serialize(WriteLoan::<T>::value_of(&slot))?;
522 if serialized == slot.bytes()[..len] {
523 self.loan.set_verified();
524 crate::instance::Payload::Loaned(slot.publish(len))
525 } else {
526 serialized.into()
527 }
528 }
529 }
530 WriteInner::Heap(b) => self.serialize(&b)?.into(),
531 };
532 self.shared
533 .write(self.guid, h, WriteOp::Value(payload, None, None), timestamp)
534 .map(|_| ())
535 }
536
537 fn serialize(&self, v: &T) -> Result<Vec<u8>> {
538 self.samples.to_payload(v, self.encoding, ByteOrder::NATIVE)
539 }
540
541 #[cfg(feature = "shm")]
544 fn plain_header(&self) -> Option<[u8; 4]> {
545 *self.loan.header.get_or_init(|| {
546 let p = self.serialize(&crate::loan::zeroed_box::<T>()).ok()?;
547 (p.len() == 4 + std::mem::size_of::<T>()).then(|| [p[0], p[1], p[2], p[3]])
548 })
549 }
550}
551
552impl<T> Drop for DataWriter<T> {
553 fn drop(&mut self) {
554 if self.owned {
555 self.shared.remove_writer(&self.guid);
556 }
557 }
558}
559
560fn writer_listener<T: 'static>(
563 encoding: Encoding,
564 samples: Arc<dyn SampleType<T>>,
565 listener: impl DataWriterListener<T> + 'static,
566) -> WriterListener {
567 Arc::new(move |shared: &Arc<Shared>, guid, event| {
568 let writer = DataWriter::<T> {
569 shared: shared.clone(),
570 guid,
571 encoding,
572 owned: false,
573 samples: samples.clone(),
574 loan: Arc::default(),
575 };
576 match event {
577 WriterEvent::PublicationMatched(s) => listener.on_publication_matched(&writer, s),
578 WriterEvent::LivelinessLost(s) => listener.on_liveliness_lost(&writer, s),
579 WriterEvent::OfferedDeadlineMissed(s) => {
580 listener.on_offered_deadline_missed(&writer, s)
581 }
582 WriterEvent::OfferedIncompatibleQos(s) => {
583 listener.on_offered_incompatible_qos(&writer, s)
584 }
585 }
586 })
587}
588
589fn encoding_of(qos: &DataWriterQos) -> Result<Encoding> {
592 match qos.data_representation.first() {
593 None | Some(&data_representation::XCDR) => Ok(Encoding::Xcdr1),
594 Some(&data_representation::XCDR2) => Ok(Encoding::Xcdr2),
595 Some(_) => Err(Error::Unsupported(
596 "a data representation other than XCDR and XCDR2",
597 )),
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
606 fn xcdr2_identifiers_of_table_60() {
607 let samples = crate::typed::Typed::<crate::test_shape::Shape>::new();
611 for (order, id) in [(ByteOrder::Little, 0x07), (ByteOrder::Big, 0x06)] {
612 let p = samples
613 .to_payload(&crate::test_shape::Shape::default(), Encoding::Xcdr2, order)
614 .unwrap();
615 assert_eq!(p[..2], [0x00, id]);
616 }
617 }
618}
619
620#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
622pub struct WriteParams {
623 pub source_timestamp: Option<Time>,
625 pub related_sample_identity: Option<SampleIdentity>,
629 pub directed_to: Option<Guid>,
634}