rustorb-dds-ros2 0.4.0

The ROS 2 conventions on DDS for rustorb-dds: names, interface types from .msg/.srv, RIHS01 type hashes, node discovery
Documentation
//! ROS 2 nodes made with rustorb-dds-ros2: the types come from the
//! `.msg` files of a ROS 2 installation (`AMENT_PREFIX_PATH`), or from
//! the definitions below when there is none; the nodes are announced on
//! `ros_discovery_info`, so that `ros2 node list` shows them.
//!
//! ```text
//! ros2_node talker [domain [count [interval_ms]]]
//! ros2_node listener [domain [count [timeout_s]]]
//! ros2_node twist_listener [domain [count [timeout_s]]]
//! ```
//!
//! The talker is the node `/rustorb_talker`: it publishes
//! `std_msgs/msg/String` "Hello World: 1", "Hello World: 2"... on
//! `/chatter` and `geometry_msgs/msg/Twist` with `linear.x` 0.5, 1.0...
//! on `/cmd_vel`, every `interval_ms` (default 500) until it has sent
//! `count` (default: no end). The listener is `/rustorb_listener` on
//! `/chatter`, the twist listener `/rustorb_twist_listener` on
//! `/cmd_vel`; they print what they hear and exit after `count`
//! messages, or with an error after `timeout_s` seconds (default 60).

use std::time::{Duration, Instant};

use rustorb_dds::{Error as DdsError, StatusMask, WaitSet};
use rustorb_dds_ros2::{QosProfile, RosParticipant, TypeLibrary, UserData, Value};

/// Used when no ROS 2 installation has the files.
const FALLBACK: &[(&str, &str)] = &[
    ("std_msgs/msg/String", "string data\n"),
    (
        "geometry_msgs/msg/Vector3",
        "float64 x\nfloat64 y\nfloat64 z\n",
    ),
    (
        "geometry_msgs/msg/Twist",
        "Vector3 linear\nVector3 angular\n",
    ),
];

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 types = TypeLibrary::with_dirs::<&str>([]);
    for (name, text) in FALLBACK {
        types.add_text(name, text)?;
    }
    let string = types.message("std_msgs/msg/String")?;
    let twist = types.message("geometry_msgs/msg/Twist")?;
    let ros = RosParticipant::new(domain)?;
    let none = UserData::new();
    match role {
        "talker" => {
            let interval = Duration::from_millis(arg(4)?.unwrap_or(500));
            let node = ros.create_node("/", "rustorb_talker")?;
            let chatter = node.create_publisher("chatter", &string, &QosProfile::DEFAULT, &none)?;
            let cmd_vel = node.create_publisher("cmd_vel", &twist, &QosProfile::DEFAULT, &none)?;
            println!(
                "rustorb-dds: /chatter {} {}",
                string.name(),
                string.type_hash()
            );
            println!(
                "rustorb-dds: /cmd_vel {} {}",
                twist.name(),
                twist.type_hash()
            );
            // Wait for a listener, so that the first messages are not
            // lost while it matches.
            while !chatter
                .writer()
                .wait_for_subscriptions(1, Duration::from_secs(1))
                && !cmd_vel
                    .writer()
                    .wait_for_subscriptions(1, Duration::from_millis(1))
            {}
            std::thread::sleep(Duration::from_millis(500));
            let mut i = 0u64;
            while count.is_none_or(|c| i < c) {
                i += 1;
                let text = format!("Hello World: {i}");
                println!("rustorb-dds: Publishing: '{text}'");
                chatter.publish(&Value::Struct(vec![("data".into(), Value::String(text))]))?;
                cmd_vel.publish(&Value::Struct(vec![(
                    "linear".into(),
                    Value::Struct(vec![("x".into(), Value::Float(i as f64 * 0.5))]),
                )]))?;
                std::thread::sleep(interval);
            }
            chatter
                .writer()
                .wait_for_acknowledgments(Duration::from_secs(10))?;
        }
        "listener" | "twist_listener" => {
            let deadline = Instant::now() + Duration::from_secs(arg(4)?.unwrap_or(60));
            let (node_name, topic, ty) = if role == "listener" {
                ("rustorb_listener", "chatter", &string)
            } else {
                ("rustorb_twist_listener", "cmd_vel", &twist)
            };
            let node = ros.create_node("/", node_name)?;
            let sub = node.create_subscription(topic, ty, &QosProfile::DEFAULT, &none)?;
            let status = sub.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(DdsError::Timeout) => {
                        return Err(format!("rustorb-dds: heard {got} messages").into());
                    }
                    r => r?,
                };
                for (v, info) in sub.take()? {
                    let from = ros
                        .writer_of(&info)
                        .and_then(|w| UserData::parse(&w.user_data).type_hash())
                        .map(|h| h.to_string())
                        .unwrap_or_else(|| "no type hash".into());
                    match (v.get("data"), v.get("linear").and_then(|l| l.get("x"))) {
                        (Some(Value::String(s)), _) => {
                            println!("rustorb-dds: I heard: [{s}] ({from})")
                        }
                        (_, Some(Value::Float(x))) => {
                            println!("rustorb-dds: I heard: linear.x {x} ({from})")
                        }
                        _ => println!("rustorb-dds: I heard: {v:?}"),
                    }
                    got += 1;
                }
            }
        }
        _ => {
            return Err(
                format!("unknown role {role:?}: use talker, listener or twist_listener").into(),
            );
        }
    }
    Ok(())
}