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<()> {
215 self.write_w_timestamp(sample, Time::now())
216 }
217
218 pub fn write_w_timestamp(&self, sample: &T, timestamp: Time) -> Result<()> {
220 self.write_w_params(
221 sample,
222 &WriteParams {
223 source_timestamp: Some(timestamp),
224 ..WriteParams::default()
225 },
226 )
227 .map(|_| ())
228 }
229
230 pub fn write_w_params(&self, sample: &T, params: &WriteParams) -> Result<SampleIdentity> {
234 self.write_mapped(sample, params, |p| p)
235 }
236
237 pub(crate) fn write_mapped(
240 &self,
241 sample: &T,
242 params: &WriteParams,
243 map: impl FnOnce(Vec<u8>) -> Vec<u8>,
244 ) -> Result<SampleIdentity> {
245 let payload = self
246 .samples
247 .to_payload(sample, self.encoding, ByteOrder::NATIVE)?;
248 let payload = map(payload);
249 let sequence_number = self.shared.write(
250 self.guid,
251 self.samples.instance_of(sample)?,
252 WriteOp::Value(
253 payload.into(),
254 params.related_sample_identity,
255 params.directed_to,
256 ),
257 params.source_timestamp.unwrap_or_else(Time::now),
258 )?;
259 Ok(SampleIdentity {
260 writer_guid: self.guid,
261 sequence_number,
262 })
263 }
264
265 pub fn register_instance(&self, instance: &T) -> Result<InstanceHandle> {
269 let h = self.samples.instance_of(instance)?;
270 self.shared.register_instance(&self.guid, h)?;
271 Ok(h)
272 }
273
274 pub fn unregister_instance(&self, instance: &T) -> Result<()> {
282 self.unregister_instance_w_timestamp(instance, Time::now())
283 }
284
285 pub fn unregister_instance_w_timestamp(&self, instance: &T, timestamp: Time) -> Result<()> {
288 let dispose = self.shared.autodispose_of(&self.guid);
289 self.shared
290 .write(
291 self.guid,
292 self.samples.instance_of(instance)?,
293 WriteOp::Lifecycle {
294 dispose,
295 unregister: true,
296 },
297 timestamp,
298 )
299 .map(|_| ())
300 }
301
302 pub fn dispose(&self, instance: &T) -> Result<()> {
306 self.dispose_w_timestamp(instance, Time::now())
307 }
308
309 pub fn dispose_w_timestamp(&self, instance: &T, timestamp: Time) -> Result<()> {
311 self.shared
312 .write(
313 self.guid,
314 self.samples.instance_of(instance)?,
315 WriteOp::Lifecycle {
316 dispose: true,
317 unregister: false,
318 },
319 timestamp,
320 )
321 .map(|_| ())
322 }
323
324 pub fn lookup_instance(&self, instance: &T) -> Option<InstanceHandle> {
327 let h = self.samples.instance_of(instance).ok()?;
328 let g = self.shared.lock_any();
329 g.writers
330 .get(&self.guid)
331 .filter(|w| w.instances.contains_key(&h))
332 .map(|_| h)
333 }
334
335 pub fn wait_for_acknowledgments(&self, max_wait: Duration) -> Result<()> {
340 self.shared.wait_for_acknowledgments(&self.guid, max_wait)
341 }
342
343 pub fn matched_subscriptions(&self) -> Vec<Guid> {
345 let g = self.shared.lock_any();
346 g.writers
347 .get(&self.guid)
348 .map(|w| w.matched.iter().copied().collect())
349 .unwrap_or_default()
350 }
351
352 pub fn offered_incompatible_qos_status(&self) -> IncompatibleQosStatus {
356 self.status(StatusMask::OFFERED_INCOMPATIBLE_QOS, |w| {
357 w.incompatible.take()
358 })
359 }
360
361 fn status<R: Default>(&self, k: StatusMask, f: impl FnOnce(&mut WriterState) -> R) -> R {
363 let mut g = self.shared.lock_any();
364 g.writers
365 .get_mut(&self.guid)
366 .map(|w| {
367 w.changes = w.changes & !k;
368 f(w)
369 })
370 .unwrap_or_default()
371 }
372
373 pub fn publication_matched_status(&self) -> MatchedStatus {
376 self.status(StatusMask::PUBLICATION_MATCHED, |w| w.matched_status.take())
377 }
378
379 pub fn set_listener(&self, listener: impl DataWriterListener<T> + 'static, mask: StatusMask)
383 where
384 T: 'static,
385 {
386 let l = writer_listener(self.encoding, self.samples.clone(), listener);
387 let mut g = self.shared.lock_any();
388 if let Some(w) = g.writers.get_mut(&self.guid) {
389 w.listener = Some((l, mask));
390 }
391 }
392
393 pub fn clear_listener(&self) {
395 let mut g = self.shared.lock_any();
396 if let Some(w) = g.writers.get_mut(&self.guid) {
397 w.listener = None;
398 }
399 }
400
401 pub fn status_changes(&self) -> StatusMask {
404 let g = self.shared.lock_any();
405 g.writers
406 .get(&self.guid)
407 .map_or(StatusMask::NONE, |w| w.changes)
408 }
409
410 pub fn status_condition(&self) -> StatusCondition {
412 StatusCondition::new(self.shared.clone(), self.guid)
413 }
414
415 pub fn assert_liveliness(&self) -> Result<()> {
420 self.shared.assert_writer_liveliness(&self.guid)
421 }
422
423 pub fn liveliness_lost_status(&self) -> LivelinessLostStatus {
427 self.status(StatusMask::LIVELINESS_LOST, |w| w.liveliness_lost.take())
428 }
429
430 pub fn offered_deadline_missed_status(&self) -> DeadlineMissedStatus {
434 self.status(StatusMask::OFFERED_DEADLINE_MISSED, |w| {
435 w.deadlines.missed.take()
436 })
437 }
438
439 pub fn wait_for_subscriptions(&self, count: usize, timeout: Duration) -> bool {
442 let deadline = Instant::now() + timeout;
443 loop {
444 if self.matched_subscriptions().len() >= count {
445 return true;
446 }
447 if Instant::now() >= deadline {
448 return false;
449 }
450 std::thread::sleep(Duration::from_millis(10));
451 }
452 }
453}
454
455impl<T: PlainType> DataWriter<T> {
456 pub fn loan_sample(&self) -> Result<WriteLoan<T>> {
476 #[cfg(feature = "shm")]
477 if let Some(header) = self.plain_header()
478 && std::mem::align_of::<T>() <= 8
479 && let Some(pool) = self
480 .shared
481 .writer_pool(&self.guid, 4 + std::mem::size_of::<T>())?
482 && let Some(mut slot) = pool.acquire()
483 {
484 slot.bytes_mut()[..4].copy_from_slice(&header);
485 return Ok(WriteLoan {
486 inner: WriteInner::Shared(slot, std::marker::PhantomData),
487 });
488 }
489 Ok(WriteLoan::heap())
490 }
491
492 pub fn write_loaned(&self, sample: WriteLoan<T>) -> Result<()> {
494 self.write_loaned_w_timestamp(sample, Time::now())
495 }
496
497 pub fn write_loaned_w_timestamp(&self, sample: WriteLoan<T>, timestamp: Time) -> Result<()> {
499 let h = self.samples.instance_of(&sample)?;
500 let payload = match sample.inner {
501 #[cfg(feature = "shm")]
502 WriteInner::Shared(slot, _) => {
503 let len = 4 + std::mem::size_of::<T>();
504 if self.loan.verified() {
505 crate::instance::Payload::Loaned(slot.publish(len))
506 } else {
507 let serialized = self.serialize(WriteLoan::<T>::value_of(&slot))?;
510 if serialized == slot.bytes()[..len] {
511 self.loan.set_verified();
512 crate::instance::Payload::Loaned(slot.publish(len))
513 } else {
514 serialized.into()
515 }
516 }
517 }
518 WriteInner::Heap(b) => self.serialize(&b)?.into(),
519 };
520 self.shared
521 .write(self.guid, h, WriteOp::Value(payload, None, None), timestamp)
522 .map(|_| ())
523 }
524
525 fn serialize(&self, v: &T) -> Result<Vec<u8>> {
526 self.samples.to_payload(v, self.encoding, ByteOrder::NATIVE)
527 }
528
529 #[cfg(feature = "shm")]
532 fn plain_header(&self) -> Option<[u8; 4]> {
533 *self.loan.header.get_or_init(|| {
534 let p = self.serialize(&crate::loan::zeroed_box::<T>()).ok()?;
535 (p.len() == 4 + std::mem::size_of::<T>()).then(|| [p[0], p[1], p[2], p[3]])
536 })
537 }
538}
539
540impl<T> Drop for DataWriter<T> {
541 fn drop(&mut self) {
542 if self.owned {
543 self.shared.remove_writer(&self.guid);
544 }
545 }
546}
547
548fn writer_listener<T: 'static>(
551 encoding: Encoding,
552 samples: Arc<dyn SampleType<T>>,
553 listener: impl DataWriterListener<T> + 'static,
554) -> WriterListener {
555 Arc::new(move |shared: &Arc<Shared>, guid, event| {
556 let writer = DataWriter::<T> {
557 shared: shared.clone(),
558 guid,
559 encoding,
560 owned: false,
561 samples: samples.clone(),
562 loan: Arc::default(),
563 };
564 match event {
565 WriterEvent::PublicationMatched(s) => listener.on_publication_matched(&writer, s),
566 WriterEvent::LivelinessLost(s) => listener.on_liveliness_lost(&writer, s),
567 WriterEvent::OfferedDeadlineMissed(s) => {
568 listener.on_offered_deadline_missed(&writer, s)
569 }
570 WriterEvent::OfferedIncompatibleQos(s) => {
571 listener.on_offered_incompatible_qos(&writer, s)
572 }
573 }
574 })
575}
576
577fn encoding_of(qos: &DataWriterQos) -> Result<Encoding> {
580 match qos.data_representation.first() {
581 None | Some(&data_representation::XCDR) => Ok(Encoding::Xcdr1),
582 Some(&data_representation::XCDR2) => Ok(Encoding::Xcdr2),
583 Some(_) => Err(Error::Unsupported(
584 "a data representation other than XCDR and XCDR2",
585 )),
586 }
587}
588
589#[cfg(test)]
590mod tests {
591 use super::*;
592
593 #[test]
594 fn xcdr2_identifiers_of_table_60() {
595 let samples = crate::typed::Typed::<crate::test_shape::Shape>::new();
599 for (order, id) in [(ByteOrder::Little, 0x07), (ByteOrder::Big, 0x06)] {
600 let p = samples
601 .to_payload(&crate::test_shape::Shape::default(), Encoding::Xcdr2, order)
602 .unwrap();
603 assert_eq!(p[..2], [0x00, id]);
604 }
605 }
606}
607
608#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
610pub struct WriteParams {
611 pub source_timestamp: Option<Time>,
613 pub related_sample_identity: Option<SampleIdentity>,
617 pub directed_to: Option<Guid>,
622}