mecha10-cli 0.1.47

Mecha10 CLI tool
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use anyhow::Result;
use serde_json::json;
use std::fs;
use tempfile::TempDir;

/// End-to-end integration test for simulation generation
///
/// Tests the complete flow:
/// 1. Create mecha10.json config
/// 2. Generate simulation scenes
/// 3. Validate .tscn files exist and are valid
#[test]
fn test_sim_generation_e2e_rover() -> Result<()> {
    // Create temporary project directory
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    // 1. Create mecha10.json config (rover template)
    let config = json!({
        "robot": {
            "id": "test-rover-001",
            "platform": "rover"
        },
        "drivers": [
            {
                "name": "lidar_front",
                "type": "lidar",
                "physics": {
                    "mount_point": [0.15, 0.0, 0.25]
                }
            },
            {
                "name": "camera_front",
                "type": "camera",
                "physics": {
                    "mount_point": [0.2, 0.0, 0.25],
                    "rotation": [0.0, 0.0, 0.0]
                }
            },
            {
                "name": "imu",
                "type": "imu"
            },
            {
                "name": "motor",
                "type": "motor"
            }
        ],
        "nodes": {
            "custom": []
        }
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    // 2. Generate simulation
    // TODO: This requires refactoring CLI to expose generation as library function
    // For now, test the individual components

    // Test config parsing
    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    assert_eq!(parsed["robot"]["platform"], "rover");
    assert_eq!(parsed["drivers"].as_array().unwrap().len(), 4);

    // Extract driver types
    let drivers = parsed["drivers"].as_array().unwrap();
    let driver_types: Vec<&str> = drivers.iter().filter_map(|d| d["type"].as_str()).collect();

    assert!(driver_types.contains(&"lidar"));
    assert!(driver_types.contains(&"camera"));
    assert!(driver_types.contains(&"imu"));
    assert!(driver_types.contains(&"motor"));

    // Verify sensors have physics config (except IMU)
    for driver in drivers {
        let driver_type = driver["type"].as_str().unwrap();
        if driver_type == "lidar" || driver_type == "camera" {
            assert!(
                driver.get("physics").is_some(),
                "{} driver should have physics config",
                driver_type
            );

            if let Some(physics) = driver.get("physics") {
                if let Some(mount_point) = physics.get("mount_point") {
                    let mp = mount_point.as_array().unwrap();
                    assert_eq!(mp.len(), 3, "mount_point should have 3 elements [x, y, z]");
                }
            }
        }
    }

    Ok(())
}

#[test]
fn test_sim_generation_multi_sensor() -> Result<()> {
    // Test with multiple instances of same sensor type
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "id": "multi-sensor-rover",
            "platform": "rover"
        },
        "drivers": [
            {
                "name": "lidar_front",
                "type": "lidar",
                "physics": {
                    "mount_point": [0.15, 0.0, 0.25]
                }
            },
            {
                "name": "lidar_rear",
                "type": "lidar",
                "physics": {
                    "mount_point": [-0.15, 0.0, 0.25],
                    "rotation": [0.0, std::f64::consts::PI, 0.0]  // 180 degrees
                }
            },
            {
                "name": "camera_front",
                "type": "camera",
                "physics": {
                    "mount_point": [0.2, 0.0, 0.3]
                }
            },
            {
                "name": "camera_rear",
                "type": "camera",
                "physics": {
                    "mount_point": [-0.2, 0.0, 0.3],
                    "rotation": [0.0, std::f64::consts::PI, 0.0]
                }
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    // Verify config structure
    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    let drivers = parsed["drivers"].as_array().unwrap();
    assert_eq!(drivers.len(), 4, "Should have 4 sensors");

    // Verify each sensor has unique name
    let names: Vec<&str> = drivers.iter().filter_map(|d| d["name"].as_str()).collect();

    assert_eq!(names.len(), 4);
    assert!(names.contains(&"lidar_front"));
    assert!(names.contains(&"lidar_rear"));
    assert!(names.contains(&"camera_front"));
    assert!(names.contains(&"camera_rear"));

    // Verify rotation is applied to rear sensors
    for driver in drivers {
        if driver["name"].as_str().unwrap().contains("rear") {
            assert!(
                driver["physics"]["rotation"].is_array(),
                "Rear sensor should have rotation"
            );
        }
    }

    Ok(())
}

#[test]
fn test_sim_generation_humanoid_template() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "platform": "humanoid"
        },
        "drivers": [
            {
                "name": "camera_head",
                "type": "camera",
                "physics": {
                    "mount_point": [0.0, 0.0, 1.6]  // Head height
                }
            },
            {
                "name": "imu",
                "type": "imu"
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    assert_eq!(parsed["robot"]["platform"], "humanoid");

    let drivers = parsed["drivers"].as_array().unwrap();
    let has_camera = drivers.iter().any(|d| d["type"] == "camera");
    let has_imu = drivers.iter().any(|d| d["type"] == "imu");

    assert!(has_camera, "Humanoid should have camera");
    assert!(has_imu, "Humanoid should have IMU");

    Ok(())
}

#[test]
fn test_sim_generation_arm_template() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "platform": "arm"
        },
        "drivers": [
            {
                "name": "camera_wrist",
                "type": "camera",
                "config": {
                    "depth": true  // RGBD camera
                },
                "physics": {
                    "mount_point": [0.0, 0.0, 0.05]  // End effector
                }
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    assert_eq!(parsed["robot"]["platform"], "arm");

    let drivers = parsed["drivers"].as_array().unwrap();
    let camera = &drivers[0];

    assert_eq!(camera["type"], "camera");
    assert_eq!(camera["config"]["depth"], true, "Arm camera should support depth");

    Ok(())
}

#[test]
fn test_config_validation_missing_required_fields() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    // Invalid config: missing robot platform
    let invalid_config = json!({
        "robot": {},
        "drivers": []
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&invalid_config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    // Should be missing platform
    assert!(parsed["robot"]["platform"].is_null(), "Platform should be missing");

    Ok(())
}

#[test]
fn test_sensor_mount_point_validation() -> Result<()> {
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "platform": "rover"
        },
        "drivers": [
            {
                "name": "lidar_front",
                "type": "lidar",
                "physics": {
                    "mount_point": [0.15, 0.0, 0.25]
                }
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    let mount_point = parsed["drivers"][0]["physics"]["mount_point"].as_array().unwrap();

    // Validate mount point format
    assert_eq!(mount_point.len(), 3, "Mount point should have 3 coordinates");

    for coord in mount_point {
        assert!(
            coord.is_f64() || coord.is_i64(),
            "Mount point coordinates should be numbers"
        );
    }

    Ok(())
}

#[test]
fn test_motors_excluded_from_sensors() -> Result<()> {
    // Motors should not be included in sensor configurations
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "platform": "rover"
        },
        "drivers": [
            {
                "name": "lidar_front",
                "type": "lidar",
                "physics": {
                    "mount_point": [0.15, 0.0, 0.25]
                }
            },
            {
                "name": "motor",
                "type": "motor"  // Should be filtered out from sensors
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    let drivers = parsed["drivers"].as_array().unwrap();

    // Get only sensors (filter out motors)
    let sensors: Vec<&serde_json::Value> = drivers.iter().filter(|d| d["type"].as_str() != Some("motor")).collect();

    assert_eq!(sensors.len(), 1, "Should have 1 sensor (lidar), motor excluded");
    assert_eq!(sensors[0]["type"], "lidar");

    Ok(())
}

#[test]
fn test_error_recovery_invalid_sensor_config() -> Result<()> {
    // Test that unknown sensor types are handled gracefully
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "platform": "rover"
        },
        "drivers": [
            {
                "name": "lidar_front",
                "type": "lidar",
                "physics": {
                    "mount_point": [0.15, 0.0, 0.25]
                }
            },
            {
                "name": "unknown_sensor",
                "type": "unknown_type",  // Invalid sensor type
                "physics": {
                    "mount_point": [0.0, 0.0, 0.3]
                }
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    let drivers = parsed["drivers"].as_array().unwrap();

    // Verify config includes both valid and invalid sensors
    assert_eq!(drivers.len(), 2);

    let sensor_types: Vec<&str> = drivers.iter().filter_map(|d| d["type"].as_str()).collect();

    assert!(sensor_types.contains(&"lidar"));
    assert!(sensor_types.contains(&"unknown_type"));

    // In actual generation, unknown_type should be skipped with a warning
    // but the valid lidar sensor should be added successfully

    Ok(())
}

#[test]
fn test_graceful_degradation_some_sensors_fail() -> Result<()> {
    // Test that partial sensor failures don't abort generation
    // Generation should continue if at least one sensor succeeds
    let temp_dir = TempDir::new()?;
    let project_path = temp_dir.path();

    let config = json!({
        "robot": {
            "platform": "rover"
        },
        "drivers": [
            {
                "name": "lidar_valid",
                "type": "lidar",
                "physics": {
                    "mount_point": [0.15, 0.0, 0.25]
                }
            },
            {
                "name": "camera_valid",
                "type": "camera",
                "physics": {
                    "mount_point": [0.2, 0.0, 0.25]
                }
            },
            {
                "name": "invalid_sensor_1",
                "type": "fake_sensor",
                "physics": {
                    "mount_point": [0.0, 0.0, 0.3]
                }
            },
            {
                "name": "invalid_sensor_2",
                "type": "another_fake",
                "physics": {
                    "mount_point": [0.0, 0.0, 0.4]
                }
            }
        ]
    });

    let config_path = project_path.join("mecha10.json");
    fs::write(&config_path, serde_json::to_string_pretty(&config)?)?;

    let config_content = fs::read_to_string(&config_path)?;
    let parsed: serde_json::Value = serde_json::from_str(&config_content)?;

    let drivers = parsed["drivers"].as_array().unwrap();
    assert_eq!(drivers.len(), 4, "Should have 4 drivers total");

    // Count valid vs invalid sensors
    let valid_sensors: Vec<&serde_json::Value> = drivers
        .iter()
        .filter(|d| {
            let sensor_type = d["type"].as_str().unwrap_or("");
            sensor_type == "lidar" || sensor_type == "camera" || sensor_type == "imu"
        })
        .collect();

    let invalid_sensors: Vec<&serde_json::Value> = drivers
        .iter()
        .filter(|d| {
            let sensor_type = d["type"].as_str().unwrap_or("");
            sensor_type != "lidar" && sensor_type != "camera" && sensor_type != "imu" && sensor_type != "motor"
        })
        .collect();

    assert_eq!(valid_sensors.len(), 2, "Should have 2 valid sensors");
    assert_eq!(invalid_sensors.len(), 2, "Should have 2 invalid sensors");

    // In actual generation:
    // - The 2 valid sensors should be added successfully
    // - The 2 invalid sensors should fail with warnings
    // - Generation should complete because some sensors succeeded
    // - Only if ALL sensors fail should generation abort

    Ok(())
}