#[allow(dead_code, clippy::all)]
mod std_msgs;
use std::time::{Duration, Instant};
use rustorb_dds::{
DataReaderQos, DataWriterQos, DomainParticipant, Error, History, ParticipantConfig,
Reliability, StatusMask, WaitSet,
};
use std_msgs::std_msgs::msg::dds::String as StringMsg;
const TOPIC: &str = "rt/chatter";
const DEPTH: usize = 10;
const ENCLAVE: &[u8] = b"enclave=/;";
const TYPE_HASH: &[u8] =
b"typehash=RIHS01_df668c740482bbd48fb39d76a70dfd4bd59db1288021743503259e948f6b1a18;";
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
let role = args.get(1).map(String::as_str).unwrap_or("listener");
let arg = |i: usize| -> Result<Option<u64>, Box<dyn std::error::Error>> {
Ok(match args.get(i) {
Some(v) => Some(v.parse()?),
None => None,
})
};
let domain = arg(2)?.unwrap_or(0) as u32;
let count = arg(3)?;
let mut config = ParticipantConfig::new(domain);
config.user_data = ENCLAVE.to_vec();
let participant = DomainParticipant::with_config(config)?;
let topic = participant.create_topic::<StringMsg>(TOPIC)?;
match role {
"talker" => {
let interval = Duration::from_millis(arg(4)?.unwrap_or(1000));
let writer = participant.create_publisher()?.create_datawriter_with_qos(
&topic,
DataWriterQos {
reliability: Reliability::reliable(),
history: History::KeepLast(DEPTH),
user_data: TYPE_HASH.to_vec(),
..DataWriterQos::default()
},
)?;
while !writer.wait_for_subscriptions(1, Duration::from_secs(1)) {}
std::thread::sleep(Duration::from_millis(500));
let mut i = 0u64;
while count.is_none_or(|c| i < c) {
i += 1;
let data = format!("Hello World: {i}");
println!("rustorb-dds: Publishing: '{data}'");
writer.write(&StringMsg { data })?;
std::thread::sleep(interval);
}
writer.wait_for_acknowledgments(Duration::from_secs(10))?;
}
"listener" => {
let deadline = Instant::now() + Duration::from_secs(arg(4)?.unwrap_or(60));
let reader = participant
.create_subscriber()?
.create_datareader_with_qos(
&topic,
DataReaderQos {
reliability: Reliability::reliable(),
history: History::KeepLast(DEPTH),
user_data: TYPE_HASH.to_vec(),
..DataReaderQos::default()
},
)?;
let status = reader.status_condition();
status.set_enabled_statuses(StatusMask::DATA_AVAILABLE);
let waitset = WaitSet::new();
waitset.attach_condition(&status)?;
let mut got = 0u64;
while count.is_none_or(|c| got < c) {
let left = deadline.saturating_duration_since(Instant::now());
match waitset.wait(left) {
Err(Error::Timeout) => {
return Err(format!("rustorb-dds: heard {got} messages").into());
}
r => r?,
};
for m in reader.take().into_iter().filter_map(|s| s.data) {
println!("rustorb-dds: I heard: [{}]", m.data);
got += 1;
}
}
}
_ => return Err(format!("unknown role {role:?}: use talker or listener").into()),
}
Ok(())
}