dimas_commands/
control.rs

1// Copyright © 2024 Stephan Kunz
2
3//! Commands for `DiMAS` control & monitoring programs
4
5#[doc(hidden)]
6extern crate alloc;
7
8#[cfg(feature = "std")]
9extern crate std;
10
11// region:		--- modules
12use crate::messages::AboutEntity;
13use alloc::{
14	string::{String, ToString},
15	vec::Vec,
16};
17use dimas_com::{traits::CommunicatorImplementationMethods, zenoh::Communicator};
18use dimas_core::{
19	Result,
20	enums::{OperationState, Signal},
21	message_types::Message,
22	utils::selector_from,
23};
24#[cfg(feature = "std")]
25use std::collections::HashMap;
26// endregion:	--- modules
27
28// region:		--- set_state
29/// Set the [`OperationState`] of `DiMAS` entities
30/// # Errors
31#[cfg(feature = "std")]
32pub fn set_state(
33	com: &Communicator,
34	base_selector: &String,
35	state: Option<OperationState>,
36) -> Result<Vec<AboutEntity>> {
37	let mut map: HashMap<String, AboutEntity> = HashMap::new();
38
39	let selector = selector_from("signal", Some(base_selector));
40	let message = Message::encode(&Signal::State { state });
41	// set state for entities matching the selector
42	com.get(
43		&selector,
44		Some(message),
45		Some(&mut |response| -> Result<()> {
46			let response: AboutEntity = response.decode()?;
47			map.entry(response.zid().to_string())
48				.or_insert(response);
49			Ok(())
50		}),
51	)?;
52
53	let result: Vec<AboutEntity> = map.values().cloned().collect();
54
55	Ok(result)
56}
57// endregion:	--- set_state
58
59// region:		--- shutdown
60/// Shutdown of `DiMAS` entities
61/// # Errors
62#[cfg(feature = "std")]
63pub fn shutdown(com: &Communicator, base_selector: &String) -> Result<Vec<AboutEntity>> {
64	let mut map: HashMap<String, AboutEntity> = HashMap::new();
65
66	let selector = selector_from("signal", Some(base_selector));
67	let message = Message::encode(&Signal::Shutdown);
68	// set state for entities matching the selector
69	com.get(
70		&selector,
71		Some(message),
72		Some(&mut |response| -> Result<()> {
73			let response: AboutEntity = response.decode()?;
74			map.entry(response.zid().to_string())
75				.or_insert(response);
76			Ok(())
77		}),
78	)?;
79
80	let result: Vec<AboutEntity> = map.values().cloned().collect();
81
82	Ok(result)
83}
84// endregion:	--- shutdown