openrr_apps_robot_command/
robot_command.rs

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
use std::path::PathBuf;

use anyhow::Result;
use clap::{CommandFactory, Parser};
use clap_complete::Shell;
use openrr_apps::{
    utils::{init_tracing, init_tracing_with_file_appender, LogConfig},
    Error, RobotConfig,
};
use openrr_client::BoxRobotClient;
use openrr_command::{RobotCommand, RobotCommandExecutor};
use tracing::info;

/// An openrr command line tool.
#[derive(Parser, Debug)]
#[clap(name = env!("CARGO_BIN_NAME"))]
struct RobotCommandArgs {
    /// Path to the setting file.
    #[clap(short, long, value_parser)]
    config_path: Option<PathBuf>,
    /// Set options from command line. These settings take priority over the
    /// setting file specified by --config-path.
    #[clap(long)]
    config: Option<String>,
    #[clap(subcommand)]
    command: Option<RobotCommand>,
    /// Prints the default setting as TOML.
    #[clap(long)]
    show_default_config: bool,
    /// Use interactive mode
    #[clap(short, long)]
    interactive: bool,
    /// Path to log directory for tracing FileAppender.
    #[clap(long, value_parser)]
    log_directory: Option<PathBuf>,
}

fn shell_completion(shell_type: openrr_command::ShellType) {
    clap_complete::generate(
        Shell::from(shell_type),
        &mut RobotCommandArgs::command(),
        env!("CARGO_BIN_NAME"),
        &mut std::io::stdout(),
    );
}

#[tokio::main]
async fn main() -> Result<()> {
    let args = RobotCommandArgs::parse();
    if args.log_directory.is_none() {
        init_tracing();
    }
    #[cfg(not(feature = "ros"))]
    let _guard = args.log_directory.as_ref().map(|log_directory| {
        init_tracing_with_file_appender(
            LogConfig {
                directory: log_directory.to_path_buf(),
                ..Default::default()
            },
            env!("CARGO_BIN_NAME").to_string(),
        )
    });

    info!("ParsedArgs {args:?}");

    if args.show_default_config {
        print!("{}", toml::to_string(&RobotConfig::default()).unwrap());
        return Ok(());
    }

    // Outputs shell completion script and exit.
    if let Some(RobotCommand::ShellCompletion(shell_type)) = args.command.as_ref() {
        shell_completion(*shell_type);
        return Ok(());
    }

    let config_path = openrr_apps::utils::get_apps_robot_config(args.config_path);

    let robot_config =
        openrr_apps::utils::resolve_robot_config(config_path.as_deref(), args.config.as_deref())?;

    openrr_apps::utils::init_with_anonymize(env!("CARGO_BIN_NAME"), &robot_config);
    #[cfg(feature = "ros")]
    let _guard = args.log_directory.map(|log_directory| {
        init_tracing_with_file_appender(
            LogConfig {
                directory: log_directory,
                ..Default::default()
            },
            if robot_config.has_ros_clients() {
                arci_ros::name()
            } else {
                env!("CARGO_BIN_NAME").to_string()
            },
        )
    });
    let client: BoxRobotClient = robot_config.create_robot_client()?;
    let executor = RobotCommandExecutor {};

    if args.interactive {
        Ok(executor.run_interactive_shell(&client).await?)
    } else {
        let command = args.command.ok_or(Error::NoCommand)?;
        Ok(executor.execute(&client, &command).await?)
    }
}

#[cfg(test)]
mod tests {
    use std::{env, path::Path};

    use openrr_command::load_command_file_and_filter;
    use tracing::log::error;

    use super::*;

    #[test]
    fn parse_args() {
        let bin = env!("CARGO_BIN_NAME");
        assert!(RobotCommandArgs::try_parse_from([bin]).is_ok());
        assert!(RobotCommandArgs::try_parse_from([bin, "--show-default-config"]).is_ok());
        assert!(RobotCommandArgs::try_parse_from([bin, "--config-path", "path", "list"]).is_ok());
        assert!(RobotCommandArgs::try_parse_from([
            bin,
            "--show-default-config",
            "--config-path",
            "path"
        ])
        .is_ok());
    }

    #[test]
    fn assert_app() {
        RobotCommandArgs::command().debug_assert();
    }

    const COMMAND_PATHS: [&str; 11] = [
        "command/sample_cmd_urdf_viz.txt",
        "command/pr2_cmd_collision.txt",
        "command/pr2_cmd_ik.txt",
        "command/pr2_cmd_joints.txt",
        "command/pr2_cmd_ros.txt",
        "command/pr2_cmd_urdf_viz.txt",
        "command/ur10_cmd_collision.txt",
        "command/ur10_cmd_ik.txt",
        "command/ur10_cmd_joints.txt",
        "command/ur10_cmd_ros.txt",
        "command/ur10_cmd_urdf_viz.txt",
    ];

    #[test]
    fn assert_commands() {
        for command_path in COMMAND_PATHS {
            let bin = env!("CARGO_BIN_NAME");
            let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));

            let config_path = manifest_dir.join("config/sample_robot_client_for_urdf_viz.toml");
            let config_path_arg = "--config-path=".to_string() + config_path.to_str().unwrap();
            let sample_command_path = manifest_dir.join(command_path);

            let sample_command = RobotCommandArgs::try_parse_from([
                bin,
                config_path_arg.as_str(),
                "load_commands",
                sample_command_path.to_str().unwrap(),
            ])
            .unwrap();
            let mut results = Vec::new();

            let command = sample_command.command.ok_or(Error::NoCommand).unwrap();

            check_command(&command, &mut results, command_path);

            for result in results {
                assert!(result);
            }
        }
    }

    fn check_command(command: &RobotCommand, log: &mut Vec<bool>, command_path: &str) {
        match &command {
            RobotCommand::SendJoints {
                name: _,
                duration,
                use_interpolation: _,
                joint: _,
                max_resolution_for_interpolation: _,
                min_number_of_points_for_interpolation: _,
            } => {
                log.push(*duration >= 0f64);
            }
            RobotCommand::SendJointsPose {
                name: _,
                pose_name: _,
                duration,
            } => {
                log.push(*duration >= 0f64);
            }
            RobotCommand::MoveIk {
                name: _,
                x: _,
                y: _,
                z: _,
                yaw: _,
                pitch: _,
                roll: _,
                duration,
                use_interpolation: _,
                is_local: _,
                max_resolution_for_interpolation: _,
                min_number_of_points_for_interpolation: _,
            } => {
                log.push(*duration >= 0f64);
            }
            RobotCommand::GetState { name: _ } => log.push(true),
            RobotCommand::LoadCommands { command_file_path } => {
                let target_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
                let target_command_file_path = target_dir.join(command_path);
                log.push(*command_file_path == target_command_file_path);

                for command in load_command_file_and_filter(target_command_file_path).unwrap() {
                    let command_parsed_iter = command.split_whitespace();
                    let read_opt = RobotCommand::try_parse_from(command_parsed_iter);
                    match read_opt {
                        Ok(robot_command) => {
                            check_command(&robot_command, log, command_path);
                        }
                        Err(err) => {
                            error!("Error in {:?}: {}", command_file_path, err);
                            log.push(false);
                        }
                    }
                }
            }
            RobotCommand::List => {
                log.push(true);
            }
            RobotCommand::Speak {
                name: _,
                message: _,
            } => {
                log.push(true);
            }
            RobotCommand::ExecuteCommand { command: _ } => {
                log.push(true);
            }
            RobotCommand::GetNavigationCurrentPose => {
                log.push(true);
            }
            RobotCommand::SendNavigationGoal {
                x: _,
                y: _,
                yaw: _,
                frame_id: _,
                timeout_secs: _,
            } => {
                log.push(true);
            }
            RobotCommand::CancelNavigationGoal => {
                log.push(true);
            }
            RobotCommand::SendBaseVelocity {
                x: _,
                y: _,
                theta: _,
                duration_secs,
            } => {
                log.push(*duration_secs >= 0f64);
            }
            _ => {
                log.push(false);
            }
        }
    }
}