Skip to content

Commit b0b2b06

Browse files
committed
ROS2: error handling
1 parent b86f3f2 commit b0b2b06

9 files changed

Lines changed: 200 additions & 21 deletions

File tree

‎docs/python-ros2.mdx‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ In ROS2, functionality is organised in **nodes** which exchange data by publishi
2222

2323
OpEn can generate ready-to-use ROS2 packages directly from a parametric optimizer. The generated package exposes the optimizer as a ROS2 node, includes the required message definitions, and provides the files needed to build, configure, and launch it inside a ROS2 workspace.
2424

25-
The input and output messages are the same as in the [ROS1 package documentation](./python-ros#messages).
25+
The input message matches the [ROS1 package documentation](./python-ros#messages). The ROS2 output message additionally includes `error_code` and `error_message` fields so that invalid requests and solver failures can be reported with more detail.
2626

2727
## Configuration Parameters
2828

@@ -180,6 +180,8 @@ solution:
180180
inner_iterations: 41
181181
outer_iterations: 6
182182
status: 0
183+
error_code: 0
184+
error_message: ''
183185
cost: 1.1656771801253916
184186
norm_fpr: 2.1973496274068953e-05
185187
penalty: 150000.0
@@ -198,11 +200,14 @@ solve_time_ms: 0.2175
198200
uint8 STATUS_NOT_CONVERGED_OUT_OF_TIME=2
199201
uint8 STATUS_NOT_CONVERGED_COST=3
200202
uint8 STATUS_NOT_CONVERGED_FINITE_COMPUTATION=4
203+
uint8 STATUS_INVALID_REQUEST=5
201204
202205
float64[] solution # solution
203206
uint8 inner_iterations # number of inner iterations
204207
uint16 outer_iterations # number of outer iterations
205-
uint8 status # status code
208+
uint8 status # coarse status code
209+
int32 error_code # detailed error code (0 on success)
210+
string error_message # detailed error message (empty on success)
206211
float64 cost # cost value at solution
207212
float64 norm_fpr # norm of FPR of last inner problem
208213
float64 penalty # penalty value
@@ -213,6 +218,8 @@ solve_time_ms: 0.2175
213218
```
214219
</details>
215220

221+
If the request is invalid, the node publishes a result with `status: 5` (`STATUS_INVALID_REQUEST`) and fills `error_code` and `error_message`. For example, if the parameter vector has the wrong length, `error_code` is `3003` and `error_message` explains the mismatch.
222+
216223
Instead of starting the node with `ros2 run`, you can also use the generated launch file:
217224

218225
```bash

‎open-codegen/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Note: This is the Changelog file of `opengen` - the Python interface of OpEn
2222
- Breaking change: the direct interface (Python bindings) now has an API which mirrors that of the TCP interface: the method `solve` returns either a solution or an error object. Website documentation is updated. New unit tests are implemented. Note that `solver.run()` does not return the solution object directly, but rather works in the same way as the TCP interface: it returns a response object (instance of `SolverResponse`), on which the method `.get()` returns either a `SolverStatus` or `SolverError`.
2323
- Added helpful `__repr__` methods to generated Python binding response/status/error objects, TCP solver response/error objects, and `GeneratedOptimizer` for easier inspection and debugging
2424
- Updated generated TCP server and C interface templates to work with the richer Rust solver error model and expose better failure information to clients
25+
- ROS2 generated packages now publish detailed `error_code` and `error_message` fields, plus `STATUS_INVALID_REQUEST`, so invalid requests and solver failures are reported explicitly instead of being silently ignored
2526

2627

2728
## [0.10.1] - 2026-03-25

‎open-codegen/opengen/templates/c/example_optimizer_c_bindings.c‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ int main(void) {
6767
printf(" Solver Statistics\n");
6868
printf("-------------------------------------------------\n");
6969
printf("exit status : %d\n", status.exit_status);
70+
printf("error code : %d\n", status.error_code);
71+
printf("error message : %s\n", status.error_message);
7072
printf("iterations : %lu\n", status.num_inner_iterations);
7173
printf("outer iterations : %lu\n", status.num_outer_iterations);
7274
printf("solve time : %f ms\n", (double)status.solve_time_ns / 1000000.0);
@@ -83,4 +85,3 @@ int main(void) {
8385

8486
return 0;
8587
}
86-

‎open-codegen/opengen/templates/c/optimizer_cinterface.rs.jinja‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,31 @@ pub struct {{meta.optimizer_name}}Cache {
88
cache: AlmCache,
99
}
1010

11+
const {{meta.optimizer_name|upper}}_NO_ERROR_CODE: c_int = 0;
12+
const {{meta.optimizer_name|upper}}_SOLVER_ERROR_CODE: c_int = 2000;
13+
const {{meta.optimizer_name|upper}}_ERROR_MESSAGE_CAPACITY: usize = 256;
14+
1115
impl {{meta.optimizer_name}}Cache {
1216
pub fn new(cache: AlmCache) -> Self {
1317
{{meta.optimizer_name}}Cache { cache }
1418
}
1519
}
1620

21+
fn empty_error_message() -> [c_char; 256] {
22+
[0 as c_char; 256]
23+
}
24+
25+
fn error_message_to_c_array(
26+
message: &str,
27+
) -> [c_char; 256] {
28+
let mut buffer = empty_error_message();
29+
let max_len = {{meta.optimizer_name|upper}}_ERROR_MESSAGE_CAPACITY - 1;
30+
for (idx, byte) in message.as_bytes().iter().copied().take(max_len).enumerate() {
31+
buffer[idx] = byte as c_char;
32+
}
33+
buffer
34+
}
35+
1736
/// {{meta.optimizer_name}} version of ExitStatus
1837
/// Structure: `{{meta.optimizer_name}}ExitStatus`
1938
#[allow(non_camel_case_types)]
@@ -41,6 +60,10 @@ pub enum {{meta.optimizer_name}}ExitStatus {
4160
pub struct {{meta.optimizer_name}}SolverStatus {
4261
/// Exit status
4362
exit_status: {{meta.optimizer_name}}ExitStatus,
63+
/// Detailed error code (0 on success)
64+
error_code: c_int,
65+
/// Detailed error message (empty string on success)
66+
error_message: [c_char; 256],
4467
/// Number of outer iterations
4568
num_outer_iterations: c_ulong,
4669
/// Total number of inner iterations
@@ -150,6 +173,8 @@ pub unsafe extern "C" fn {{meta.optimizer_name|lower}}_solve(
150173
core::ExitStatus::NotConvergedIterations => {{meta.optimizer_name}}ExitStatus::{{meta.optimizer_name}}NotConvergedIterations,
151174
core::ExitStatus::NotConvergedOutOfTime => {{meta.optimizer_name}}ExitStatus::{{meta.optimizer_name}}NotConvergedOutOfTime,
152175
},
176+
error_code: {{meta.optimizer_name|upper}}_NO_ERROR_CODE,
177+
error_message: empty_error_message(),
153178
num_outer_iterations: status.num_outer_iterations() as c_ulong,
154179
num_inner_iterations: status.num_inner_iterations() as c_ulong,
155180
last_problem_norm_fpr: status.last_problem_norm_fpr(),
@@ -177,14 +202,18 @@ pub unsafe extern "C" fn {{meta.optimizer_name|lower}}_solve(
177202
}
178203
}
179204
},
180-
Err(e) => {{meta.optimizer_name}}SolverStatus {
205+
Err(e) => {
206+
let error_message = format!("problem solution failed: {}", e);
207+
{{meta.optimizer_name}}SolverStatus {
181208
exit_status: match e {
182209
SolverError::Cost(_)
183210
| SolverError::ProjectionFailed(_)
184211
| SolverError::LinearAlgebraFailure(_)
185212
| SolverError::InvalidProblemState(_) => {{meta.optimizer_name}}ExitStatus::{{meta.optimizer_name}}NotConvergedCost,
186213
SolverError::NotFiniteComputation(_) => {{meta.optimizer_name}}ExitStatus::{{meta.optimizer_name}}NotConvergedNotFiniteComputation,
187214
},
215+
error_code: {{meta.optimizer_name|upper}}_SOLVER_ERROR_CODE,
216+
error_message: error_message_to_c_array(&error_message),
188217
num_outer_iterations: u64::MAX as c_ulong,
189218
num_inner_iterations: u64::MAX as c_ulong,
190219
last_problem_norm_fpr: f64::INFINITY,
@@ -196,6 +225,7 @@ pub unsafe extern "C" fn {{meta.optimizer_name|lower}}_solve(
196225
lagrange: {%- if problem.dim_constraints_aug_lagrangian() > 0 -%}
197226
[0.0; {{meta.optimizer_name|upper}}_N1]
198227
{%- else -%}std::ptr::null::<c_double>(){%- endif %}
228+
}
199229
},
200230
}
201231
}

‎open-codegen/opengen/templates/optimizer.rs.jinja‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
//
66

77
{% if activate_clib_generation -%}
8-
use libc::{c_double, c_ulong, c_ulonglong};
8+
use libc::{c_char, c_double, c_int, c_ulong, c_ulonglong};
99
{% endif %}
1010
use optimization_engine::{constraints::*, panoc::*, alm::*, *};
1111

‎open-codegen/opengen/templates/ros2/OptimizationResult.msg‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,14 @@ uint8 STATUS_NOT_CONVERGED_ITERATIONS=1
44
uint8 STATUS_NOT_CONVERGED_OUT_OF_TIME=2
55
uint8 STATUS_NOT_CONVERGED_COST=3
66
uint8 STATUS_NOT_CONVERGED_FINITE_COMPUTATION=4
7+
uint8 STATUS_INVALID_REQUEST=5
78

89
float64[] solution # optimizer (solution)
910
uint8 inner_iterations # number of inner iterations
1011
uint16 outer_iterations # number of outer iterations
11-
uint8 status # status code
12+
uint8 status # coarse status code
13+
int32 error_code # detailed error code (0 on success)
14+
string error_message # detailed error message (empty on success)
1215
float64 cost # cost at solution
1316
float64 norm_fpr # norm of FPR of last inner problem
1417
float64 penalty # penalty value

‎open-codegen/opengen/templates/ros2/README.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,10 @@ guess for the vector of Lagrange multipliers and the initial value
103103
of the penalty value. `OptimizationResult` is a message containing
104104
all information related to the solution of the optimization
105105
problem, including the optimal solution, the solver status,
106-
solution time, Lagrange multiplier vector and more.
106+
solution time, Lagrange multiplier vector and more. The ROS2
107+
result message also includes `error_code` and `error_message`
108+
fields so invalid requests and solver failures can be diagnosed
109+
without inspecting logs.
107110

108111
The message structures are defined in the following msg files:
109112

‎open-codegen/opengen/templates/ros2/open_optimizer.cpp‎

Lines changed: 79 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#include <cstdint>
99
#include <functional>
1010
#include <memory>
11+
#include <sstream>
1112
#include <string>
1213
#include <vector>
1314

@@ -36,6 +37,10 @@ class OptimizationEngineNode : public rclcpp::Node {
3637
rclcpp::Subscription<OptimizationParametersMsg>::SharedPtr subscriber_;
3738
rclcpp::TimerBase::SharedPtr timer_;
3839

40+
static constexpr int32_t kInvalidInitialGuessErrorCode = 1600;
41+
static constexpr int32_t kInvalidInitialYErrorCode = 1700;
42+
static constexpr int32_t kInvalidParameterErrorCode = 3003;
43+
3944
static std::chrono::milliseconds rateToPeriod(double rate)
4045
{
4146
if (rate <= 0.0) {
@@ -48,29 +53,90 @@ class OptimizationEngineNode : public rclcpp::Node {
4853
return std::chrono::milliseconds(period_ms);
4954
}
5055

51-
void updateInputData()
56+
std::string makeDimensionErrorMessage(
57+
const char* label,
58+
size_t provided,
59+
size_t expected) const
60+
{
61+
std::ostringstream oss;
62+
oss << label << ": provided " << provided << ", expected " << expected;
63+
return oss.str();
64+
}
65+
66+
void setErrorResult(
67+
uint8_t status,
68+
int32_t error_code,
69+
const std::string& error_message)
70+
{
71+
results_.solution.clear();
72+
results_.lagrange_multipliers.clear();
73+
results_.inner_iterations = 0;
74+
results_.outer_iterations = 0;
75+
results_.status = status;
76+
results_.error_code = error_code;
77+
results_.error_message = error_message;
78+
results_.cost = 0.0;
79+
results_.norm_fpr = 0.0;
80+
results_.penalty = 0.0;
81+
results_.infeasibility_f1 = 0.0;
82+
results_.infeasibility_f2 = 0.0;
83+
results_.solve_time_ms = 0.0;
84+
}
85+
86+
bool validateAndUpdateInputData()
5287
{
5388
init_penalty_ = (params_.initial_penalty > 1.0)
5489
? params_.initial_penalty
5590
: ROS2_NODE_{{meta.optimizer_name|upper}}_DEFAULT_INITIAL_PENALTY;
5691

57-
if (params_.parameter.size() == {{meta.optimizer_name|upper}}_NUM_PARAMETERS) {
58-
for (size_t i = 0; i < {{meta.optimizer_name|upper}}_NUM_PARAMETERS; ++i) {
59-
p_[i] = params_.parameter[i];
60-
}
92+
if (params_.parameter.size() != {{meta.optimizer_name|upper}}_NUM_PARAMETERS) {
93+
setErrorResult(
94+
OptimizationResultMsg::STATUS_INVALID_REQUEST,
95+
kInvalidParameterErrorCode,
96+
makeDimensionErrorMessage(
97+
"wrong number of parameters",
98+
params_.parameter.size(),
99+
{{meta.optimizer_name|upper}}_NUM_PARAMETERS));
100+
return false;
101+
}
102+
for (size_t i = 0; i < {{meta.optimizer_name|upper}}_NUM_PARAMETERS; ++i) {
103+
p_[i] = params_.parameter[i];
61104
}
62105

106+
if (!params_.initial_guess.empty()
107+
&& params_.initial_guess.size() != {{meta.optimizer_name|upper}}_NUM_DECISION_VARIABLES) {
108+
setErrorResult(
109+
OptimizationResultMsg::STATUS_INVALID_REQUEST,
110+
kInvalidInitialGuessErrorCode,
111+
makeDimensionErrorMessage(
112+
"initial guess has incompatible dimensions",
113+
params_.initial_guess.size(),
114+
{{meta.optimizer_name|upper}}_NUM_DECISION_VARIABLES));
115+
return false;
116+
}
63117
if (params_.initial_guess.size() == {{meta.optimizer_name|upper}}_NUM_DECISION_VARIABLES) {
64118
for (size_t i = 0; i < {{meta.optimizer_name|upper}}_NUM_DECISION_VARIABLES; ++i) {
65119
u_[i] = params_.initial_guess[i];
66120
}
67121
}
68122

123+
if (!params_.initial_y.empty() && params_.initial_y.size() != {{meta.optimizer_name|upper}}_N1) {
124+
setErrorResult(
125+
OptimizationResultMsg::STATUS_INVALID_REQUEST,
126+
kInvalidInitialYErrorCode,
127+
makeDimensionErrorMessage(
128+
"wrong dimension of Lagrange multipliers",
129+
params_.initial_y.size(),
130+
{{meta.optimizer_name|upper}}_N1));
131+
return false;
132+
}
69133
if (params_.initial_y.size() == {{meta.optimizer_name|upper}}_N1) {
70134
for (size_t i = 0; i < {{meta.optimizer_name|upper}}_N1; ++i) {
71135
y_[i] = params_.initial_y[i];
72136
}
73137
}
138+
139+
return true;
74140
}
75141

76142
{{meta.optimizer_name}}SolverStatus solve()
@@ -106,6 +172,8 @@ class OptimizationEngineNode : public rclcpp::Node {
106172
results_.cost = status.cost;
107173
results_.penalty = status.penalty;
108174
results_.status = static_cast<uint8_t>(status.exit_status);
175+
results_.error_code = status.error_code;
176+
results_.error_message = std::string(status.error_message);
109177
results_.solve_time_ms = static_cast<double>(status.solve_time_ns) / 1000000.0;
110178
results_.infeasibility_f2 = status.f2_norm;
111179
results_.infeasibility_f1 = status.delta_y_norm_over_c;
@@ -123,10 +191,15 @@ class OptimizationEngineNode : public rclcpp::Node {
123191
return;
124192
}
125193
initializeSolverIfNeeded();
126-
updateInputData();
194+
if (!validateAndUpdateInputData()) {
195+
publisher_->publish(results_);
196+
has_received_request_ = false;
197+
return;
198+
}
127199
{{meta.optimizer_name}}SolverStatus status = solve();
128200
updateResults(status);
129201
publisher_->publish(results_);
202+
has_received_request_ = false;
130203
}
131204

132205
public:

0 commit comments

Comments
 (0)