1use crate::messages::{JointState, Twist};
2use crate::node::Capability;
3use crate::{Mecha10Error, Result};
4use anyhow::Context as _;
5use serde::de::DeserializeOwned;
6use std::env;
7use std::fs;
8use std::path::Path;
9
10pub mod defaults {
11 pub fn default_odom_rate_hz() -> f32 {
13 50.0
14 }
15
16 pub fn default_max_linear_vel() -> f32 {
18 10.0
19 }
20
21 pub fn default_max_angular_vel() -> f32 {
23 5.0
24 }
25
26 pub fn default_max_acceleration() -> f32 {
33 8.0
34 }
35
36 pub fn default_camera_width() -> u32 {
39 360
40 }
41
42 pub fn default_camera_height() -> u32 {
44 360
45 }
46}
47
48pub const LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR: &str = "MECHA10_LOCOMOTION_MAX_LINEAR_SPEED";
49pub const LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR: &str = "MECHA10_LOCOMOTION_MAX_ANGULAR_SPEED";
50pub const LOCOMOTION_MAX_ACCELERATION_ENV_VAR: &str = "MECHA10_LOCOMOTION_ACCELERATION";
51
52#[derive(Debug, Clone, Copy, PartialEq)]
53pub struct LocomotionLimits {
54 pub max_linear_vel: f32,
55 pub max_angular_vel: f32,
56 pub max_acceleration: f32,
57}
58
59pub fn locomotion_limits() -> LocomotionLimits {
65 LocomotionLimits {
66 max_linear_vel: env_f32_or(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR, defaults::default_max_linear_vel()),
67 max_angular_vel: env_f32_or(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR, defaults::default_max_angular_vel()),
68 max_acceleration: env_f32_or(
69 LOCOMOTION_MAX_ACCELERATION_ENV_VAR,
70 defaults::default_max_acceleration(),
71 ),
72 }
73}
74
75fn env_f32_or(key: &str, default: f32) -> f32 {
76 env::var(key).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
77}
78
79fn env_u32_or(key: &str, default: u32) -> u32 {
80 env::var(key).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
81}
82
83pub const CAMERA_WIDTH_ENV_VAR: &str = "MECHA10_CAMERA_WIDTH";
84pub const CAMERA_HEIGHT_ENV_VAR: &str = "MECHA10_CAMERA_HEIGHT";
85
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct CameraDimensions {
88 pub width: u32,
89 pub height: u32,
90}
91
92pub fn camera_dimensions() -> CameraDimensions {
101 CameraDimensions {
102 width: env_u32_or(CAMERA_WIDTH_ENV_VAR, defaults::default_camera_width()),
103 height: env_u32_or(CAMERA_HEIGHT_ENV_VAR, defaults::default_camera_height()),
104 }
105}
106
107pub const ACTUATOR_JOINT_LIMITS_ENV_VAR: &str = "MECHA10_ACTUATOR_JOINT_LIMITS";
108
109#[derive(Debug, Clone, Copy, PartialEq)]
110pub struct JointLimits {
111 pub min_angle_rad: f32,
112 pub max_angle_rad: f32,
113}
114
115#[derive(serde::Deserialize)]
116struct JointLimitEntry {
117 joint_id: String,
118 min_angle_rad: f32,
119 max_angle_rad: f32,
120}
121
122pub fn joint_limits(joint_id: &str) -> Option<JointLimits> {
132 let raw = env::var(ACTUATOR_JOINT_LIMITS_ENV_VAR).ok()?;
133 let entries: Vec<JointLimitEntry> = serde_json::from_str(&raw).ok()?;
134 entries
135 .into_iter()
136 .find(|entry| entry.joint_id == joint_id)
137 .map(|entry| JointLimits {
138 min_angle_rad: entry.min_angle_rad,
139 max_angle_rad: entry.max_angle_rad,
140 })
141}
142
143pub const CAPABILITIES_ENV_VAR: &str = "MECHA10_CAPABILITIES";
144pub const ACTUATION_JOINT_NAMES_ENV_VAR: &str = "MECHA10_ACTUATION_JOINT_NAMES";
145
146#[derive(Debug, Clone, PartialEq)]
151pub enum ControllerMode {
152 Locomotion,
153 Joints { joint_names: Vec<String> },
154}
155
156pub fn controller_mode() -> ControllerMode {
171 let capabilities: Vec<Capability> = env::var(CAPABILITIES_ENV_VAR)
172 .ok()
173 .and_then(|raw| serde_json::from_str(&raw).ok())
174 .unwrap_or_default();
175
176 if capabilities.contains(&Capability::Joints) && !capabilities.contains(&Capability::Locomotion) {
177 let joint_names: Vec<String> = env::var(ACTUATION_JOINT_NAMES_ENV_VAR)
178 .ok()
179 .and_then(|raw| serde_json::from_str(&raw).ok())
180 .unwrap_or_default();
181 return ControllerMode::Joints { joint_names };
182 }
183
184 ControllerMode::Locomotion
185}
186
187pub fn generate_locomotion_command(linear: f32, angular: f32) -> Twist {
192 let limits = locomotion_limits();
193 let mut twist = Twist::new_2d(linear, angular);
194 twist.clamp(limits.max_linear_vel, limits.max_angular_vel);
195 twist
196}
197
198pub fn generate_joint_command(joint_name: &str, angle_rad: f32) -> JointState {
203 let angle_rad = match joint_limits(joint_name) {
204 Some(limits) => angle_rad.clamp(limits.min_angle_rad, limits.max_angle_rad),
205 None => angle_rad,
206 };
207 JointState::with_positions(vec![joint_name.to_string()], vec![angle_rad])
208}
209
210pub fn env_or_default(key: &str, default: &str) -> String {
222 env::var(key).unwrap_or_else(|_| default.to_string())
223}
224
225pub fn to_websocket_url(url: &str) -> String {
245 if let Some(rest) = url.strip_prefix("https://") {
246 format!("wss://{}", rest)
247 } else if let Some(rest) = url.strip_prefix("http://") {
248 format!("ws://{}", rest)
249 } else {
250 format!("wss://{}", url)
251 }
252}
253
254pub fn relay_url(control_plane_url: &str) -> String {
271 if let Ok(url) = env::var("WEBRTC_RELAY_URL") {
272 return url;
273 }
274
275 format!("{}/webrtc-relay", to_websocket_url(control_plane_url))
276}
277
278pub fn lookup_environment<'a, E>(env: &str, dev: &'a E, staging: Option<&'a E>, prod: Option<&'a E>) -> Option<&'a E> {
288 match env {
289 "dev" | "development" => Some(dev),
290 "staging" => staging,
291 "prod" | "production" => prod,
292 _ => None,
293 }
294}
295
296pub fn current_environment<'a, E>(env_name: &str, dev: &'a E, staging: Option<&'a E>, prod: Option<&'a E>) -> &'a E {
302 lookup_environment(env_name, dev, staging, prod).unwrap_or(dev)
303}
304
305pub fn robot_process_env(
338 control_plane_url: &str,
339 relay_url: &str,
340 redis_url: &str,
341 robot_id: &str,
342 api_key: Option<&str>,
343) -> Vec<(&'static str, String)> {
344 let mut env = vec![
345 ("CONTROL_PLANE_URL", control_plane_url.to_string()),
346 ("WEBRTC_RELAY_URL", relay_url.to_string()),
347 ("REDIS_URL", redis_url.to_string()),
348 ("ROBOT_ID", robot_id.to_string()),
349 ];
350 if let Some(key) = api_key {
351 env.push(("ROBOT_API_KEY", key.to_string()));
352 }
353 env
354}
355
356pub fn load_config<T, P>(path: P) -> Result<T>
402where
403 T: DeserializeOwned,
404 P: AsRef<Path>,
405{
406 let path = path.as_ref();
407
408 let content = fs::read_to_string(path)
409 .with_context(|| format!("Failed to read config file at '{}'", path.display()))
410 .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
411
412 let content = substitute_env_vars(&content)
413 .with_context(|| format!("Failed to substitute environment variables in '{}'", path.display()))
414 .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
415
416 let value: serde_json::Value = match path.extension().and_then(|s| s.to_str()) {
417 Some("json") => serde_json::from_str(&content)
418 .with_context(|| format!("Failed to parse JSON config from '{}'", path.display()))
419 .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?,
420 Some("yaml") | Some("yml") => serde_yaml::from_str(&content)
421 .with_context(|| format!("Failed to parse YAML config from '{}'", path.display()))
422 .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?,
423 Some("toml") => {
424 let toml_value: toml::Value = toml::from_str(&content)
425 .with_context(|| format!("Failed to parse TOML config from '{}'", path.display()))
426 .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
427 serde_json::to_value(toml_value)
428 .map_err(|e| Mecha10Error::Configuration(format!("Failed to convert TOML: {}", e)))?
429 }
430 Some(ext) => {
431 return Err(Mecha10Error::Configuration(format!(
432 "Unsupported config file extension: {}",
433 ext
434 )));
435 }
436 None => {
437 return Err(Mecha10Error::Configuration("Config file has no extension".to_string()));
438 }
439 };
440
441 let final_value = extract_env_config(value);
442
443 let config: T = serde_json::from_value(final_value)
444 .with_context(|| format!("Failed to parse config from '{}'", path.display()))
445 .map_err(|e| Mecha10Error::Configuration(format!("{:#}", e)))?;
446
447 Ok(config)
448}
449
450fn extract_env_config(value: serde_json::Value) -> serde_json::Value {
457 let env_keys = ["dev", "development", "prod", "production", "staging", "test"];
458
459 if let serde_json::Value::Object(ref map) = value {
460 let current_env = env::var("MECHA10_ENV").unwrap_or_else(|_| "development".to_string());
461
462 let env_key = match current_env.as_str() {
463 "development" | "dev" => {
464 if map.contains_key("dev") {
465 "dev"
466 } else {
467 "development"
468 }
469 }
470 "production" | "prod" => {
471 if map.contains_key("production") {
472 "production"
473 } else {
474 "prod"
475 }
476 }
477 other => other,
478 };
479
480 if let Some(env_config) = map.get(env_key) {
481 return env_config.clone();
482 }
483
484 let has_any_env_keys = map.keys().any(|k| env_keys.contains(&k.as_str()));
485 if has_any_env_keys {
486 return serde_json::Value::Object(serde_json::Map::new());
487 }
488
489 return serde_json::Value::Object(serde_json::Map::new());
490 }
491
492 serde_json::Value::Object(serde_json::Map::new())
493}
494
495pub fn load_config_from_env<T>(prefix: &str) -> Result<T>
517where
518 T: DeserializeOwned,
519{
520 let mut config_map = serde_json::Map::new();
521
522 for (key, value) in env::vars() {
523 if let Some(suffix) = key.strip_prefix(&format!("{}_", prefix)) {
524 let json_key = suffix.to_lowercase();
525
526 let json_value = serde_json::from_str(&value).unwrap_or(serde_json::Value::String(value));
527
528 config_map.insert(json_key, json_value);
529 }
530 }
531
532 let config: T = serde_json::from_value(serde_json::Value::Object(config_map))
533 .map_err(|e| Mecha10Error::Configuration(format!("Failed to parse config from environment: {}", e)))?;
534
535 Ok(config)
536}
537
538pub fn substitute_env_vars(input: &str) -> Result<String> {
552 let mut result = input.to_string();
553
554 let re = regex::Regex::new(r"\$\{([A-Z_][A-Z0-9_]*)\}").unwrap();
555
556 for cap in re.captures_iter(input) {
557 let var_name = &cap[1];
558 let var_value = env::var(var_name).map_err(|_| {
559 Mecha10Error::Configuration(format!(
560 "Environment variable {} not found (required by config)",
561 var_name
562 ))
563 })?;
564
565 result = result.replace(&format!("${{{}}}", var_name), &var_value);
566 }
567
568 let re = regex::Regex::new(r"\$([A-Z_][A-Z0-9_]*)").unwrap();
569
570 for cap in re.captures_iter(input) {
571 let var_name = &cap[1];
572 if let Ok(var_value) = env::var(var_name) {
573 result = result.replace(&format!("${}", var_name), &var_value);
574 }
575 }
576
577 Ok(result)
578}
579
580pub trait Validate {
581 fn validate(&self) -> Result<()>;
585}
586
587pub fn load_and_validate<T, P>(path: P) -> Result<T>
593where
594 T: DeserializeOwned + Validate,
595 P: AsRef<Path>,
596{
597 let config: T = load_config(path)?;
598 config.validate()?;
599 Ok(config)
600}
601
602#[cfg(feature = "schema-validation")]
621pub fn load_project_config<P: AsRef<Path>>(path: P) -> Result<serde_json::Value> {
622 use crate::schema_validation::load_and_validate_project;
623 load_and_validate_project(path)
624}
625
626pub fn config_key_to_path(key: &str) -> String {
641 if key == "mecha10.json" || key.starts_with("rl/") {
642 key.to_string()
643 } else {
644 format!("{}/config.json", key)
645 }
646}
647
648#[cfg(test)]
649mod tests {
650 use super::*;
651
652 #[test]
653 fn test_config_key_to_path_project_config() {
654 assert_eq!(config_key_to_path("mecha10.json"), "mecha10.json");
655 }
656
657 #[test]
658 fn test_config_key_to_path_scoped_node() {
659 assert_eq!(
660 config_key_to_path("nodes/@mecha10/motor"),
661 "nodes/@mecha10/motor/config.json"
662 );
663 }
664
665 #[test]
666 fn test_config_key_to_path_scoped_behavior() {
667 assert_eq!(
668 config_key_to_path("behaviors/@mecha10/patrol"),
669 "behaviors/@mecha10/patrol/config.json"
670 );
671 }
672
673 #[test]
674 fn test_config_key_to_path_simple_key() {
675 assert_eq!(config_key_to_path("simulation"), "simulation/config.json");
676 }
677
678 #[test]
679 fn test_config_key_to_path_rl_config() {
680 assert_eq!(config_key_to_path("rl/jobs/train.yml"), "rl/jobs/train.yml");
681 assert_eq!(config_key_to_path("rl/jobs/train-cat.yml"), "rl/jobs/train-cat.yml");
682 }
683
684 #[test]
685 fn test_to_websocket_url_https() {
686 assert_eq!(to_websocket_url("https://mecha.industries"), "wss://mecha.industries");
687 }
688
689 #[test]
690 fn test_to_websocket_url_http() {
691 assert_eq!(to_websocket_url("http://localhost:8000"), "ws://localhost:8000");
692 }
693
694 #[test]
695 fn test_to_websocket_url_no_scheme() {
696 assert_eq!(to_websocket_url("mecha.industries"), "wss://mecha.industries");
697 }
698
699 #[test]
700 fn test_robot_process_env_with_api_key() {
701 let env = robot_process_env(
702 "https://api.mecha.industries",
703 "wss://api.mecha.industries/webrtc-relay",
704 "redis://localhost:6379",
705 "robot-001",
706 Some("secret-key"),
707 );
708 assert_eq!(
709 env,
710 vec![
711 ("CONTROL_PLANE_URL", "https://api.mecha.industries".to_string()),
712 (
713 "WEBRTC_RELAY_URL",
714 "wss://api.mecha.industries/webrtc-relay".to_string()
715 ),
716 ("REDIS_URL", "redis://localhost:6379".to_string()),
717 ("ROBOT_ID", "robot-001".to_string()),
718 ("ROBOT_API_KEY", "secret-key".to_string()),
719 ]
720 );
721 }
722
723 #[test]
724 fn test_robot_process_env_without_api_key_omits_it() {
725 let env = robot_process_env(
726 "https://api.mecha.industries",
727 "wss://api.mecha.industries/webrtc-relay",
728 "redis://localhost:6379",
729 "robot-001",
730 None,
731 );
732 assert!(!env.iter().any(|(k, _)| *k == "ROBOT_API_KEY"));
733 assert_eq!(env.len(), 4);
734 }
735
736 struct AlwaysValid;
737
738 impl Validate for AlwaysValid {
739 fn validate(&self) -> Result<()> {
740 Ok(())
741 }
742 }
743
744 struct AlwaysInvalid;
745
746 impl Validate for AlwaysInvalid {
747 fn validate(&self) -> Result<()> {
748 Err(Mecha10Error::Configuration("always invalid".to_string()))
749 }
750 }
751
752 #[test]
753 fn test_validate_ok_for_a_valid_impl() {
754 assert!(AlwaysValid.validate().is_ok());
755 }
756
757 #[test]
758 fn test_validate_propagates_errors_for_an_invalid_impl() {
759 let err = AlwaysInvalid.validate().unwrap_err();
760 assert!(matches!(err, Mecha10Error::Configuration(_)));
761 }
762
763 static LOCOMOTION_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
764
765 #[test]
766 fn test_locomotion_limits_falls_back_to_compiled_defaults_when_env_unset() {
767 let _guard = LOCOMOTION_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
768 env::remove_var(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR);
769 env::remove_var(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR);
770 env::remove_var(LOCOMOTION_MAX_ACCELERATION_ENV_VAR);
771
772 let limits = locomotion_limits();
773
774 assert_eq!(limits.max_linear_vel, defaults::default_max_linear_vel());
775 assert_eq!(limits.max_angular_vel, defaults::default_max_angular_vel());
776 assert_eq!(limits.max_acceleration, defaults::default_max_acceleration());
777 }
778
779 #[test]
780 fn test_locomotion_limits_reads_env_vars_when_set() {
781 let _guard = LOCOMOTION_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
782 env::set_var(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR, "2.5");
783 env::set_var(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR, "3.5");
784 env::set_var(LOCOMOTION_MAX_ACCELERATION_ENV_VAR, "4.5");
785
786 let limits = locomotion_limits();
787
788 assert_eq!(limits.max_linear_vel, 2.5);
789 assert_eq!(limits.max_angular_vel, 3.5);
790 assert_eq!(limits.max_acceleration, 4.5);
791
792 env::remove_var(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR);
793 env::remove_var(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR);
794 env::remove_var(LOCOMOTION_MAX_ACCELERATION_ENV_VAR);
795 }
796
797 static CAMERA_DIMENSIONS_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
798
799 #[test]
800 fn test_camera_dimensions_falls_back_to_compiled_defaults_when_env_unset() {
801 let _guard = CAMERA_DIMENSIONS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
802 env::remove_var(CAMERA_WIDTH_ENV_VAR);
803 env::remove_var(CAMERA_HEIGHT_ENV_VAR);
804
805 let dims = camera_dimensions();
806
807 assert_eq!(dims.width, defaults::default_camera_width());
808 assert_eq!(dims.height, defaults::default_camera_height());
809 }
810
811 #[test]
812 fn test_camera_dimensions_reads_env_vars_when_set() {
813 let _guard = CAMERA_DIMENSIONS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
814 env::set_var(CAMERA_WIDTH_ENV_VAR, "640");
815 env::set_var(CAMERA_HEIGHT_ENV_VAR, "480");
816
817 let dims = camera_dimensions();
818
819 assert_eq!(dims.width, 640);
820 assert_eq!(dims.height, 480);
821
822 env::remove_var(CAMERA_WIDTH_ENV_VAR);
823 env::remove_var(CAMERA_HEIGHT_ENV_VAR);
824 }
825
826 static ACTUATOR_JOINT_LIMITS_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
827
828 #[test]
829 fn test_joint_limits_returns_none_when_env_unset() {
830 let _guard = ACTUATOR_JOINT_LIMITS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
831 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
832
833 assert_eq!(joint_limits("shoulder"), None);
834 }
835
836 #[test]
837 fn test_joint_limits_returns_matching_joint_id() {
838 let _guard = ACTUATOR_JOINT_LIMITS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
839 env::set_var(
840 ACTUATOR_JOINT_LIMITS_ENV_VAR,
841 r#"[{"joint_id":"shoulder","min_angle_rad":-1.5,"max_angle_rad":1.5},{"joint_id":"elbow","min_angle_rad":0.0,"max_angle_rad":2.0}]"#,
842 );
843
844 assert_eq!(
845 joint_limits("shoulder"),
846 Some(JointLimits {
847 min_angle_rad: -1.5,
848 max_angle_rad: 1.5,
849 })
850 );
851 assert_eq!(
852 joint_limits("elbow"),
853 Some(JointLimits {
854 min_angle_rad: 0.0,
855 max_angle_rad: 2.0,
856 })
857 );
858
859 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
860 }
861
862 #[test]
863 fn test_joint_limits_returns_none_when_joint_id_absent() {
864 let _guard = ACTUATOR_JOINT_LIMITS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
865 env::set_var(
866 ACTUATOR_JOINT_LIMITS_ENV_VAR,
867 r#"[{"joint_id":"elbow","min_angle_rad":0.0,"max_angle_rad":2.0}]"#,
868 );
869
870 assert_eq!(joint_limits("shoulder"), None);
871
872 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
873 }
874
875 #[test]
876 fn test_joint_limits_returns_none_on_malformed_json() {
877 let _guard = ACTUATOR_JOINT_LIMITS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
878 env::set_var(ACTUATOR_JOINT_LIMITS_ENV_VAR, "not valid json");
879
880 assert_eq!(joint_limits("shoulder"), None);
881
882 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
883 }
884
885 static CONTROLLER_MODE_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
886
887 fn clear_controller_mode_env() {
888 env::remove_var(CAPABILITIES_ENV_VAR);
889 env::remove_var(ACTUATION_JOINT_NAMES_ENV_VAR);
890 }
891
892 #[test]
893 fn test_controller_mode_defaults_to_locomotion_when_env_unset() {
894 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
895 clear_controller_mode_env();
896
897 assert_eq!(controller_mode(), ControllerMode::Locomotion);
898 }
899
900 #[test]
901 fn test_controller_mode_defaults_to_locomotion_on_malformed_json() {
902 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
903 clear_controller_mode_env();
904 env::set_var(CAPABILITIES_ENV_VAR, "not valid json");
905
906 assert_eq!(controller_mode(), ControllerMode::Locomotion);
907
908 clear_controller_mode_env();
909 }
910
911 #[test]
912 fn test_controller_mode_is_locomotion_when_only_locomotion_declared() {
913 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
914 clear_controller_mode_env();
915 env::set_var(CAPABILITIES_ENV_VAR, r#"["locomotion"]"#);
916
917 assert_eq!(controller_mode(), ControllerMode::Locomotion);
918
919 clear_controller_mode_env();
920 }
921
922 #[test]
923 fn test_controller_mode_is_joints_when_only_joints_declared() {
924 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
925 clear_controller_mode_env();
926 env::set_var(CAPABILITIES_ENV_VAR, r#"["joints"]"#);
927 env::set_var(ACTUATION_JOINT_NAMES_ENV_VAR, r#"["shoulder","elbow"]"#);
928
929 assert_eq!(
930 controller_mode(),
931 ControllerMode::Joints {
932 joint_names: vec!["shoulder".to_string(), "elbow".to_string()]
933 }
934 );
935
936 clear_controller_mode_env();
937 }
938
939 #[test]
940 fn test_controller_mode_joints_with_no_joint_names_env_is_empty() {
941 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
942 clear_controller_mode_env();
943 env::set_var(CAPABILITIES_ENV_VAR, r#"["joints"]"#);
944
945 assert_eq!(controller_mode(), ControllerMode::Joints { joint_names: vec![] });
946
947 clear_controller_mode_env();
948 }
949
950 #[test]
951 fn test_controller_mode_locomotion_wins_when_both_declared() {
952 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
953 clear_controller_mode_env();
954 env::set_var(CAPABILITIES_ENV_VAR, r#"["joints","locomotion"]"#);
955 env::set_var(ACTUATION_JOINT_NAMES_ENV_VAR, r#"["shoulder"]"#);
956
957 assert_eq!(controller_mode(), ControllerMode::Locomotion);
958
959 clear_controller_mode_env();
960 }
961
962 #[test]
963 fn test_controller_mode_locomotion_when_unrelated_capabilities_declared() {
964 let _guard = CONTROLLER_MODE_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
965 clear_controller_mode_env();
966 env::set_var(CAPABILITIES_ENV_VAR, r#"["vision","audio"]"#);
967
968 assert_eq!(controller_mode(), ControllerMode::Locomotion);
969
970 clear_controller_mode_env();
971 }
972
973 #[test]
974 fn test_generate_locomotion_command_clamps_to_configured_limits() {
975 let _guard = LOCOMOTION_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
976 env::set_var(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR, "1.0");
977 env::set_var(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR, "2.0");
978
979 let twist = generate_locomotion_command(5.0, 10.0);
980
981 assert_eq!(twist.linear_speed(), 1.0);
982 assert_eq!(twist.angular_speed(), 2.0);
983
984 env::remove_var(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR);
985 env::remove_var(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR);
986 env::remove_var(LOCOMOTION_MAX_ACCELERATION_ENV_VAR);
987 }
988
989 #[test]
990 fn test_generate_locomotion_command_passes_through_within_limits() {
991 let _guard = LOCOMOTION_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
992 env::remove_var(LOCOMOTION_MAX_LINEAR_VEL_ENV_VAR);
993 env::remove_var(LOCOMOTION_MAX_ANGULAR_VEL_ENV_VAR);
994 env::remove_var(LOCOMOTION_MAX_ACCELERATION_ENV_VAR);
995
996 let twist = generate_locomotion_command(1.0, 0.5);
997
998 assert_eq!(twist.linear[0], 1.0);
999 assert_eq!(twist.angular[2], 0.5);
1000 }
1001
1002 #[test]
1003 fn test_generate_joint_command_clamps_to_configured_joint_limits() {
1004 let _guard = ACTUATOR_JOINT_LIMITS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1005 env::set_var(
1006 ACTUATOR_JOINT_LIMITS_ENV_VAR,
1007 r#"[{"joint_id":"shoulder","min_angle_rad":-1.0,"max_angle_rad":1.0}]"#,
1008 );
1009
1010 let joint_state = generate_joint_command("shoulder", 5.0);
1011
1012 assert_eq!(joint_state.names, vec!["shoulder".to_string()]);
1013 assert_eq!(joint_state.positions, vec![1.0]);
1014
1015 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
1016 }
1017
1018 #[test]
1019 fn test_generate_joint_command_passes_through_when_no_limit_configured() {
1020 let _guard = ACTUATOR_JOINT_LIMITS_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
1021 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
1022
1023 let joint_state = generate_joint_command("shoulder", 3.0);
1024
1025 assert_eq!(joint_state.positions, vec![3.0]);
1026
1027 env::remove_var(ACTUATOR_JOINT_LIMITS_ENV_VAR);
1028 }
1029}