Skip to main content

moqros_cli/
lib.rs

1//! Shared plumbing for the moqros bridge binaries.
2
3use std::any::TypeId;
4use std::collections::HashSet;
5use std::str::FromStr;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex};
8use std::time::Duration;
9
10use anyhow::{Context, bail, ensure};
11use clap::builder::BoolishValueParser;
12use clap::error::ErrorKind;
13use clap::{ArgAction, Args, Command, Parser, ValueEnum};
14use moqros::ros::r2r::ParameterValue;
15use moqros::ros::{QosProfile, ROS_IMAGE_TYPE, r2r};
16use tokio::task::JoinHandle;
17
18/// Relay connection flags.
19#[derive(Debug, Clone, Args)]
20pub struct RelayArgs {
21	/// Relay URL; its path scopes broadcast names.
22	#[arg(long, env = "MOQROS_URL", default_value = "http://localhost:4443/anon")]
23	pub url: moqros::Url,
24
25	/// Disable TLS certificate verification (development only).
26	#[arg(long, env = "MOQROS_INSECURE", action = ArgAction::Set, value_parser = BoolishValueParser::new(),
27		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
28	pub insecure: bool,
29}
30
31impl RelayArgs {
32	pub fn config(&self) -> moqros::ClientConfig {
33		moqros::ClientConfig {
34			url: self.url.clone(),
35			insecure: self.insecure,
36		}
37	}
38}
39
40/// What `moqros-pub` sends.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
42pub enum Format {
43	/// Encode `sensor_msgs/msg/Image` messages as video.
44	Video,
45	/// Any message type, as one JSON document per message.
46	Json,
47	/// Any message type, in its ROS serialization (CDR).
48	Cdr,
49}
50
51impl Format {
52	/// The data track format, or `None` for video.
53	pub fn data(self) -> Option<moqros::DataFormat> {
54		match self {
55			Self::Video => None,
56			Self::Json => Some(moqros::DataFormat::Json),
57			Self::Cdr => Some(moqros::DataFormat::Cdr),
58		}
59	}
60}
61
62/// `NAME[,key=value...]` split into the name and its options.
63type Spec<'a> = (&'a str, Vec<(&'a str, &'a str)>);
64
65/// Split `NAME[,key=value...]` into the name and its options, rejecting keys not in `keys`.
66fn split_spec<'a>(spec: &'a str, keys: &[&str]) -> Result<Spec<'a>, String> {
67	let mut parts = spec.split(',');
68	let name = parts.next().unwrap_or_default().trim();
69	if name.is_empty() {
70		return Err(format!("{spec:?} doesn't start with a name"));
71	}
72	let mut options: Vec<(&str, &str)> = Vec::new();
73	for part in parts {
74		let (key, value) = part
75			.split_once('=')
76			.ok_or_else(|| format!("expected key=value, got {part:?}"))?;
77		let (key, value) = (key.trim(), value.trim());
78		if !keys.contains(&key) {
79			return Err(format!("unknown option {key:?} (expected one of: {})", keys.join(", ")));
80		}
81		if options.iter().any(|(k, _)| *k == key) {
82			return Err(format!("option {key:?} given twice"));
83		}
84		options.push((key, value));
85	}
86	Ok((name, options))
87}
88
89/// A topic for `moqros-pub`: `TOPIC[,format=…][,type=…][,mode=…][,broadcast=…]`.
90///
91/// Options left out fall back to the matching command-line flags.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub struct TopicSpec {
94	pub topic: String,
95	pub format: Option<Format>,
96	pub ros_type: Option<String>,
97	pub mode: Option<moqros::DataMode>,
98	pub broadcast: Option<String>,
99}
100
101impl FromStr for TopicSpec {
102	type Err = String;
103
104	fn from_str(spec: &str) -> Result<Self, String> {
105		let (topic, options) = split_spec(spec, &["format", "type", "mode", "broadcast"])?;
106		let mut parsed = Self {
107			topic: topic.to_string(),
108			format: None,
109			ros_type: None,
110			mode: None,
111			broadcast: None,
112		};
113		for (key, value) in options {
114			match key {
115				"format" => parsed.format = Some(Format::from_str(value, true)?),
116				"type" => parsed.ros_type = Some(value.to_string()),
117				"mode" => parsed.mode = Some(value.parse().map_err(|err| format!("{err}"))?),
118				_ => parsed.broadcast = Some(value.to_string()),
119			}
120		}
121		Ok(parsed)
122	}
123}
124
125/// What `moqros-pub` does with one topic.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct PubTopic {
128	pub topic: String,
129	pub broadcast: String,
130	pub format: Format,
131	pub mode: moqros::DataMode,
132	/// Looked up in the ROS graph when `None` (unless the format is video).
133	pub ros_type: Option<String>,
134}
135
136/// Fill in each topic's options from the flags: `format` and `mode` apply to every topic,
137/// while `ros_type` and `broadcast` name one topic, so they need exactly one.
138pub fn pub_topics(
139	specs: Vec<TopicSpec>,
140	format: Format,
141	mode: moqros::DataMode,
142	ros_type: Option<String>,
143	broadcast: Option<String>,
144) -> anyhow::Result<Vec<PubTopic>> {
145	ensure!(!specs.is_empty(), "no topic to publish");
146	ensure!(
147		specs.len() == 1 || (ros_type.is_none() && broadcast.is_none()),
148		"--type and --broadcast need a single --topic; give several topics `type=` and `broadcast=` options instead"
149	);
150	let mut broadcasts = HashSet::new();
151	specs
152		.into_iter()
153		.map(|spec| {
154			let topic = PubTopic {
155				broadcast: spec
156					.broadcast
157					.or(broadcast.clone())
158					.unwrap_or_else(|| moqros::broadcast_name_for_topic(&spec.topic)),
159				format: spec.format.unwrap_or(format),
160				mode: spec.mode.unwrap_or(mode),
161				ros_type: spec.ros_type.or(ros_type.clone()),
162				topic: spec.topic,
163			};
164			if topic.format == Format::Video
165				&& let Some(ros_type) = topic.ros_type.as_deref().filter(|t| *t != ROS_IMAGE_TYPE)
166			{
167				bail!(
168					"{}: video needs {ROS_IMAGE_TYPE} messages, not {ros_type}; use format=json or cdr",
169					topic.topic
170				);
171			}
172			ensure!(
173				broadcasts.insert(topic.broadcast.clone()),
174				"several topics publish the broadcast {:?}",
175				topic.broadcast
176			);
177			Ok(topic)
178		})
179		.collect()
180}
181
182/// A broadcast for `moqros-sub`: `BROADCAST[,topic=…][,type=…][,frame_id=…]`.
183///
184/// Options left out fall back to the matching command-line flags.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct BroadcastSpec {
187	pub broadcast: String,
188	pub topic: Option<String>,
189	pub ros_type: Option<String>,
190	pub frame_id: Option<String>,
191}
192
193impl FromStr for BroadcastSpec {
194	type Err = String;
195
196	fn from_str(spec: &str) -> Result<Self, String> {
197		let (broadcast, options) = split_spec(spec, &["topic", "type", "frame_id"])?;
198		let mut parsed = Self {
199			broadcast: broadcast.to_string(),
200			topic: None,
201			ros_type: None,
202			frame_id: None,
203		};
204		for (key, value) in options {
205			let value = Some(value.to_string());
206			match key {
207				"topic" => parsed.topic = value,
208				"type" => parsed.ros_type = value,
209				_ => parsed.frame_id = value,
210			}
211		}
212		Ok(parsed)
213	}
214}
215
216/// What `moqros-sub` does with one broadcast.
217#[derive(Debug, Clone, PartialEq, Eq)]
218pub struct SubBroadcast {
219	pub broadcast: String,
220	pub topic: String,
221	/// Taken from the catalog when `None`.
222	pub ros_type: Option<String>,
223	pub frame_id: String,
224}
225
226/// Topic of a lone broadcast that neither `topic=` nor `--topic` names.
227pub const DEFAULT_SUB_TOPIC: &str = "/moqros/image";
228
229/// Fill in each broadcast's options from the flags. `topic` and `ros_type` name one
230/// broadcast, so they need exactly one. Without either `topic=` or `--topic`, a lone
231/// broadcast goes to [`DEFAULT_SUB_TOPIC`], and each of several to `/moqros/<broadcast>`.
232pub fn sub_broadcasts(
233	specs: Vec<BroadcastSpec>,
234	topic: Option<String>,
235	ros_type: Option<String>,
236	frame_id: &str,
237) -> anyhow::Result<Vec<SubBroadcast>> {
238	ensure!(!specs.is_empty(), "no broadcast to subscribe to");
239	let single = specs.len() == 1;
240	ensure!(
241		single || (topic.is_none() && ros_type.is_none()),
242		"--topic and --type need a single --broadcast; give several broadcasts `topic=` and `type=` options instead"
243	);
244	let mut topics = HashSet::new();
245	specs
246		.into_iter()
247		.map(|spec| {
248			let broadcast = SubBroadcast {
249				topic: spec.topic.or(topic.clone()).unwrap_or_else(|| match single {
250					true => DEFAULT_SUB_TOPIC.to_string(),
251					false => format!("/moqros/{}", spec.broadcast.trim_matches('/')),
252				}),
253				ros_type: spec.ros_type.or(ros_type.clone()),
254				frame_id: spec.frame_id.unwrap_or_else(|| frame_id.to_string()),
255				broadcast: spec.broadcast,
256			};
257			ensure!(
258				topics.insert(broadcast.topic.clone()),
259				"several broadcasts publish on {}",
260				broadcast.topic
261			);
262			Ok(broadcast)
263		})
264		.collect()
265}
266
267/// ROS QoS flags.
268#[derive(Debug, Clone, Args)]
269pub struct QosArgs {
270	/// Use reliable QoS instead of the best-effort sensor-data profile.
271	#[arg(long, action = ArgAction::Set, value_parser = BoolishValueParser::new(),
272		num_args = 0..=1, require_equals = true, default_value_t = false, default_missing_value = "true")]
273	pub reliable: bool,
274}
275
276impl QosArgs {
277	pub fn profile(&self) -> QosProfile {
278		if self.reliable {
279			QosProfile::default().keep_last(5)
280		} else {
281			QosProfile::sensor_data()
282		}
283	}
284}
285
286/// Create the ROS node and parse `T` from the command line and the node's ROS parameters.
287///
288/// Arguments between `--ros-args` and `--` are left to rcl, so the binaries accept
289/// remapping (`-r __node:=…`, `-r __ns:=…`), `-p` and `--params-file` like any ROS
290/// node. Each ROS parameter named after an argument (`bitrate`, `keyframe_interval_ms`,
291/// …) fills that argument: flags win over parameters, which win over environment
292/// variables and defaults.
293pub fn init<T: Parser>(node_name: &str) -> anyhow::Result<(T, r2r::Node)> {
294	let args = strip_ros_args(std::env::args());
295	// Answer `--help` and `--version` without bringing up ROS.
296	if let Some(err) = help_or_version(T::command(), &args) {
297		err.exit();
298	}
299
300	let ctx = r2r::Context::create().context("failed to create ROS context")?;
301	let node = r2r::Node::create(ctx, node_name, "").context("failed to create ROS node")?;
302
303	let flags = param_flags(
304		&T::command(),
305		node.params
306			.lock()
307			.unwrap()
308			.iter()
309			.map(|(name, param)| (name.as_str(), &param.value)),
310	)?;
311	let cli = match parse_args(args, flags) {
312		Ok(cli) => cli,
313		Err(ParseError::CommandLine(err)) => err.exit(),
314		Err(ParseError::Param(err)) => {
315			// Just clap's first line; its usage hints are about the command line.
316			let message = err.to_string();
317			let message = message.lines().next().unwrap_or_default().trim_start_matches("error: ");
318			bail!("invalid ROS parameter: {message}");
319		}
320	};
321	Ok((cli, node))
322}
323
324/// Drop the ROS arguments (`--ros-args … [--]`, possibly repeated) from `args`.
325pub fn strip_ros_args(args: impl IntoIterator<Item = String>) -> Vec<String> {
326	let mut in_ros_args = false;
327	args.into_iter()
328		.filter(|arg| match (in_ros_args, arg.as_str()) {
329			(false, "--ros-args") | (true, "--") => {
330				in_ros_args = !in_ros_args;
331				false
332			}
333			_ => !in_ros_args,
334		})
335		.collect()
336}
337
338/// The error to exit with if `args` ask for help or the version.
339///
340/// Clap answers these as soon as it meets the flag, before checking anything else.
341fn help_or_version(command: Command, args: &[String]) -> Option<clap::Error> {
342	let err = command.try_get_matches_from(args).err()?;
343	matches!(err.kind(), ErrorKind::DisplayHelp | ErrorKind::DisplayVersion).then_some(err)
344}
345
346/// Why [`parse_args`] failed.
347#[derive(Debug)]
348enum ParseError {
349	/// The command line itself is invalid.
350	CommandLine(clap::Error),
351	/// The command line is fine on its own, so a ROS parameter is invalid.
352	Param(clap::Error),
353}
354
355/// Parse `T` from `args` (program name first, ROS arguments already stripped) and
356/// `param_flags`.
357///
358/// The parameter flags go right after the program name. With `args_override_self` a
359/// later occurrence of a flag wins, so the command line overrides them, while
360/// environment variables and defaults only apply to flags given neither way. Repeatable
361/// flags collect every occurrence instead, so parameter flags that the command line
362/// gives again are dropped up front.
363fn parse_args<T: Parser>(args: Vec<String>, param_flags: Vec<String>) -> Result<T, ParseError> {
364	let flag = |arg: &str| arg.split_once('=').map_or(arg, |(flag, _)| flag).to_string();
365	let given: HashSet<String> = args
366		.iter()
367		.skip(1)
368		.filter(|arg| arg.starts_with("--"))
369		.map(|arg| flag(arg))
370		.collect();
371	let param_flags: Vec<String> = param_flags
372		.into_iter()
373		.filter(|param| !given.contains(&flag(param)))
374		.collect();
375	let parse = |param_flags: Vec<String>| {
376		let mut args = args.iter().cloned();
377		let args = args.next().into_iter().chain(param_flags).chain(args);
378		let matches = T::command().args_override_self(true).try_get_matches_from(args)?;
379		T::from_arg_matches(&matches)
380	};
381	parse(param_flags).map_err(|err| match parse(Vec::new()) {
382		Ok(_) => ParseError::Param(err),
383		Err(err) => ParseError::CommandLine(err),
384	})
385}
386
387/// Command-line flags (`--name=value`) for the ROS parameters named after an argument
388/// of `command`.
389fn param_flags<'a>(
390	command: &Command,
391	params: impl IntoIterator<Item = (&'a str, &'a ParameterValue)>,
392) -> anyhow::Result<Vec<String>> {
393	let mut flags = Vec::new();
394	for (name, value) in params {
395		let Some((long, arg)) = command
396			.get_arguments()
397			.find(|arg| arg.get_id() == name)
398			.and_then(|arg| Some((arg.get_long()?, arg)))
399		else {
400			// r2r reads `use_sim_time` itself.
401			if name != "use_sim_time" {
402				tracing::warn!(name, "ignoring unknown ROS parameter");
403			}
404			continue;
405		};
406		let value = match value {
407			// An empty YAML value: leave the flag to its environment variable or default.
408			ParameterValue::NotSet => continue,
409			ParameterValue::Bool(value) => value.to_string(),
410			ParameterValue::Integer(value) => value.to_string(),
411			// Keep the fraction of whole numbers for strings (`1.0` stays `1.0`), but drop
412			// it for numbers so `2000000.0` still fits an integer flag.
413			ParameterValue::Double(value) if arg.get_value_parser().type_id() == TypeId::of::<String>() => {
414				format!("{value:?}")
415			}
416			ParameterValue::Double(value) => value.to_string(),
417			ParameterValue::String(value) => value.clone(),
418			// A list fills a repeatable flag, one occurrence per element.
419			ParameterValue::StringArray(values) if matches!(arg.get_action(), ArgAction::Append) => {
420				flags.extend(values.iter().map(|value| format!("--{long}={value}")));
421				continue;
422			}
423			value => bail!("ROS parameter `{name}` has unsupported type: {value:?}"),
424		};
425		// One token, so values starting with `-` aren't taken for flags.
426		flags.push(format!("--{long}={value}"));
427	}
428	Ok(flags)
429}
430
431pub fn init_logging() {
432	tracing_subscriber::fmt()
433		.with_env_filter(
434			tracing_subscriber::EnvFilter::try_from_default_env()
435				.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
436		)
437		.init();
438}
439
440/// A node shared between [`spawn_spinner`] and code that adds subscriptions while it spins.
441pub struct SharedNode {
442	node: Mutex<r2r::Node>,
443	/// Set while [`SharedNode::with`] waits, so the spinner lets go of the lock. A mutex
444	/// isn't fair: a spinner relocking it right away could starve the waiter.
445	waiting: AtomicBool,
446}
447
448impl SharedNode {
449	pub fn new(node: r2r::Node) -> Arc<Self> {
450		Arc::new(Self {
451			node: Mutex::new(node),
452			waiting: AtomicBool::new(false),
453		})
454	}
455
456	/// Run `f` on the node, between two spins.
457	pub fn with<R>(&self, f: impl FnOnce(&mut r2r::Node) -> R) -> R {
458		self.waiting.store(true, Ordering::Relaxed);
459		let mut node = self.node.lock().unwrap_or_else(|err| err.into_inner());
460		self.waiting.store(false, Ordering::Relaxed);
461		f(&mut node)
462	}
463}
464
465/// Spin `node` on a blocking thread until the returned guard is dropped.
466///
467/// The tokio runtime waits for blocking tasks on shutdown, so a spinner that never
468/// stops would keep the process alive after `main` returns.
469pub fn spawn_spinner(node: Arc<SharedNode>) -> Spinner {
470	let stop = Arc::new(AtomicBool::new(false));
471	let stopped = stop.clone();
472	let task = tokio::task::spawn_blocking(move || {
473		while !stopped.load(Ordering::Relaxed) {
474			if node.waiting.load(Ordering::Relaxed) {
475				std::thread::yield_now();
476				continue;
477			}
478			let mut guard = node.node.lock().unwrap_or_else(|err| err.into_inner());
479			guard.spin_once(Duration::from_millis(50));
480		}
481	});
482	Spinner { stop, task: Some(task) }
483}
484
485/// Stops the [`spawn_spinner`] thread when dropped.
486pub struct Spinner {
487	stop: Arc<AtomicBool>,
488	task: Option<JoinHandle<()>>,
489}
490
491impl Spinner {
492	/// Resolves if the spinner thread dies, which only happens when it panics, since
493	/// without spinning no ROS message arrives anymore. Never resolves again after that.
494	pub async fn failed(&mut self) -> anyhow::Error {
495		let Some(task) = self.task.as_mut() else {
496			return std::future::pending().await;
497		};
498		let result = task.await;
499		self.task = None;
500		match result {
501			Err(err) => anyhow::Error::new(err).context("ROS spinner failed"),
502			Ok(()) => anyhow::anyhow!("ROS spinner stopped"),
503		}
504	}
505}
506
507impl Drop for Spinner {
508	fn drop(&mut self) {
509		self.stop.store(true, Ordering::Relaxed);
510	}
511}
512
513#[cfg(test)]
514mod tests {
515	use clap::CommandFactory;
516
517	use super::*;
518
519	fn strip(args: &[&str]) -> Vec<String> {
520		strip_ros_args(args.iter().map(|arg| arg.to_string()))
521	}
522
523	#[derive(Debug, Parser)]
524	#[command(version = "1.2.3")]
525	struct TestCli {
526		#[arg(long, default_value = "/image_raw")]
527		topic: String,
528
529		#[arg(long)]
530		broadcast: Option<String>,
531
532		#[arg(long, default_value_t = 30.0)]
533		fps: f32,
534
535		#[arg(long, default_value_t = 2000)]
536		keyframe_interval_ms: u64,
537
538		#[arg(long, value_enum, default_value_t = Format::Video)]
539		format: Format,
540
541		#[arg(id = "type", long = "type")]
542		ros_type: Option<String>,
543
544		#[arg(long, default_value_t = moqros::DataMode::default())]
545		mode: moqros::DataMode,
546
547		#[command(flatten)]
548		relay: RelayArgs,
549
550		#[command(flatten)]
551		qos: QosArgs,
552	}
553
554	#[derive(Debug, Parser)]
555	struct MultiCli {
556		#[arg(long, default_value = "/image_raw")]
557		topic: Vec<TopicSpec>,
558	}
559
560	/// Only parsed by `params_override_env`, in a child process of its own.
561	#[derive(Debug, Parser)]
562	struct EnvCli {
563		#[arg(long, env = "MOQROS_TEST_BITRATE", default_value_t = 1)]
564		bitrate: u32,
565	}
566
567	fn flags<T: Parser>(params: &[(&str, ParameterValue)]) -> anyhow::Result<Vec<String>> {
568		param_flags(&T::command(), params.iter().map(|(name, value)| (*name, value)))
569	}
570
571	fn args(args: &[&str]) -> Vec<String> {
572		std::iter::once("bin")
573			.chain(args.iter().copied())
574			.map(String::from)
575			.collect()
576	}
577
578	fn parse<T: Parser>(args_: &[&str], params: &[(&str, ParameterValue)]) -> Result<T, ParseError> {
579		parse_args(args(args_), flags::<T>(params).unwrap())
580	}
581
582	fn string(value: &str) -> ParameterValue {
583		ParameterValue::String(value.to_string())
584	}
585
586	#[test]
587	fn strips_ros_args() {
588		assert_eq!(strip(&["bin", "--topic", "a"]), ["bin", "--topic", "a"]);
589		assert_eq!(
590			strip(&[
591				"bin",
592				"--topic",
593				"a",
594				"--ros-args",
595				"-r",
596				"__node:=n",
597				"-p",
598				"bitrate:=1"
599			]),
600			["bin", "--topic", "a"]
601		);
602		assert_eq!(
603			strip(&[
604				"bin",
605				"--ros-args",
606				"-r",
607				"__ns:=/x",
608				"--",
609				"--reliable",
610				"--ros-args",
611				"-p",
612				"a:=1"
613			]),
614			["bin", "--reliable"]
615		);
616	}
617
618	#[test]
619	fn params_fill_flags() {
620		let cli: TestCli = parse(
621			&[],
622			&[
623				("topic", string("/front/image_raw")),
624				("keyframe_interval_ms", ParameterValue::Integer(500)),
625				("reliable", ParameterValue::Bool(true)),
626				("url", string("http://relay:4443/anon")),
627			],
628		)
629		.unwrap();
630		assert_eq!(cli.topic, "/front/image_raw");
631		assert_eq!(cli.keyframe_interval_ms, 500);
632		assert!(cli.qos.reliable);
633		assert_eq!(cli.relay.url.as_str(), "http://relay:4443/anon");
634		assert!(!cli.relay.insecure);
635		assert_eq!(cli.broadcast, None);
636	}
637
638	#[test]
639	fn data_params_fill_flags() {
640		let cli: TestCli = parse(&[], &[]).unwrap();
641		assert_eq!(
642			(cli.format, cli.ros_type, cli.mode),
643			(Format::Video, None, moqros::DataMode::Snapshot)
644		);
645
646		let cli: TestCli = parse(
647			&[],
648			&[
649				("format", string("json")),
650				("type", string("sensor_msgs/msg/Imu")),
651				("mode", string("stream")),
652			],
653		)
654		.unwrap();
655		assert_eq!(cli.format, Format::Json);
656		assert_eq!(cli.format.data(), Some(moqros::DataFormat::Json));
657		assert_eq!(cli.ros_type.as_deref(), Some("sensor_msgs/msg/Imu"));
658		assert_eq!(cli.mode, moqros::DataMode::Stream);
659
660		let cli: TestCli = parse(&["--format", "cdr", "--type", "std_msgs/msg/String"], &[]).unwrap();
661		assert_eq!(cli.format.data(), Some(moqros::DataFormat::Cdr));
662		assert_eq!(cli.ros_type.as_deref(), Some("std_msgs/msg/String"));
663		assert!(matches!(
664			parse::<TestCli>(&[], &[("format", string("xml"))]),
665			Err(ParseError::Param(_))
666		));
667	}
668
669	#[test]
670	fn command_line_overrides_params() {
671		let params = [
672			("topic", string("/param")),
673			("reliable", ParameterValue::Bool(true)),
674			("insecure", ParameterValue::Bool(false)),
675		];
676		let cli: TestCli = parse(&["--topic", "/flag", "--reliable=false", "--insecure"], &params).unwrap();
677		assert_eq!(cli.topic, "/flag");
678		assert!(!cli.qos.reliable);
679		assert!(cli.relay.insecure);
680	}
681
682	/// Setting a variable while other tests read the environment is undefined behavior,
683	/// so this test reruns itself in a child process for each value of the variable.
684	#[test]
685	fn params_override_env() {
686		const VAR: &str = "MOQROS_TEST_BITRATE";
687		let bitrate = ("bitrate", ParameterValue::Integer(2));
688		match std::env::var(VAR).ok().as_deref() {
689			None => {
690				for value in ["bogus", "4"] {
691					let output = std::process::Command::new(std::env::current_exe().unwrap())
692						.args(["--exact", "tests::params_override_env"])
693						.env(VAR, value)
694						.output()
695						.unwrap();
696					let stdout = String::from_utf8_lossy(&output.stdout);
697					assert!(
698						output.status.success() && stdout.contains("1 passed"),
699						"{VAR}={value}:\n{stdout}"
700					);
701				}
702			}
703			// An invalid variable is never looked at when a parameter or flag is set.
704			Some("bogus") => {
705				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
706				assert_eq!(parse::<EnvCli>(&["--bitrate", "3"], &[]).unwrap().bitrate, 3);
707				assert!(matches!(parse::<EnvCli>(&[], &[]), Err(ParseError::CommandLine(_))));
708				let help = help_or_version(EnvCli::command(), &args(&["--help"]));
709				assert_eq!(help.map(|err| err.kind()), Some(ErrorKind::DisplayHelp));
710			}
711			Some(value) => {
712				assert_eq!(value, "4");
713				assert_eq!(parse::<EnvCli>(&[], &[]).unwrap().bitrate, 4);
714				assert_eq!(parse::<EnvCli>(&[], std::slice::from_ref(&bitrate)).unwrap().bitrate, 2);
715				assert_eq!(parse::<EnvCli>(&["--bitrate=3"], &[bitrate]).unwrap().bitrate, 3);
716			}
717		}
718	}
719
720	#[test]
721	fn doubles_keep_their_fraction() {
722		let cli: TestCli = parse(
723			&[],
724			&[
725				("broadcast", ParameterValue::Double(1.0)),
726				("fps", ParameterValue::Double(12.5)),
727			],
728		)
729		.unwrap();
730		assert_eq!(cli.broadcast.as_deref(), Some("1.0"));
731		assert_eq!(cli.fps, 12.5);
732
733		// Whole numbers still fit integer flags.
734		let cli: TestCli = parse(&[], &[("keyframe_interval_ms", ParameterValue::Double(500.0))]).unwrap();
735		assert_eq!(cli.keyframe_interval_ms, 500);
736
737		// YAML `fps: 15` is an integer parameter.
738		let cli: TestCli = parse(&[], &[("fps", ParameterValue::Integer(15))]).unwrap();
739		assert_eq!(cli.fps, 15.0);
740	}
741
742	#[test]
743	fn values_starting_with_a_dash_stay_values() {
744		let cli: TestCli = parse(&[], &[("broadcast", string("-x"))]).unwrap();
745		assert_eq!(cli.broadcast.as_deref(), Some("-x"));
746	}
747
748	#[test]
749	fn unset_and_unknown_params_are_ignored() {
750		let params = [
751			("broadcast", ParameterValue::NotSet),
752			("use_sim_time", ParameterValue::Bool(false)),
753			("bitrat", ParameterValue::Integer(1)),
754			("keyframe-interval-ms", ParameterValue::Integer(1)),
755			// Clap's own arguments aren't parameters.
756			("help", ParameterValue::Bool(true)),
757			("version", string("2")),
758		];
759		assert!(flags::<TestCli>(&params).unwrap().is_empty());
760	}
761
762	#[test]
763	fn arrays_fill_repeatable_flags() {
764		let topics = |cli: MultiCli| cli.topic.into_iter().map(|spec| spec.topic).collect::<Vec<_>>();
765		assert_eq!(topics(parse(&[], &[]).unwrap()), ["/image_raw"]);
766		let params = [(
767			"topic",
768			ParameterValue::StringArray(vec!["/a".into(), "/b,format=json".into()]),
769		)];
770		let cli: MultiCli = parse(&[], &params).unwrap();
771		assert_eq!(cli.topic[1].format, Some(Format::Json));
772		assert_eq!(topics(cli), ["/a", "/b"]);
773		// A single string still works, and the command line replaces the whole list.
774		assert_eq!(topics(parse(&[], &[("topic", string("/c"))]).unwrap()), ["/c"]);
775		assert_eq!(topics(parse(&["--topic", "/d"], &params).unwrap()), ["/d"]);
776	}
777
778	#[test]
779	fn parses_topic_specs() {
780		let spec: TopicSpec = "/scan, format=cdr ,type=sensor_msgs/msg/LaserScan,mode=stream,broadcast=lidar"
781			.parse()
782			.unwrap();
783		assert_eq!(
784			spec,
785			TopicSpec {
786				topic: "/scan".into(),
787				format: Some(Format::Cdr),
788				ros_type: Some("sensor_msgs/msg/LaserScan".into()),
789				mode: Some(moqros::DataMode::Stream),
790				broadcast: Some("lidar".into()),
791			}
792		);
793		assert_eq!("/image_raw".parse::<TopicSpec>().unwrap().format, None);
794		for bad in [
795			"",
796			",format=json",
797			"/a,json",
798			"/a,codec=vp8",
799			"/a,format=xml",
800			"/a,mode=x",
801			"/a,type=x,type=y",
802		] {
803			assert!(bad.parse::<TopicSpec>().is_err(), "{bad:?}");
804		}
805
806		let spec: BroadcastSpec = "camera/image_raw,topic=/out,frame_id=cam,type=sensor_msgs/msg/Image"
807			.parse()
808			.unwrap();
809		assert_eq!(
810			(spec.broadcast.as_str(), spec.topic.as_deref(), spec.frame_id.as_deref()),
811			("camera/image_raw", Some("/out"), Some("cam"))
812		);
813		assert!("chatter,format=json".parse::<BroadcastSpec>().is_err());
814	}
815
816	#[test]
817	fn resolves_pub_topics() {
818		let specs = |specs: &[&str]| {
819			specs
820				.iter()
821				.map(|s| s.parse::<TopicSpec>().unwrap())
822				.collect::<Vec<_>>()
823		};
824		let snapshot = moqros::DataMode::Snapshot;
825
826		let topics = pub_topics(
827			specs(&[
828				"/camera/image_raw",
829				"/chatter,format=json",
830				"/log,mode=stream,broadcast=logs",
831			]),
832			Format::Video,
833			snapshot,
834			None,
835			None,
836		)
837		.unwrap();
838		let summary: Vec<_> = topics
839			.iter()
840			.map(|t| (t.broadcast.as_str(), t.format, t.mode))
841			.collect();
842		assert_eq!(
843			summary,
844			[
845				("camera/image_raw", Format::Video, snapshot),
846				("chatter", Format::Json, snapshot),
847				("logs", Format::Video, moqros::DataMode::Stream),
848			]
849		);
850
851		// Flags that name one topic.
852		let one = pub_topics(
853			specs(&["/a"]),
854			Format::Cdr,
855			snapshot,
856			Some("t/msg/T".into()),
857			Some("b".into()),
858		)
859		.unwrap();
860		assert_eq!(
861			(one[0].broadcast.as_str(), one[0].ros_type.as_deref()),
862			("b", Some("t/msg/T"))
863		);
864		assert!(
865			pub_topics(
866				specs(&["/a", "/b"]),
867				Format::Json,
868				snapshot,
869				Some("t/msg/T".into()),
870				None
871			)
872			.is_err()
873		);
874		assert!(pub_topics(specs(&["/a", "/b"]), Format::Json, snapshot, None, Some("b".into())).is_err());
875
876		assert!(pub_topics(specs(&["/a", "a,format=json"]), Format::Video, snapshot, None, None).is_err());
877		assert!(
878			pub_topics(
879				specs(&["/a,type=std_msgs/msg/String"]),
880				Format::Video,
881				snapshot,
882				None,
883				None
884			)
885			.is_err()
886		);
887		assert!(
888			pub_topics(
889				specs(&["/a,type=sensor_msgs/msg/Image"]),
890				Format::Video,
891				snapshot,
892				None,
893				None
894			)
895			.is_ok()
896		);
897		assert!(pub_topics(Vec::new(), Format::Video, snapshot, None, None).is_err());
898	}
899
900	#[test]
901	fn resolves_sub_broadcasts() {
902		let specs = |specs: &[&str]| {
903			specs
904				.iter()
905				.map(|s| s.parse::<BroadcastSpec>().unwrap())
906				.collect::<Vec<_>>()
907		};
908		let topics = |broadcasts: Vec<SubBroadcast>| broadcasts.into_iter().map(|b| b.topic).collect::<Vec<_>>();
909
910		assert_eq!(
911			topics(sub_broadcasts(specs(&["image_raw"]), None, None, "camera").unwrap()),
912			[DEFAULT_SUB_TOPIC]
913		);
914		assert_eq!(
915			topics(sub_broadcasts(specs(&["image_raw"]), Some("/x".into()), None, "camera").unwrap()),
916			["/x"]
917		);
918		let broadcasts = sub_broadcasts(
919			specs(&[
920				"sample/image_raw,topic=/moqros/image",
921				"chatter",
922				"/front/imu/,frame_id=imu",
923			]),
924			None,
925			None,
926			"camera",
927		)
928		.unwrap();
929		assert_eq!(broadcasts[2].frame_id, "imu");
930		assert_eq!(
931			topics(broadcasts),
932			["/moqros/image", "/moqros/chatter", "/moqros/front/imu"]
933		);
934
935		assert!(sub_broadcasts(specs(&["a", "b"]), Some("/x".into()), None, "camera").is_err());
936		assert!(sub_broadcasts(specs(&["a", "b"]), None, Some("t/msg/T".into()), "camera").is_err());
937		assert!(sub_broadcasts(specs(&["a,topic=/x", "b,topic=/x"]), None, None, "camera").is_err());
938	}
939
940	#[test]
941	fn arrays_are_rejected() {
942		let params = [("topic", ParameterValue::StringArray(vec!["/a".into()]))];
943		let err = flags::<TestCli>(&params).unwrap_err();
944		assert!(err.to_string().contains("`topic`"), "{err}");
945	}
946
947	#[test]
948	fn invalid_param_values_are_blamed_on_the_param() {
949		for (name, value) in [("keyframe_interval_ms", "soon"), ("url", "not a url")] {
950			match parse::<TestCli>(&[], &[(name, string(value))]) {
951				Err(ParseError::Param(err)) => assert_eq!(err.kind(), ErrorKind::ValueValidation, "{name}"),
952				other => panic!("{name}: {other:?}"),
953			}
954		}
955	}
956
957	#[test]
958	fn invalid_command_lines_are_blamed_on_the_command_line() {
959		let params = [("keyframe_interval_ms", string("soon"))];
960		for args in [&["--fps=fast"][..], &["--unknown"]] {
961			assert!(
962				matches!(parse::<TestCli>(args, &params), Err(ParseError::CommandLine(_))),
963				"{args:?}"
964			);
965		}
966	}
967
968	#[test]
969	fn detects_help_and_version() {
970		let kind = |args_: &[&str]| help_or_version(TestCli::command(), &args(args_)).map(|err| err.kind());
971		assert_eq!(kind(&["--help"]), Some(ErrorKind::DisplayHelp));
972		assert_eq!(kind(&["-V"]), Some(ErrorKind::DisplayVersion));
973		// Arguments after the help flag aren't looked at.
974		assert_eq!(kind(&["-h", "--fps=fast"]), Some(ErrorKind::DisplayHelp));
975		assert_eq!(kind(&["--topic", "/a"]), None);
976		assert_eq!(kind(&["--fps=fast"]), None);
977	}
978}