Skip to main content

mecha10_core/
config.rs

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    /// Default odometry update rate in Hz.
12    pub fn default_odom_rate_hz() -> f32 {
13        50.0
14    }
15
16    /// Default maximum linear velocity in m/s.
17    pub fn default_max_linear_vel() -> f32 {
18        10.0
19    }
20
21    /// Default maximum angular velocity in rad/s.
22    pub fn default_max_angular_vel() -> f32 {
23        5.0
24    }
25
26    /// Default physics acceleration ceiling in m/s^2. Matches the `mecha10 init`-scaffolded
27    /// `mecha10.json` template's own value (`config/mecha10.json.template`) - a project that
28    /// deletes its `actuator.locomotion` block entirely should still get reasonably fast
29    /// movement, not fall back to the old, overly conservative `2.0` that pre-dates
30    /// `mecha10.json` being the sole source for this value (acceleration used to also come from
31    /// the robot model's own `model.json`, which bundled `5.0` for the stock rover).
32    pub fn default_max_acceleration() -> f32 {
33        8.0
34    }
35
36    /// Default real-camera width in pixels - square, so sim and real camera always agree on
37    /// aspect ratio with no project-level config required.
38    pub fn default_camera_width() -> u32 {
39        360
40    }
41
42    /// Default real-camera height in pixels - see [`default_camera_width`].
43    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
59/// Resolve this process's locomotion limits from the env vars `mecha10 dev`/`mecha10 run`
60/// inject from the project's `mecha10.json` `actuator.locomotion`. Every node that
61/// enforces or reports linear/angular velocity (motor, teleop, llm-command, rl, navigation
62/// behaviors) calls this instead of carrying its own config field or compiled default -
63/// there is exactly one place in a project to set these values.
64pub 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
92/// Resolve this process's camera dimensions from the env vars `mecha10 dev`/`mecha10 run`
93/// inject from the project's `mecha10.json` `vision.camera_dimensions` - the single place a
94/// project sets its camera's resolution, consumed by both the real `camera` node (as its
95/// capture resolution default) and the simulated camera (`mecha10-sim`'s Godot scene
96/// generator), so sim and real frames agree on aspect ratio instead of drifting apart (the
97/// sim camera was previously hardcoded to a square 84x84 regardless of the real camera's
98/// landscape default, which is what produced mismatched object-detection results between sim
99/// and real). Mirrors [`locomotion_limits`]'s pattern exactly.
100pub 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
122/// Resolve `joint_id`'s joint angle limits from the project's `mecha10.json` `actuator.joints`
123/// array, injected by `mecha10 dev`/`mecha10 run` as one JSON-encoded env var
124/// (`MECHA10_ACTUATOR_JOINT_LIMITS`, a `[{"joint_id": ..., "min_angle_rad": ..., "max_angle_rad":
125/// ...}, ...]` array) - mirrors `locomotion_limits()`'s role for drivetrain nodes, but for an
126/// open-ended set of named actuators rather than 3 fixed scalars, so it can't be individual env
127/// vars. Returns `None` when the env var is unset or `joint_id` isn't in it - callers (e.g. the
128/// `servo`/`pan-tilt` nodes in `mecha10-nodes`, out of scope here) fall back to their own
129/// per-instance config default in that case, the same "project config wins, node default is the
130/// fallback" precedent `NodeConfigBase` already establishes.
131pub 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/// Which actuation surface this project wants a controller node (teleop, rl, llm-command, ...)
147/// to drive: whole-robot drivetrain velocity commands, or named per-joint angle commands.
148/// Mirrors [`Capability::Locomotion`]/[`Capability::Joints`] exactly - deliberately reuses those
149/// variants' naming rather than inventing a parallel vocabulary.
150#[derive(Debug, Clone, PartialEq)]
151pub enum ControllerMode {
152    Locomotion,
153    Joints { joint_names: Vec<String> },
154}
155
156/// Resolve this process's controller mode from the env vars `mecha10 dev`/`mecha10 run` inject
157/// from the project's `mecha10.json` top-level `capabilities` array and `actuator.joints` names
158/// (`MECHA10_CAPABILITIES`, a JSON-encoded array of [`Capability`] strings, and
159/// `MECHA10_ACTUATION_JOINT_NAMES`, a JSON-encoded array of joint name strings) - the shared
160/// mechanism a controller node (teleop, rl, llm-command in `mecha10-nodes`) calls instead of
161/// hardcoding "am I a locomotion controller or a joints controller" via its own ad hoc config
162/// key, mirroring [`locomotion_limits`]/[`joint_limits`]'s "one project-level source of truth"
163/// pattern.
164///
165/// When both `locomotion` and `joints` are declared, locomotion wins - matching the existing
166/// precedent in `mecha10_rl`'s `mecha10_gym.py` (`"joints" in capabilities and "locomotion" not
167/// in capabilities`). When neither is set (env var unset, malformed, or an empty/unrelated
168/// capabilities list), this also falls back to `Locomotion` - the same "else" branch that
169/// Python precedent takes.
170pub 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
187/// Build a locomotion drivetrain command, clamped to the project's configured
188/// [`locomotion_limits`] - the shared way a controller node (teleop, rl, llm-command) turns a
189/// desired linear/angular velocity into a safe-to-publish [`Twist`], instead of clamping (or
190/// forgetting to clamp) against its own copy of the limits.
191pub 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
198/// Build a single-joint command, clamped to `joint_name`'s configured [`joint_limits`] (if the
199/// project declares any for that joint - otherwise the requested angle is passed through
200/// unclamped, matching [`joint_limits`]'s own "no project limit configured" fallback) - the
201/// shared way a controller node turns a desired joint angle into a safe-to-publish [`JointState`].
202pub 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
210/// Read an environment variable, falling back to `default` if it's unset (or
211/// not valid unicode).
212///
213/// # Example
214///
215/// ```
216/// use mecha10_core::config::env_or_default;
217///
218/// std::env::remove_var("MECHA10_EXAMPLE_ENV_VAR");
219/// assert_eq!(env_or_default("MECHA10_EXAMPLE_ENV_VAR", "fallback"), "fallback");
220/// ```
221pub fn env_or_default(key: &str, default: &str) -> String {
222    env::var(key).unwrap_or_else(|_| default.to_string())
223}
224
225/// Convert an `http(s)://` URL into its `ws(s)://` equivalent.
226///
227/// - `https://` is replaced with `wss://`
228/// - `http://` is replaced with `ws://`
229/// - if the input has no recognized scheme prefix at all, `wss://` is
230///   prepended rather than leaving the URL scheme-less. A schemeless URL
231///   (e.g. a `control_plane` value copied from config without a protocol)
232///   would otherwise silently produce a malformed relay URL that fails to
233///   connect.
234///
235/// # Example
236///
237/// ```
238/// use mecha10_core::config::to_websocket_url;
239///
240/// assert_eq!(to_websocket_url("https://example.com"), "wss://example.com");
241/// assert_eq!(to_websocket_url("http://example.com"), "ws://example.com");
242/// assert_eq!(to_websocket_url("example.com"), "wss://example.com");
243/// ```
244pub 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
254/// Build the WebRTC relay URL for camera signaling from a resolved control plane base URL:
255/// an explicit `WEBRTC_RELAY_URL` env var override if set, else the control plane URL converted
256/// to a websocket scheme (see [`to_websocket_url`]) with `/webrtc-relay` appended.
257///
258/// Shared by `mecha10-cli-core`'s `EnvironmentsConfig::relay_url` and `launcher-service`'s
259/// `ProjectConfig::relay_url` (LAB-2892, cargo-dupes group E89), which were byte-for-byte
260/// identical modulo the `self`/method they're defined on.
261///
262/// # Example
263///
264/// ```
265/// use mecha10_core::config::relay_url;
266///
267/// std::env::remove_var("WEBRTC_RELAY_URL");
268/// assert_eq!(relay_url("https://mecha.industries"), "wss://mecha.industries/webrtc-relay");
269/// ```
270pub 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
278/// Resolve the environment config matching a symbolic environment name ("dev"/"development",
279/// "staging", "prod"/"production", anything else -> `None`).
280///
281/// Generic over the per-environment config type `E` since `mecha10-cli-core`'s and
282/// `launcher-service`'s `EnvironmentConfig` types carry different fields; `prod` is `Option<&E>`
283/// so callers whose `prod` slot is unconditionally populated (not itself optional) can just pass
284/// `Some(&self.prod)`.
285///
286/// Shared by both crates' `EnvironmentsConfig::get` (LAB-2892, cargo-dupes group N53).
287pub 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
296/// Resolve the config for the currently active environment, falling back to `dev` when
297/// [`lookup_environment`] finds no match for `env_name` (e.g. `staging`/`prod` selected but not
298/// configured in this project).
299///
300/// Shared by both crates' `EnvironmentsConfig::current` (LAB-2892, cargo-dupes group E88).
301pub 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
305/// Build the base set of environment variables that a spawned robot/node process needs to
306/// reach the control plane, WebRTC relay, and Redis, and to identify itself.
307///
308/// This is the subset that's genuinely identical between `mecha10 dev`'s node spawning
309/// (`packages/cli/src/handlers/dev/ops/spawn.rs`'s `project_env` construction) and the
310/// launcher service's `start_robot_binary`
311/// (`packages/launcher-service/src/service.rs`) - both derive `CONTROL_PLANE_URL`,
312/// `WEBRTC_RELAY_URL`, `REDIS_URL`, and `ROBOT_ID`/`ROBOT_API_KEY` from the same inputs, so
313/// this gives them one place to do it instead of two hand-rolled copies. Callers layer their
314/// own extras on top (e.g. the launcher additionally sets `MECHA10_ENV`,
315/// `MECHA10_PLATFORM_URL`, `MECHA10_DEVICE_ID`, and `MECHA10_`-prefixed duplicates of these
316/// same values; `mecha10 dev` additionally injects TURN credentials and simulator overrides).
317///
318/// `api_key` is `None` when there are no credentials to inject (e.g. not logged in) - in that
319/// case `ROBOT_API_KEY` is simply omitted from the result rather than set to an empty string,
320/// matching `mecha10 dev`'s existing behavior.
321///
322/// # Example
323///
324/// ```
325/// use mecha10_core::config::robot_process_env;
326///
327/// let env = robot_process_env(
328///     "https://api.mecha.industries",
329///     "wss://api.mecha.industries/webrtc-relay",
330///     "redis://localhost:6379",
331///     "robot-001",
332///     Some("secret-key"),
333/// );
334/// assert!(env.contains(&("CONTROL_PLANE_URL", "https://api.mecha.industries".to_string())));
335/// assert!(env.contains(&("ROBOT_API_KEY", "secret-key".to_string())));
336/// ```
337pub 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
356/// Load configuration from a file with environment variable substitution.
357///
358/// Supports:
359/// - JSON, YAML, TOML files (based on extension)
360/// - Environment variable substitution with `${VAR_NAME}` syntax
361/// - Environment-specific config sections (dev, production, staging)
362/// - Validation via serde
363///
364/// This does *not* run [`Validate::validate`] -- stable Rust has no
365/// specialization, so a generic function over `T` can't conditionally call a
366/// trait method only when `T` happens to implement it. Use
367/// [`load_and_validate`] instead for config types that implement
368/// [`Validate`]; its `T: Validate` bound is real, so it can (and does) call
369/// `validate()` unconditionally.
370///
371/// # Environment Selection
372///
373/// If the config file has top-level keys matching environment names (dev, development,
374/// prod, production, staging), the function will select the appropriate section based
375/// on the `MECHA10_ENV` environment variable (defaults to "development").
376///
377/// # Example
378///
379/// ```rust,no_run
380/// use mecha10_core::prelude::*;
381///
382/// #[derive(Debug, Deserialize)]
383/// struct MyConfig {
384///     rate: f32,
385///     endpoint: String,
386/// }
387///
388/// # fn main() -> Result<()> {
389/// // Load from file
390/// let config: MyConfig = load_config("config.yaml")?;
391///
392/// // If config.json contains:
393/// // {
394/// //   "dev": { "rate": 10.0, "endpoint": "http://localhost" },
395/// //   "production": { "rate": 1.0, "endpoint": "https://api.example.com" }
396/// // }
397/// // And MECHA10_ENV=development, then config will use the "dev" section
398/// # Ok(())
399/// # }
400/// ```
401pub 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
450/// Extract environment-specific config section.
451///
452/// Node configs MUST have environment keys (dev, development, prod, production, staging, test).
453/// Returns the appropriate section based on MECHA10_ENV (defaults to "development").
454///
455/// Flat configs are not supported - all node configs must be nested by environment.
456fn 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
495/// Load configuration from environment variables with a prefix.
496///
497/// # Example
498///
499/// ```rust,no_run
500/// use mecha10_core::prelude::*;
501///
502/// #[derive(Debug, Deserialize)]
503/// struct MyConfig {
504///     rate: f32,
505///     endpoint: String,
506/// }
507///
508/// # fn main() -> Result<()> {
509/// // Load from environment variables:
510/// // MYAPP_RATE=10.5
511/// // MYAPP_ENDPOINT=http://localhost:8080
512/// let config: MyConfig = load_config_from_env("MYAPP")?;
513/// # Ok(())
514/// # }
515/// ```
516pub 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
538/// Substitute environment variables in a string.
539///
540/// Syntax: `${VAR_NAME}` or `$VAR_NAME`
541///
542/// # Example
543///
544/// ```rust
545/// use mecha10_core::config::substitute_env_vars;
546///
547/// std::env::set_var("MY_VAR", "hello");
548/// let result = substitute_env_vars("Value is: ${MY_VAR}").unwrap();
549/// assert_eq!(result, "Value is: hello");
550/// ```
551pub 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    /// Validate the configuration.
582    ///
583    /// Returns an error if validation fails.
584    fn validate(&self) -> Result<()>;
585}
586
587/// Load and validate configuration.
588///
589/// This is a convenience function that combines [`load_config`] with
590/// [`Validate::validate`]: it deserializes `T` from `path`, then calls
591/// `validate()` on the result and propagates any error it returns.
592pub 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/// Load project configuration with JSON Schema validation
603///
604/// This function loads a mecha10.json file and validates it against the built-in schema.
605/// Use this for loading project-level configuration files.
606///
607/// Requires the `schema-validation` feature.
608///
609/// # Example
610///
611/// ```rust,no_run
612/// use mecha10_core::config::load_project_config;
613///
614/// fn main() -> Result<(), Box<dyn std::error::Error>> {
615///     let config = load_project_config("mecha10.json")?;
616///     println!("Project: {}", config["name"]);
617///     Ok(())
618/// }
619/// ```
620#[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
626/// Convert a config key to its on-disk display path.
627///
628/// Keys are category-prefixed (`nodes/...`, `behaviors/...`, `rl/...` - see
629/// `mecha10_robot_config::sync::derive_config_key`/`collect_rl_configs`), so the prefix already
630/// tells us which directory the config lives under; this just appends `config.json` (except for
631/// `rl/...`, whose keys are already full paths - see the `rl/jobs/train.yml` example below).
632///
633/// Examples:
634/// - `mecha10.json` -> `mecha10.json`
635/// - `nodes/@mecha10/motor` -> `nodes/@mecha10/motor/config.json`
636/// - `behaviors/@mecha10/patrol` -> `behaviors/@mecha10/patrol/config.json`
637/// - `simulation` -> `simulation/config.json`
638/// - `rl/jobs/train.yml` -> `rl/jobs/train.yml` (already a full path - see
639///   `mecha10_robot_config::sync::collect_rl_configs`, no fixed `config.json` filename)
640pub 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}