Add complete ROS 2 Jazzy & Gazebo Harmonic workspace (Panther PiPER + TurtleBot 2)

This commit is contained in:
2026-11-06 19:39:44 +01:00
commit 109d3064ab
2172 changed files with 524965 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
# Ensure Unix line endings (LF) for all text files so Linux Docker containers can execute scripts directly on Windows hosts
* text=auto eol=lf
# Binary assets
*.stl binary
*.STL binary
*.dae binary
*.DAE binary
*.obj binary
*.png binary
*.jpg binary
*.jpeg binary
*.pgm binary
*.pbstream binary
+82
View File
@@ -0,0 +1,82 @@
FROM osrf/ros:jazzy-desktop-full
ENV DEBIAN_FRONTEND=noninteractive
ENV ROS_DISTRO=jazzy
# Install Gazebo Harmonic (paired with ROS 2 Jazzy), Kobuki dependencies, colcon, and Mesa/GUI utilities
RUN apt-get update && apt-get install -y --no-install-recommends \
ros-${ROS_DISTRO}-ros-gz \
ros-${ROS_DISTRO}-kobuki-ros-interfaces \
ros-${ROS_DISTRO}-kobuki-velocity-smoother \
ros-${ROS_DISTRO}-sophus \
ros-${ROS_DISTRO}-ecl-build \
ros-${ROS_DISTRO}-teleop-twist-keyboard \
ros-${ROS_DISTRO}-teleop-twist-joy \
ros-${ROS_DISTRO}-joy-teleop \
ros-${ROS_DISTRO}-xacro \
ros-${ROS_DISTRO}-robot-state-publisher \
ros-${ROS_DISTRO}-joint-state-publisher \
ros-${ROS_DISTRO}-joint-state-publisher-gui \
ros-${ROS_DISTRO}-laser-filters \
ros-${ROS_DISTRO}-ros-testing \
ros-${ROS_DISTRO}-gz-ros2-control \
ros-${ROS_DISTRO}-ros2-control \
ros-${ROS_DISTRO}-ros2-controllers \
ros-${ROS_DISTRO}-moveit \
ros-${ROS_DISTRO}-behaviortree-cpp \
ros-${ROS_DISTRO}-generate-parameter-library \
ros-${ROS_DISTRO}-realtime-tools \
ros-${ROS_DISTRO}-robot-localization \
ros-${ROS_DISTRO}-imu-filter-madgwick \
ros-${ROS_DISTRO}-nmea-navsat-driver \
ros-${ROS_DISTRO}-phidgets-api \
ros-${ROS_DISTRO}-joy-linux \
ros-${ROS_DISTRO}-nav2-common \
ros-${ROS_DISTRO}-husarion-mecanum-drive-controller \
ros-${ROS_DISTRO}-twist-mux-controller \
ros-${ROS_DISTRO}-depthai-descriptions \
ros-${ROS_DISTRO}-kortex-description \
ros-${ROS_DISTRO}-realsense2-description \
ros-${ROS_DISTRO}-robotiq-description \
ros-${ROS_DISTRO}-ur-description \
ros-${ROS_DISTRO}-zed-description \
qtdeclarative5-dev \
qml-module-qtquick2 \
qml-module-qtquick-controls2 \
qml-module-qtquick-layouts \
qml-module-qtquick-window2 \
python3-click \
python3-transforms3d \
autoconf-archive \
libtool \
libtool-bin \
iputils-ping \
iproute2 \
libusb-1.0-0-dev \
libftdi1-dev \
python3-colcon-common-extensions \
python3-rosdep \
python3-vcstool \
git \
nano \
curl \
wget \
mesa-utils \
libgl1-mesa-dri \
libglx-mesa0 \
x11-apps \
&& rm -rf /var/lib/apt/lists/*
# Create workspace directory
WORKDIR /ros2_ws
RUN mkdir -p /ros2_ws/src
# Automatically source ROS 2 and workspace in interactive bash sessions
RUN echo "source /opt/ros/${ROS_DISTRO}/setup.bash" >> /root/.bashrc && \
echo "if [ -f /ros2_ws/install/setup.bash ]; then source /ros2_ws/install/setup.bash; fi" >> /root/.bashrc
COPY entrypoint.sh /entrypoint.sh
RUN sed -i 's/\r$//' /entrypoint.sh && chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
CMD ["bash"]
+90
View File
@@ -0,0 +1,90 @@
# ROS 2 Jazzy & Gazebo Harmonic – TurtleBot 2 (Kobuki) & Panther PiPER Setup
Dieses Setup stellt einen Docker-Container mit **ROS 2 Jazzy Jalisco** (Ubuntu 24.04), **Gazebo Harmonic** (`ros-jazzy-ros-gz`) und **MoveIt 2** bereit – vorkonfiguriert für **WSLg** (Windows 11 / WSL2) und ausgestattet mit:
1. **TurtleBot 2 (Kobuki)**: Treiber-Stack + 3D-Modell (`kobuki_description`) + Gazebo-Simulation (`turtlebot2_gazebo`).
2. **Husarion Panther UGV & AgileX PiPER 6-DOF Arm (`panther_piper`)**: Gazebo-Simulation (`panther_piper_description`), ROS 2 Control & MoveIt 2 (`panther_piper_moveit_config`).
---
## Schnellstart (Container)
### 1. Container starten / neu bauen
```powershell
docker compose up -d --build
```
### 2. Interaktive Shell im Container öffnen
```powershell
docker compose exec ros2_jazzy bash
```
---
## Roboter 1: Husarion Panther UGV & AgileX PiPER Arm (`panther_piper`)
### 1. Gazebo-Simulation starten
Im Container:
```bash
source /ros2_ws/install/setup.bash
# Karte 1: Office & Lab Layout (Standard)
ros2 launch panther_piper_description simulation.launch.py world:=office_lab.sdf
# Alternativ Karte 2: Outdoor Forest Map
ros2 launch panther_piper_description simulation.launch.py world:=forest.sdf
# Alternativ Leere Welt:
ros2 launch panther_piper_description simulation.launch.py world:=empty.sdf
```
### 2. Not-Aus (E-Stop) der Panther-Basis lösen
Die Panther-Basis spawnt wie beim echten Roboter standardmäßig mit aktivem E-Stop (`e_stop: true` auf `/hardware/e_stop`). Zum Freigeben der Räder in einem zweiten Container-Terminal ausführen:
```bash
ros2 service call /hardware/e_stop_reset std_srvs/srv/Trigger {}
```
*(Optional lässt sich der E-Stop jederzeit wieder mit `ros2 service call /hardware/e_stop_trigger std_srvs/srv/Trigger {}` auslösen.)*
### 3. Panther-Basis per Tastatur steuern (Teleop)
```bash
ros2 run teleop_twist_keyboard teleop_twist_keyboard
```
### 4. MoveIt 2 Bewegungsplanung für den PiPER-Arm starten
Während Gazebo läuft, in zwei weiteren Container-Terminals:
- **MoveGroup Server**:
```bash
ros2 launch panther_piper_moveit_config move_group.launch.py
```
- **MoveIt RViz2 GUI**:
```bash
ros2 launch panther_piper_moveit_config moveit_rviz.launch.py
```
---
## Roboter 2: TurtleBot 2 (Kobuki)
### 1. Gazebo-Simulation mit dem TurtleBot 2 starten
Im Container:
```bash
source /ros2_ws/install/setup.bash
ros2 launch turtlebot2_gazebo simulation.launch.py
```
### 2. TurtleBot 2 per Tastatur steuern (Teleop)
In einem zweiten Container-Terminal:
```bash
ros2 run teleop_twist_keyboard teleop_twist_keyboard
```
---
## Workspace bei Änderungen neu bauen
```bash
cd /ros2_ws
colcon build --symlink-install
source install/setup.bash
```
+25
View File
@@ -0,0 +1,25 @@
services:
ros2_jazzy:
build:
context: .
dockerfile: Dockerfile
container_name: ros2_jazzy_gazebo
stdin_open: true
tty: true
network_mode: host
ipc: host
environment:
- DISPLAY=${DISPLAY:-:0}
- WAYLAND_DISPLAY=${WAYLAND_DISPLAY:-wayland-0}
- XDG_RUNTIME_DIR=${XDG_RUNTIME_DIR:-/mnt/wslg/runtime-dir}
- PULSE_SERVER=${PULSE_SERVER:-/mnt/wslg/PulseServer}
- QT_X11_NO_MITSHM=1
# Software-Rendering aktivieren (stabil für CPU / integrierte Grafik in WSLg)
- LIBGL_ALWAYS_SOFTWARE=1
volumes:
# Lokalen src-Ordner in das ROS 2 Workspace im Container einbinden
- ./src:/ros2_ws/src
# WSLg Sockets für Docker Desktop unter Windows (PowerShell / CMD & WSL2)
- /run/desktop/mnt/host/wslg/.X11-unix:/tmp/.X11-unix:rw
- /run/desktop/mnt/host/wslg:/mnt/wslg:rw
+13
View File
@@ -0,0 +1,13 @@
#!/bin/bash
set -e
# Source ROS 2 Jazzy setup
source "/opt/ros/${ROS_DISTRO}/setup.bash"
# Source workspace overlay if built
if [ -f "/ros2_ws/install/setup.bash" ]; then
source "/ros2_ws/install/setup.bash"
fi
exec "$@"
+1
View File
@@ -0,0 +1 @@
+68
View File
@@ -0,0 +1,68 @@
---
BasedOnStyle: Google
AccessModifierOffset: -2
ConstructorInitializerIndentWidth: 2
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AlwaysBreakTemplateDeclarations: true
AlwaysBreakBeforeMultilineStrings: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: false
BreakConstructorInitializers: BeforeComma
BinPackParameters: true
ColumnLimit: 90
ConstructorInitializerAllOnOneLineOrOnePerLine: true
DerivePointerBinding: false
PointerBindsToType: true
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: true
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 60
PenaltyBreakString: 1
PenaltyBreakFirstLessLess: 1000
PenaltyExcessCharacter: 1000
PenaltyReturnTypeOnItsOwnLine: 90
SpacesBeforeTrailingComments: 2
Cpp11BracedListStyle: false
Standard: Auto
IndentWidth: 2
TabWidth: 2
UseTab: Never
IndentFunctionDeclarationAfterType: false
SpacesInParentheses: false
SpacesInAngles: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpaceAfterControlStatementKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: Never
ContinuationIndentWidth: 4
SortIncludes: false
SpaceAfterCStyleCast: false
ReflowComments: false
# Configure each individual brace in BraceWrapping
BreakBeforeBraces: Custom
# Control of individual brace wrapping cases
BraceWrapping: {
AfterClass: 'true',
AfterControlStatement: 'true',
AfterEnum : 'true',
AfterFunction : 'true',
AfterNamespace : 'true',
AfterStruct : 'true',
AfterUnion : 'true',
BeforeCatch : 'true',
BeforeElse : 'true',
IndentBraces : 'false',
SplitEmptyFunction: 'false'
}
...
+14
View File
@@ -0,0 +1,14 @@
name: pre-commit
on:
pull_request:
push:
branches: [master]
jobs:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v3
- uses: pre-commit/action@v3.0.1
+28
View File
@@ -0,0 +1,28 @@
name: Test
on:
pull_request:
push:
branches:
- humble
jobs:
build_and_test:
runs-on: ubuntu-latest
env:
ROS_DISTRO: ${{ matrix.ros_distro }}
container:
image: rostooling/setup-ros-docker:ubuntu-jammy-latest
strategy:
fail-fast: false
matrix:
ros_distro: [humble]
steps:
- name: Build and run tests
id: action-ros-ci
uses: ros-tooling/action-ros-ci@v0.4
with:
target-ros2-distro: ${{ matrix.ros_distro }}
- uses: actions/upload-artifact@v4
with:
name: colcon-logs
path: ros_ws/log
+32
View File
@@ -0,0 +1,32 @@
# Prerequisites
*.d
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
*.smod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
@@ -0,0 +1,44 @@
# To use:
#
# pre-commit run -a
#
# Or:
#
# pre-commit install # (runs every time you commit in git)
#
# To update this file:
#
# pre-commit autoupdate
#
# See https://github.com/pre-commit/pre-commit
exclude: ^3rdparty/|3rdparty|^include/behaviortree_cpp/contrib/
repos:
# Standard hooks
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-ast
- id: check-case-conflict
- id: check-docstring-first
- id: check-merge-conflict
- id: check-symlinks
- id: check-xml
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
exclude_types: [svg]
- id: mixed-line-ending
- id: trailing-whitespace
exclude_types: [svg]
- id: fix-byte-order-marker
# CPP hooks
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: v17.0.6
hooks:
- id: clang-format
args: ['-fallback-style=none', '-i']
File diff suppressed because it is too large Load Diff
+204
View File
@@ -0,0 +1,204 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2019 Intel Corporation
Copyright 2023 Davide Faconti
Copyright 2023 Unmanned Life
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+38
View File
@@ -0,0 +1,38 @@
# BehaviorTree.ROS2
[![Test](https://github.com/BehaviorTree/BehaviorTree.ROS2/actions/workflows/test.yml/badge.svg)](https://github.com/BehaviorTree/BehaviorTree.ROS2/actions/workflows/test.yml)
This repository contains useful wrappers to use ROS2 and BehaviorTree.CPP together.
In particular, it provides a standard way to implement:
- Behavior Tree Executor with ROS Action interface.
- Action clients.
- Service Clients.
- Topic Subscribers.
- Topic Publishers.
Our main goals are:
- to minimize the amount of boilerplate.
- to make asynchronous Actions non-blocking.
# Documentation
- [ROS Behavior Wrappers](behaviortree_ros2/ros_behavior_wrappers.md)
- [TreeExecutionServer](behaviortree_ros2/tree_execution_server.md)
- [Sample Behaviors](btcpp_ros2_samples/README.md)
Note that this library is compatible **only** with:
- **BT.CPP** 4.6 or newer.
- **ROS2** Humble or newer.
Additionally, check **plugins.hpp** to see how to learn how to
wrap your Nodes into plugins that can be loaded at run-time.
## Acknowledgements
A lot of code is either inspired or copied from [Nav2](https://docs.nav2.org/).
For this reason, we retain the same license and copyright.
@@ -0,0 +1,65 @@
cmake_minimum_required(VERSION 3.16)
project(behaviortree_ros2)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(THIS_PACKAGE_DEPS
rclcpp
rclcpp_action
ament_index_cpp
behaviortree_cpp
btcpp_ros2_interfaces
generate_parameter_library
)
find_package(ament_cmake REQUIRED)
foreach(PACKAGE ${THIS_PACKAGE_DEPS})
find_package(${PACKAGE} REQUIRED )
endforeach()
generate_parameter_library(
bt_executor_parameters
src/bt_executor_parameters.yaml)
add_library(${PROJECT_NAME}
src/bt_ros2.cpp
src/bt_utils.cpp
src/tree_execution_server.cpp
src/bt_ros_logger.cpp )
target_include_directories(${PROJECT_NAME} PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
target_link_libraries(${PROJECT_NAME} PUBLIC
rclcpp::rclcpp
rclcpp_action::rclcpp_action
ament_index_cpp::ament_index_cpp
behaviortree_cpp::behaviortree_cpp
${btcpp_ros2_interfaces_TARGETS}
bt_executor_parameters
)
######################################################
# INSTALL
install(DIRECTORY include/ DESTINATION include/)
ament_export_targets(${PROJECT_NAME}Targets HAS_LIBRARY_TARGET)
ament_export_dependencies(${THIS_PACKAGE_DEPS})
install(
TARGETS ${PROJECT_NAME} bt_executor_parameters
EXPORT ${PROJECT_NAME}Targets
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION lib/${PROJECT_NAME})
ament_export_include_directories(include)
ament_export_libraries(${PROJECT_NAME})
ament_package()
@@ -0,0 +1,74 @@
# Bt Server Parameters
Default Config
```yaml
bt_server:
ros__parameters:
action_name: bt_execution
behavior_trees: []
groot2_port: 1667
plugins: []
ros_plugins_timeout: 1000
tick_frequency: 100
```
## action_name
The name the Action Server takes requests from
* Type: `string`
* Default Value: "bt_execution"
* Read only: True
## tick_frequency
Frequency in Hz to tick() the Behavior tree at
* Type: `int`
* Default Value: 100
* Read only: True
*Constraints:*
- parameter must be within bounds 1
## groot2_port
Server port value to publish Groot2 messages on
* Type: `int`
* Default Value: 1667
* Read only: True
*Constraints:*
- parameter must be within bounds 1
## plugins
List of 'package_name/subfolder' containing BehaviorTree plugins to load into the factory
* Type: `string_array`
* Default Value: {}
*Constraints:*
- contains no duplicates
## ros_plugins_timeout
Timeout (ms) used in BT::RosNodeParams
* Type: `int`
* Default Value: 1000
*Constraints:*
- parameter must be within bounds 1
## behavior_trees
List of 'package_name/subfolder' containing SubTrees to load into the BehaviorTree factory
* Type: `string_array`
* Default Value: {}
*Constraints:*
- contains no duplicates
@@ -0,0 +1,579 @@
// Copyright (c) 2018 Intel Corporation
// Copyright (c) 2023 Davide Faconti
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <string>
#include <optional>
#include <rclcpp/executors.hpp>
#include <rclcpp/allocator/allocator_common.hpp>
#include "behaviortree_cpp/action_node.h"
#include "behaviortree_cpp/bt_factory.h"
#include "rclcpp_action/rclcpp_action.hpp"
#include "behaviortree_ros2/ros_node_params.hpp"
namespace BT
{
enum ActionNodeErrorCode
{
SERVER_UNREACHABLE,
SEND_GOAL_TIMEOUT,
GOAL_REJECTED_BY_SERVER,
ACTION_ABORTED,
ACTION_CANCELLED,
INVALID_GOAL
};
inline const char* toStr(const ActionNodeErrorCode& err)
{
switch(err)
{
case SERVER_UNREACHABLE:
return "SERVER_UNREACHABLE";
case SEND_GOAL_TIMEOUT:
return "SEND_GOAL_TIMEOUT";
case GOAL_REJECTED_BY_SERVER:
return "GOAL_REJECTED_BY_SERVER";
case ACTION_ABORTED:
return "ACTION_ABORTED";
case ACTION_CANCELLED:
return "ACTION_CANCELLED";
case INVALID_GOAL:
return "INVALID_GOAL";
}
return nullptr;
}
/**
* @brief Abstract class to wrap rclcpp_action::Client<>
*
* For instance, given the type AddTwoInts described in this tutorial:
* https://docs.ros.org/en/humble/Tutorials/Intermediate/Writing-an-Action-Server-Client/Cpp.html
*
* the corresponding wrapper would be:
*
* class FibonacciNode: public RosActionNode<action_tutorials_interfaces::action::Fibonacci>
*
* RosActionNode will try to be non-blocking for the entire duration of the call.
* The derived class must reimplement the virtual methods as described below.
*
* The name of the action will be determined as follows:
*
* 1. If a value is passes in the InputPort "action_name", use that
* 2. Otherwise, use the value in RosNodeParams::default_port_value
*/
template <class ActionT>
class RosActionNode : public BT::ActionNodeBase
{
public:
// Type definitions
using ActionType = ActionT;
using ActionClient = typename rclcpp_action::Client<ActionT>;
using ActionClientPtr = std::shared_ptr<ActionClient>;
using Goal = typename ActionT::Goal;
using GoalHandle = typename rclcpp_action::ClientGoalHandle<ActionT>;
using WrappedResult = typename rclcpp_action::ClientGoalHandle<ActionT>::WrappedResult;
using Feedback = typename ActionT::Feedback;
/** To register this class into the factory, use:
*
* factory.registerNodeType<>(node_name, params);
*
*/
explicit RosActionNode(const std::string& instance_name, const BT::NodeConfig& conf,
const RosNodeParams& params);
virtual ~RosActionNode() = default;
/**
* @brief Any subclass of RosActionNode that has ports must implement a
* providedPorts method and call providedBasicPorts in it.
*
* The basic ports:
*
* - `action_name` Action server name
*
* @param addition Additional ports to add to BT port list
* @return PortsList containing basic ports along with node-specific ports
*/
static PortsList providedBasicPorts(PortsList addition)
{
PortsList basic = { InputPort<std::string>("action_name", "", "Action server name") };
basic.insert(addition.begin(), addition.end());
return basic;
}
/**
* @brief Creates list of BT ports
* @return PortsList Containing basic ports along with node-specific ports
*/
static PortsList providedPorts()
{
return providedBasicPorts({});
}
/// @brief Callback executed when the node is halted. Note that cancelGoal()
/// is done automatically.
virtual void onHalt()
{}
/** setGoal s a callback that allows the user to set
* the goal message (ActionT::Goal).
*
* @param goal the goal to be sent to the action server.
*
* @return false if the request should not be sent. In that case,
* RosActionNode::onFailure(INVALID_GOAL) will be called.
*/
virtual bool setGoal(Goal& goal) = 0;
/** Callback invoked when the result is received by the server.
* It is up to the user to define if the action returns SUCCESS or FAILURE.
*/
virtual BT::NodeStatus onResultReceived(const WrappedResult& result) = 0;
/** Callback invoked when the feedback is received.
* It generally returns RUNNING, but the user can also use this callback to cancel the
* current action and return SUCCESS or FAILURE.
*/
virtual BT::NodeStatus onFeedback(const std::shared_ptr<const Feedback> /*feedback*/)
{
return NodeStatus::RUNNING;
}
/** Callback invoked when something goes wrong.
* The result is provided if it is available.
* It must return either SUCCESS or FAILURE.
*/
virtual BT::NodeStatus onFailure(ActionNodeErrorCode error,
const std::optional<WrappedResult>&)
{
return onFailure(error);
}
virtual BT::NodeStatus onFailure(ActionNodeErrorCode /*error*/)
{
return NodeStatus::FAILURE;
}
/// Method used to send a request to the Action server to cancel the current goal
void cancelGoal();
/// The default halt() implementation will call cancelGoal if necessary.
void halt() override;
NodeStatus tick() override;
/// Can be used to change the name of the action programmatically
void setActionName(const std::string& action_name);
protected:
struct ActionClientInstance
{
ActionClientInstance(std::shared_ptr<rclcpp::Node> node,
const std::string& action_name);
ActionClientPtr action_client;
rclcpp::CallbackGroup::SharedPtr callback_group;
rclcpp::executors::SingleThreadedExecutor callback_executor;
typename ActionClient::SendGoalOptions goal_options;
};
static std::mutex& getMutex()
{
static std::mutex action_client_mutex;
return action_client_mutex;
}
rclcpp::Logger logger()
{
if(auto node = node_.lock())
{
return node->get_logger();
}
return rclcpp::get_logger("RosActionNode");
}
rclcpp::Time now()
{
if(auto node = node_.lock())
{
return node->now();
}
return rclcpp::Clock(RCL_ROS_TIME).now();
}
using ClientsRegistry =
std::unordered_map<std::string, std::weak_ptr<ActionClientInstance>>;
// contains the fully-qualified name of the node and the name of the client
static ClientsRegistry& getRegistry()
{
static ClientsRegistry action_clients_registry;
return action_clients_registry;
}
std::weak_ptr<rclcpp::Node> node_;
std::shared_ptr<ActionClientInstance> client_instance_;
std::string action_name_;
bool action_name_should_be_checked_ = false;
const std::chrono::milliseconds server_timeout_;
const std::chrono::milliseconds wait_for_server_timeout_;
std::string action_client_key_;
private:
std::shared_future<typename GoalHandle::SharedPtr> future_goal_handle_;
typename GoalHandle::SharedPtr goal_handle_;
rclcpp::Time time_goal_sent_;
NodeStatus on_feedback_state_change_;
bool goal_received_;
WrappedResult result_;
bool createClient(const std::string& action_name);
};
//----------------------------------------------------------------
//---------------------- DEFINITIONS -----------------------------
//----------------------------------------------------------------
template <class T>
RosActionNode<T>::ActionClientInstance::ActionClientInstance(
std::shared_ptr<rclcpp::Node> node, const std::string& action_name)
{
callback_group =
node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive, false);
callback_executor.add_callback_group(callback_group, node->get_node_base_interface());
action_client = rclcpp_action::create_client<T>(node, action_name, callback_group);
}
template <class T>
inline RosActionNode<T>::RosActionNode(const std::string& instance_name,
const NodeConfig& conf,
const RosNodeParams& params)
: BT::ActionNodeBase(instance_name, conf)
, node_(params.nh)
, server_timeout_(params.server_timeout)
, wait_for_server_timeout_(params.wait_for_server_timeout)
{
// Three cases:
// - we use the default action_name in RosNodeParams when port is empty
// - we use the action_name in the port and it is a static string.
// - we use the action_name in the port and it is blackboard entry.
// check port remapping
auto portIt = config().input_ports.find("action_name");
if(portIt != config().input_ports.end())
{
const std::string& bb_service_name = portIt->second;
if(isBlackboardPointer(bb_service_name))
{
// unknown value at construction time. Postpone to tick
action_name_should_be_checked_ = true;
}
else if(!bb_service_name.empty())
{
// "hard-coded" name in the bb_service_name. Use it.
createClient(bb_service_name);
}
}
// no port value or it is empty. Use the default value
if(!client_instance_ && !params.default_port_value.empty())
{
createClient(params.default_port_value);
}
}
template <class T>
inline bool RosActionNode<T>::createClient(const std::string& action_name)
{
if(action_name.empty())
{
throw RuntimeError("action_name is empty");
}
std::unique_lock lk(getMutex());
auto node = node_.lock();
if(!node)
{
throw RuntimeError("The ROS node went out of scope. RosNodeParams doesn't take the "
"ownership of the node.");
}
action_client_key_ = std::string(node->get_fully_qualified_name()) + "/" + action_name;
auto& registry = getRegistry();
auto it = registry.find(action_client_key_);
if(it == registry.end() || it->second.expired())
{
client_instance_ = std::make_shared<ActionClientInstance>(node, action_name);
registry.insert_or_assign(action_client_key_, client_instance_);
}
else
{
client_instance_ = it->second.lock();
}
action_name_ = action_name;
bool found =
client_instance_->action_client->wait_for_action_server(wait_for_server_timeout_);
if(!found)
{
RCLCPP_ERROR(logger(), "%s: Action server with name '%s' is not reachable.",
name().c_str(), action_name_.c_str());
}
return found;
}
template <class T>
inline void RosActionNode<T>::setActionName(const std::string& action_name)
{
action_name_ = action_name;
createClient(action_name);
}
template <class T>
inline NodeStatus RosActionNode<T>::tick()
{
if(!rclcpp::ok())
{
halt();
return NodeStatus::FAILURE;
}
// First, check if the action_client_ is valid and that the name of the
// action_name in the port didn't change.
// otherwise, create a new client
if(!client_instance_ ||
(status() == NodeStatus::IDLE && action_name_should_be_checked_))
{
std::string action_name;
getInput("action_name", action_name);
if(action_name_ != action_name)
{
createClient(action_name);
}
}
if(!client_instance_)
{
throw BT::RuntimeError("RosActionNode: no client was specified, neither as default "
"nor in the ports");
}
auto& action_client = client_instance_->action_client;
//------------------------------------------
auto CheckStatus = [](NodeStatus status) {
if(!isStatusCompleted(status))
{
throw LogicError("RosActionNode: the callback must return either SUCCESS nor "
"FAILURE");
}
return status;
};
// first step to be done only at the beginning of the Action
if(status() == BT::NodeStatus::IDLE)
{
setStatus(NodeStatus::RUNNING);
goal_received_ = false;
future_goal_handle_ = {};
on_feedback_state_change_ = NodeStatus::RUNNING;
result_ = {};
Goal goal;
if(!setGoal(goal))
{
return CheckStatus(onFailure(INVALID_GOAL, {}));
}
typename ActionClient::SendGoalOptions goal_options;
//--------------------
goal_options.feedback_callback =
[this](typename GoalHandle::SharedPtr,
const std::shared_ptr<const Feedback> feedback) {
on_feedback_state_change_ = onFeedback(feedback);
if(on_feedback_state_change_ == NodeStatus::IDLE)
{
throw std::logic_error("onFeedback must not return IDLE");
}
emitWakeUpSignal();
};
//--------------------
goal_options.result_callback = [this](const WrappedResult& result) {
if(goal_handle_->get_goal_id() == result.goal_id)
{
RCLCPP_DEBUG(logger(), "result_callback");
result_ = result;
emitWakeUpSignal();
}
};
//--------------------
goal_options.goal_response_callback =
[this](typename GoalHandle::SharedPtr const future_handle) {
auto goal_handle_ = future_handle.get();
if(!goal_handle_)
{
RCLCPP_ERROR(logger(), "Goal was rejected by server");
}
else
{
RCLCPP_DEBUG(logger(), "Goal accepted by server, waiting for result");
}
};
//--------------------
// Check if server is ready
if(!action_client->action_server_is_ready())
{
return onFailure(SERVER_UNREACHABLE, {});
}
future_goal_handle_ = action_client->async_send_goal(goal, goal_options);
time_goal_sent_ = now();
return NodeStatus::RUNNING;
}
if(status() == NodeStatus::RUNNING)
{
std::unique_lock<std::mutex> lock(getMutex());
client_instance_->callback_executor.spin_some();
// FIRST case: check if the goal request has a timeout
if(!goal_received_)
{
auto nodelay = std::chrono::milliseconds(0);
auto timeout =
rclcpp::Duration::from_seconds(double(server_timeout_.count()) / 1000);
auto ret = client_instance_->callback_executor.spin_until_future_complete(
future_goal_handle_, nodelay);
if(ret != rclcpp::FutureReturnCode::SUCCESS)
{
if((now() - time_goal_sent_) > timeout)
{
return CheckStatus(onFailure(SEND_GOAL_TIMEOUT, {}));
}
else
{
return NodeStatus::RUNNING;
}
}
else
{
goal_received_ = true;
goal_handle_ = future_goal_handle_.get();
future_goal_handle_ = {};
if(!goal_handle_)
{
return CheckStatus(onFailure(GOAL_REJECTED_BY_SERVER));
}
}
}
// SECOND case: onFeedback requested a stop
if(on_feedback_state_change_ != NodeStatus::RUNNING)
{
cancelGoal();
return on_feedback_state_change_;
}
// THIRD case: result received, requested a stop
if(result_.code != rclcpp_action::ResultCode::UNKNOWN)
{
if(result_.code == rclcpp_action::ResultCode::ABORTED)
{
return CheckStatus(onFailure(ACTION_ABORTED, result_));
}
else if(result_.code == rclcpp_action::ResultCode::CANCELED)
{
return CheckStatus(onFailure(ACTION_CANCELLED, result_));
}
else
{
return CheckStatus(onResultReceived(result_));
}
}
}
return NodeStatus::RUNNING;
}
template <class T>
inline void RosActionNode<T>::halt()
{
if(status() == BT::NodeStatus::RUNNING)
{
cancelGoal();
onHalt();
}
}
template <class T>
inline void RosActionNode<T>::cancelGoal()
{
auto& executor = client_instance_->callback_executor;
if(!goal_handle_)
{
if(future_goal_handle_.valid())
{
// Here the discussion is if we should block or put a timer for the waiting
auto ret =
executor.spin_until_future_complete(future_goal_handle_, server_timeout_);
if(ret != rclcpp::FutureReturnCode::SUCCESS)
{
// In that case the goal was not accepted or timed out so probably we should do nothing.
return;
}
else
{
goal_handle_ = future_goal_handle_.get();
future_goal_handle_ = {};
}
}
else
{
RCLCPP_WARN(logger(), "cancelGoal called on an empty goal_handle");
return;
}
}
auto& action_client = client_instance_->action_client;
auto future_result = action_client->async_get_result(goal_handle_);
auto future_cancel = action_client->async_cancel_goal(goal_handle_);
constexpr auto SUCCESS = rclcpp::FutureReturnCode::SUCCESS;
if(executor.spin_until_future_complete(future_cancel, server_timeout_) != SUCCESS)
{
RCLCPP_ERROR(logger(), "Failed to cancel action server for [%s]",
action_name_.c_str());
}
if(executor.spin_until_future_complete(future_result, server_timeout_) != SUCCESS)
{
RCLCPP_ERROR(logger(), "Failed to get result call failed :( for [%s]",
action_name_.c_str());
}
}
} // namespace BT
@@ -0,0 +1,32 @@
#ifndef BT_ROS_LOGGER_H
#define BT_ROS_LOGGER_H
#include <cstring>
#include <rclcpp/executors.hpp>
#include <rclcpp/allocator/allocator_common.hpp>
#include <rclcpp/logging.hpp>
#include "behaviortree_cpp/loggers/abstract_logger.h"
namespace BT
{
/**
* @brief RosLogger is a very simple logger that
* displays all the transitions on the console.
*/
class RosLogger : public StatusChangeLogger
{
public:
RosLogger(const BT::Tree& tree, std::shared_ptr<rclcpp::Node> node);
~RosLogger() override;
virtual void flush() override;
private:
virtual void callback(Duration timestamp, const TreeNode& node, NodeStatus prev_status,
NodeStatus status) override;
std::weak_ptr<rclcpp::Node> node_;
};
} // namespace BT
#endif // BT_ROS_LOGGER_H
@@ -0,0 +1,432 @@
// Copyright (c) 2019 Intel Corporation
// Copyright (c) 2023 Davide Faconti
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <string>
#include <rclcpp/executors.hpp>
#include <rclcpp/allocator/allocator_common.hpp>
#include <rclcpp/version.h>
#include <rclcpp/qos.hpp>
#include "behaviortree_cpp/bt_factory.h"
#include "behaviortree_ros2/ros_node_params.hpp"
namespace BT
{
enum ServiceNodeErrorCode
{
SERVICE_UNREACHABLE,
SERVICE_TIMEOUT,
INVALID_REQUEST,
SERVICE_ABORTED
};
inline const char* toStr(const ServiceNodeErrorCode& err)
{
switch(err)
{
case SERVICE_UNREACHABLE:
return "SERVICE_UNREACHABLE";
case SERVICE_TIMEOUT:
return "SERVICE_TIMEOUT";
case INVALID_REQUEST:
return "INVALID_REQUEST";
case SERVICE_ABORTED:
return "SERVICE_ABORTED";
}
return nullptr;
}
/**
* @brief Abstract class use to wrap rclcpp::Client<>
*
* For instance, given the type AddTwoInts described in this tutorial:
* https://docs.ros.org/en/humble/Tutorials/Beginner-Client-Libraries/Writing-A-Simple-Cpp-Service-And-Client.html
*
* the corresponding wrapper would be:
*
* class AddTwoNumbers: public RosServiceNode<example_interfaces::srv::AddTwoInts>
*
* RosServiceNode will try to be non-blocking for the entire duration of the call.
* The derived class must reimplement the virtual methods as described below.
*
* The name of the service will be determined as follows:
*
* 1. If a value is passes in the InputPort "service_name", use that
* 2. Otherwise, use the value in RosNodeParams::default_port_value
*/
template <class ServiceT>
class RosServiceNode : public BT::ActionNodeBase
{
public:
// Type definitions
using ServiceClient = typename rclcpp::Client<ServiceT>;
using ServiceClientPtr = std::shared_ptr<ServiceClient>;
using Request = typename ServiceT::Request;
using Response = typename ServiceT::Response;
/** To register this class into the factory, use:
*
* factory.registerNodeType<>(node_name, params);
*/
explicit RosServiceNode(const std::string& instance_name, const BT::NodeConfig& conf,
const BT::RosNodeParams& params);
virtual ~RosServiceNode() = default;
/**
* @brief Any subclass of RosServiceNode that has ports must implement a
* providedPorts method and call providedBasicPorts in it.
*
* @param addition Additional ports to add to BT port list
* @return PortsList containing basic ports along with node-specific ports
*/
static PortsList providedBasicPorts(PortsList addition)
{
PortsList basic = { InputPort<std::string>("service_name", "", "Service name") };
basic.insert(addition.begin(), addition.end());
return basic;
}
/**
* @brief Creates list of BT ports
* @return PortsList Containing basic ports along with node-specific ports
*/
static PortsList providedPorts()
{
return providedBasicPorts({});
}
NodeStatus tick() override;
/// The default halt() implementation.
void halt() override;
/** setRequest is a callback that allows the user to set
* the request message (ServiceT::Request).
*
* @param request the request to be sent to the service provider.
*
* @return false if the request should not be sent. In that case,
* RosServiceNode::onFailure(INVALID_REQUEST) will be called.
*/
virtual bool setRequest(typename Request::SharedPtr& request) = 0;
/** Callback invoked when the response is received by the server.
* It is up to the user to define if this returns SUCCESS or FAILURE.
*/
virtual BT::NodeStatus
onResponseReceived(const typename Response::SharedPtr& response) = 0;
/** Callback invoked when something goes wrong; you can override it.
* It must return either SUCCESS or FAILURE.
*/
virtual BT::NodeStatus onFailure(ServiceNodeErrorCode /*error*/)
{
return NodeStatus::FAILURE;
}
protected:
struct ServiceClientInstance
{
ServiceClientInstance(std::shared_ptr<rclcpp::Node> node,
const std::string& service_name);
ServiceClientPtr service_client;
rclcpp::CallbackGroup::SharedPtr callback_group;
rclcpp::executors::SingleThreadedExecutor callback_executor;
};
static std::mutex& getMutex()
{
static std::mutex action_client_mutex;
return action_client_mutex;
}
// method to set the service name programmatically
void setServiceName(const std::string& service_name);
rclcpp::Logger logger()
{
if(auto node = node_.lock())
{
return node->get_logger();
}
return rclcpp::get_logger("RosServiceNode");
}
rclcpp::Time now()
{
if(auto node = node_.lock())
{
return node->now();
}
return rclcpp::Clock(RCL_ROS_TIME).now();
}
using ClientsRegistry =
std::unordered_map<std::string, std::weak_ptr<ServiceClientInstance>>;
// contains the fully-qualified name of the node and the name of the client
static ClientsRegistry& getRegistry()
{
static ClientsRegistry clients_registry;
return clients_registry;
}
std::weak_ptr<rclcpp::Node> node_;
std::string service_name_;
bool service_name_should_be_checked_ = false;
const std::chrono::milliseconds service_timeout_;
const std::chrono::milliseconds wait_for_service_timeout_;
private:
std::shared_ptr<ServiceClientInstance> srv_instance_;
std::shared_future<typename Response::SharedPtr> future_response_;
rclcpp::Time time_request_sent_;
NodeStatus on_feedback_state_change_;
bool response_received_;
typename Response::SharedPtr response_;
bool createClient(const std::string& service_name);
};
//----------------------------------------------------------------
//---------------------- DEFINITIONS -----------------------------
//----------------------------------------------------------------
template <class T>
inline RosServiceNode<T>::ServiceClientInstance::ServiceClientInstance(
std::shared_ptr<rclcpp::Node> node, const std::string& service_name)
{
callback_group =
node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive, false);
callback_executor.add_callback_group(callback_group, node->get_node_base_interface());
// For Jazzy and Later Support
#if RCLCPP_VERSION_GTE(28, 0, 0)
service_client =
node->create_client<T>(service_name, rclcpp::ServicesQoS(), callback_group);
#else
service_client = node->create_client<T>(service_name, rmw_qos_profile_services_default,
callback_group);
#endif
}
template <class T>
inline RosServiceNode<T>::RosServiceNode(const std::string& instance_name,
const NodeConfig& conf,
const RosNodeParams& params)
: BT::ActionNodeBase(instance_name, conf)
, node_(params.nh)
, service_timeout_(params.server_timeout)
, wait_for_service_timeout_(params.wait_for_server_timeout)
{
// check port remapping
auto portIt = config().input_ports.find("service_name");
if(portIt != config().input_ports.end())
{
const std::string& bb_service_name = portIt->second;
if(isBlackboardPointer(bb_service_name))
{
// unknown value at construction time. postpone to tick
service_name_should_be_checked_ = true;
}
else if(!bb_service_name.empty())
{
// "hard-coded" name in the bb_service_name. Use it.
createClient(bb_service_name);
}
}
// no port value or it is empty. Use the default port value
if(!srv_instance_ && !params.default_port_value.empty())
{
createClient(params.default_port_value);
}
}
template <class T>
inline bool RosServiceNode<T>::createClient(const std::string& service_name)
{
if(service_name.empty() || service_name == "__default__placeholder__")
{
throw RuntimeError("service_name is empty or invalid");
}
std::unique_lock lk(getMutex());
auto node = node_.lock();
if(!node)
{
throw RuntimeError("The ROS node went out of scope. RosNodeParams doesn't take the "
"ownership of the node.");
}
auto client_key = std::string(node->get_fully_qualified_name()) + "/" + service_name;
auto& registry = getRegistry();
auto it = registry.find(client_key);
if(it == registry.end() || it->second.expired())
{
srv_instance_ = std::make_shared<ServiceClientInstance>(node, service_name);
registry.insert_or_assign(client_key, srv_instance_);
RCLCPP_INFO(logger(), "Node [%s] created service client [%s]", name().c_str(),
service_name.c_str());
}
else
{
srv_instance_ = it->second.lock();
}
service_name_ = service_name;
bool found = srv_instance_->service_client->wait_for_service(wait_for_service_timeout_);
if(!found)
{
RCLCPP_ERROR(logger(), "%s: Service with name '%s' is not reachable.", name().c_str(),
service_name_.c_str());
}
return found;
}
template <class T>
inline void RosServiceNode<T>::setServiceName(const std::string& service_name)
{
service_name_ = service_name;
createClient(service_name);
}
template <class T>
inline NodeStatus RosServiceNode<T>::tick()
{
if(!rclcpp::ok())
{
halt();
return NodeStatus::FAILURE;
}
// First, check if the service_client is valid and that the name of the
// service_name in the port didn't change.
// otherwise, create a new client
if(!srv_instance_ || (status() == NodeStatus::IDLE && service_name_should_be_checked_))
{
std::string service_name;
getInput("service_name", service_name);
if(service_name_ != service_name)
{
createClient(service_name);
}
}
if(!srv_instance_)
{
throw BT::RuntimeError("RosServiceNode: no service client was specified neither as "
"default or in the ports");
}
auto CheckStatus = [](NodeStatus status) {
if(!isStatusCompleted(status))
{
throw LogicError("RosServiceNode: the callback must return either SUCCESS nor "
"FAILURE");
}
return status;
};
// first step to be done only at the beginning of the Action
if(status() == BT::NodeStatus::IDLE)
{
setStatus(NodeStatus::RUNNING);
response_received_ = false;
future_response_ = {};
on_feedback_state_change_ = NodeStatus::RUNNING;
response_ = {};
typename Request::SharedPtr request = std::make_shared<Request>();
if(!setRequest(request))
{
return CheckStatus(onFailure(INVALID_REQUEST));
}
// Check if server is ready
if(!srv_instance_->service_client->service_is_ready())
{
return onFailure(SERVICE_UNREACHABLE);
}
future_response_ = srv_instance_->service_client->async_send_request(request).share();
time_request_sent_ = now();
return NodeStatus::RUNNING;
}
if(status() == NodeStatus::RUNNING)
{
srv_instance_->callback_executor.spin_some();
// FIRST case: check if the goal request has a timeout
if(!response_received_)
{
auto const nodelay = std::chrono::milliseconds(0);
auto const timeout =
rclcpp::Duration::from_seconds(double(service_timeout_.count()) / 1000);
auto ret = srv_instance_->callback_executor.spin_until_future_complete(
future_response_, nodelay);
if(ret != rclcpp::FutureReturnCode::SUCCESS)
{
if((now() - time_request_sent_) > timeout)
{
return CheckStatus(onFailure(SERVICE_TIMEOUT));
}
else
{
return NodeStatus::RUNNING;
}
}
else
{
response_received_ = true;
response_ = future_response_.get();
future_response_ = {};
if(!response_)
{
throw RuntimeError("Request was rejected by the service");
}
}
}
// SECOND case: response received
return CheckStatus(onResponseReceived(response_));
}
return NodeStatus::RUNNING;
}
template <class T>
inline void RosServiceNode<T>::halt()
{
if(status() == NodeStatus::RUNNING)
{
resetStatus();
}
}
} // namespace BT
@@ -0,0 +1,191 @@
// Copyright (c) 2023 Davide Faconti, Unmanned Life
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <string>
#include <rclcpp/executors.hpp>
#include <rclcpp/allocator/allocator_common.hpp>
#include "behaviortree_cpp/condition_node.h"
#include "behaviortree_cpp/bt_factory.h"
#include "behaviortree_ros2/ros_node_params.hpp"
namespace BT
{
/**
* @brief Abstract class to wrap a ROS publisher
*
*/
template <class TopicT>
class RosTopicPubNode : public BT::ConditionNode
{
public:
// Type definitions
using Publisher = typename rclcpp::Publisher<TopicT>;
/** You are not supposed to instantiate this class directly, the factory will do it.
* To register this class into the factory, use:
*
* RegisterRosAction<DerivedClass>(factory, params)
*
* Note that if the external_action_client is not set, the constructor will build its own.
* */
explicit RosTopicPubNode(const std::string& instance_name, const BT::NodeConfig& conf,
const RosNodeParams& params);
virtual ~RosTopicPubNode() = default;
/**
* @brief Any subclass of RosTopicPubNode that has additinal ports must provide a
* providedPorts method and call providedBasicPorts in it.
*
* @param addition Additional ports to add to BT port list
* @return PortsList Containing basic ports along with node-specific ports
*/
static PortsList providedBasicPorts(PortsList addition)
{
PortsList basic = { InputPort<std::string>("topic_name", "__default__placeholder__",
"Topic name") };
basic.insert(addition.begin(), addition.end());
return basic;
}
/**
* @brief Creates list of BT ports
* @return PortsList Containing basic ports along with node-specific ports
*/
static PortsList providedPorts()
{
return providedBasicPorts({});
}
NodeStatus tick() override final;
/**
* @brief setMessage is a callback invoked in tick to allow the user to pass
* the message to be published.
*
* @param msg the message.
* @return return false if anything is wrong and we must not send the message.
* the Condition will return FAILURE.
*/
virtual bool setMessage(TopicT& msg) = 0;
protected:
std::shared_ptr<rclcpp::Node> node_;
std::string prev_topic_name_;
bool topic_name_may_change_ = false;
private:
std::shared_ptr<Publisher> publisher_;
bool createPublisher(const std::string& topic_name);
};
//----------------------------------------------------------------
//---------------------- DEFINITIONS -----------------------------
//----------------------------------------------------------------
template <class T>
inline RosTopicPubNode<T>::RosTopicPubNode(const std::string& instance_name,
const NodeConfig& conf,
const RosNodeParams& params)
: BT::ConditionNode(instance_name, conf), node_(params.nh)
{
// check port remapping
auto portIt = config().input_ports.find("topic_name");
if(portIt != config().input_ports.end())
{
const std::string& bb_topic_name = portIt->second;
if(bb_topic_name.empty() || bb_topic_name == "__default__placeholder__")
{
if(params.default_port_value.empty())
{
throw std::logic_error("Both [topic_name] in the InputPort and the RosNodeParams "
"are empty.");
}
else
{
createPublisher(params.default_port_value);
}
}
else if(!isBlackboardPointer(bb_topic_name))
{
// If the content of the port "topic_name" is not
// a pointer to the blackboard, but a static string, we can
// create the client in the constructor.
createPublisher(bb_topic_name);
}
else
{
topic_name_may_change_ = true;
// createPublisher will be invoked in the first tick().
}
}
else
{
if(params.default_port_value.empty())
{
throw std::logic_error("Both [topic_name] in the InputPort and the RosNodeParams "
"are empty.");
}
else
{
createPublisher(params.default_port_value);
}
}
}
template <class T>
inline bool RosTopicPubNode<T>::createPublisher(const std::string& topic_name)
{
if(topic_name.empty())
{
throw RuntimeError("topic_name is empty");
}
publisher_ = node_->create_publisher<T>(topic_name, 1);
prev_topic_name_ = topic_name;
return true;
}
template <class T>
inline NodeStatus RosTopicPubNode<T>::tick()
{
// First, check if the subscriber_ is valid and that the name of the
// topic_name in the port didn't change.
// otherwise, create a new subscriber
if(!publisher_ || (status() == NodeStatus::IDLE && topic_name_may_change_))
{
std::string topic_name;
getInput("topic_name", topic_name);
if(prev_topic_name_ != topic_name)
{
createPublisher(topic_name);
}
}
T msg;
if(!setMessage(msg))
{
return NodeStatus::FAILURE;
}
publisher_->publish(msg);
return NodeStatus::SUCCESS;
}
} // namespace BT
@@ -0,0 +1,326 @@
// Copyright (c) 2023 Davide Faconti, Unmanned Life
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <string>
#include <rclcpp/executors.hpp>
#include <rclcpp/allocator/allocator_common.hpp>
#include "behaviortree_cpp/condition_node.h"
#include "behaviortree_cpp/bt_factory.h"
#include "behaviortree_ros2/ros_node_params.hpp"
#include <boost/signals2.hpp>
namespace BT
{
/**
* @brief Abstract class to wrap a Topic subscriber.
* Considering the example in the tutorial:
* https://docs.ros.org/en/humble/Tutorials/Beginner-Client-Libraries/Writing-A-Simple-Cpp-Publisher-And-Subscriber.html
*
* The corresponding wrapper would be:
*
* class SubscriberNode: RosTopicSubNode<std_msgs::msg::String>
*
* The name of the topic will be determined as follows:
*
* 1. If a value is passes in the InputPort "topic_name", use that
* 2. Otherwise, use the value in RosNodeParams::default_port_value
*/
template <class TopicT>
class RosTopicSubNode : public BT::ConditionNode
{
public:
// Type definitions
using Subscriber = typename rclcpp::Subscription<TopicT>;
protected:
struct SubscriberInstance
{
SubscriberInstance(std::shared_ptr<rclcpp::Node> node, const std::string& topic_name);
std::shared_ptr<Subscriber> subscriber;
rclcpp::CallbackGroup::SharedPtr callback_group;
rclcpp::executors::SingleThreadedExecutor callback_group_executor;
boost::signals2::signal<void(const std::shared_ptr<TopicT>)> broadcaster;
std::shared_ptr<TopicT> last_msg;
};
static std::mutex& registryMutex()
{
static std::mutex sub_mutex;
return sub_mutex;
}
using SubscribersRegistry =
std::unordered_map<std::string, std::weak_ptr<SubscriberInstance>>;
// contains the fully-qualified name of the node and the name of the topic
static SubscribersRegistry& getRegistry()
{
static SubscribersRegistry subscribers_registry;
return subscribers_registry;
}
std::weak_ptr<rclcpp::Node> node_;
std::shared_ptr<SubscriberInstance> sub_instance_;
std::shared_ptr<TopicT> last_msg_;
std::string topic_name_;
boost::signals2::connection signal_connection_;
std::string subscriber_key_;
rclcpp::Logger logger()
{
if(auto node = node_.lock())
{
return node->get_logger();
}
return rclcpp::get_logger("RosTopicSubNode");
}
public:
/** You are not supposed to instantiate this class directly, the factory will do it.
* To register this class into the factory, use:
*
* RegisterRosAction<DerivedClass>(factory, params)
*
* Note that if the external_action_client is not set, the constructor will build its own.
* */
explicit RosTopicSubNode(const std::string& instance_name, const BT::NodeConfig& conf,
const RosNodeParams& params);
virtual ~RosTopicSubNode()
{
signal_connection_.disconnect();
}
/**
* @brief Any subclass of RosTopicNode that accepts parameters must provide a
* providedPorts method and call providedBasicPorts in it.
* @param addition Additional ports to add to BT port list
* @return PortsList Containing basic ports along with node-specific ports
*/
static PortsList providedBasicPorts(PortsList addition)
{
PortsList basic = { InputPort<std::string>("topic_name", "__default__placeholder__",
"Topic name") };
basic.insert(addition.begin(), addition.end());
return basic;
}
/**
* @brief Creates list of BT ports
* @return PortsList Containing basic ports along with node-specific ports
*/
static PortsList providedPorts()
{
return providedBasicPorts({});
}
NodeStatus tick() override final;
/** Callback invoked in the tick. You must return either SUCCESS of FAILURE
*
* @param last_msg the latest message received, since the last tick.
* Will be empty if no new message received.
*
* @return the new status of the Node, based on last_msg
*/
virtual NodeStatus onTick(const std::shared_ptr<TopicT>& last_msg) = 0;
/** latch the message that has been processed. If returns false and no new message is
* received, before next call there will be no message to process. If returns true,
* the next call will process the same message again, if no new message received.
*
* This can be equated with latched vs non-latched topics in ros 1.
*
* @return false will clear the message after ticking/processing.
*/
virtual bool latchLastMessage() const
{
return false;
}
private:
bool createSubscriber(const std::string& topic_name);
};
//----------------------------------------------------------------
//---------------------- DEFINITIONS -----------------------------
//----------------------------------------------------------------
template <class T>
inline RosTopicSubNode<T>::SubscriberInstance::SubscriberInstance(
std::shared_ptr<rclcpp::Node> node, const std::string& topic_name)
{
// create a callback group for this particular instance
callback_group =
node->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive, false);
callback_group_executor.add_callback_group(callback_group,
node->get_node_base_interface());
rclcpp::SubscriptionOptions option;
option.callback_group = callback_group;
// The callback will broadcast to all the instances of RosTopicSubNode<T>
auto callback = [this](const std::shared_ptr<T> msg) {
last_msg = msg;
broadcaster(msg);
};
subscriber = node->create_subscription<T>(topic_name, 1, callback, option);
}
template <class T>
inline RosTopicSubNode<T>::RosTopicSubNode(const std::string& instance_name,
const NodeConfig& conf,
const RosNodeParams& params)
: BT::ConditionNode(instance_name, conf), node_(params.nh)
{
// check port remapping
auto portIt = config().input_ports.find("topic_name");
if(portIt != config().input_ports.end())
{
const std::string& bb_topic_name = portIt->second;
if(bb_topic_name.empty() || bb_topic_name == "__default__placeholder__")
{
if(params.default_port_value.empty())
{
throw std::logic_error("Both [topic_name] in the InputPort and the RosNodeParams "
"are empty.");
}
else
{
createSubscriber(params.default_port_value);
}
}
else if(!isBlackboardPointer(bb_topic_name))
{
// If the content of the port "topic_name" is not
// a pointer to the blackboard, but a static string, we can
// create the client in the constructor.
createSubscriber(bb_topic_name);
}
else
{
// do nothing
// createSubscriber will be invoked in the first tick().
}
}
else
{
if(params.default_port_value.empty())
{
throw std::logic_error("Both [topic_name] in the InputPort and the RosNodeParams "
"are empty.");
}
else
{
createSubscriber(params.default_port_value);
}
}
}
template <class T>
inline bool RosTopicSubNode<T>::createSubscriber(const std::string& topic_name)
{
if(topic_name.empty())
{
throw RuntimeError("topic_name is empty");
}
if(sub_instance_)
{
throw RuntimeError("Can't call createSubscriber more than once");
}
// find SubscriberInstance in the registry
std::unique_lock lk(registryMutex());
auto node = node_.lock();
if(!node)
{
throw RuntimeError("The ROS node went out of scope. RosNodeParams doesn't take the "
"ownership of the node.");
}
subscriber_key_ = std::string(node->get_fully_qualified_name()) + "/" + topic_name;
auto& registry = getRegistry();
auto it = registry.find(subscriber_key_);
if(it == registry.end() || it->second.expired())
{
sub_instance_ = std::make_shared<SubscriberInstance>(node, topic_name);
registry.insert_or_assign(subscriber_key_, sub_instance_);
RCLCPP_INFO(logger(), "Node [%s] created Subscriber to topic [%s]", name().c_str(),
topic_name.c_str());
}
else
{
sub_instance_ = it->second.lock();
}
// Check if there was a message received before the creation of this subscriber action
if(sub_instance_->last_msg)
{
last_msg_ = sub_instance_->last_msg;
}
// add "this" as received of the broadcaster
signal_connection_ = sub_instance_->broadcaster.connect(
[this](const std::shared_ptr<T> msg) { last_msg_ = msg; });
topic_name_ = topic_name;
return true;
}
template <class T>
inline NodeStatus RosTopicSubNode<T>::tick()
{
// First, check if the subscriber_ is valid and that the name of the
// topic_name in the port didn't change.
// otherwise, create a new subscriber
std::string topic_name;
getInput("topic_name", topic_name);
if(!topic_name.empty() && topic_name != "__default__placeholder__" &&
topic_name != topic_name_)
{
sub_instance_.reset();
}
if(!sub_instance_)
{
createSubscriber(topic_name);
}
auto CheckStatus = [](NodeStatus status) {
if(!isStatusCompleted(status))
{
throw std::logic_error("RosTopicSubNode: the callback must return"
"either SUCCESS or FAILURE");
}
return status;
};
sub_instance_->callback_group_executor.spin_some();
auto status = CheckStatus(onTick(last_msg_));
if(!latchLastMessage())
{
last_msg_.reset();
}
return status;
}
} // namespace BT
@@ -0,0 +1,89 @@
// Copyright 2024 Marq Rasmussen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#pragma once
#include <functional>
#include <memory>
#include <thread>
#include "btcpp_ros2_interfaces/msg/node_status.hpp"
#include "behaviortree_cpp/bt_factory.h"
// auto-generated header, created by generate_parameter_library
#include "behaviortree_ros2/bt_executor_parameters.hpp"
#include "behaviortree_ros2/plugins.hpp"
#include "behaviortree_ros2/ros_node_params.hpp"
#include "rclcpp/rclcpp.hpp"
#include <ament_index_cpp/get_package_share_directory.hpp>
namespace BT
{
/**
* @brief Convert BT::NodeStatus into Action Server feedback message NodeStatus
*
* @param status Current status of the executing BehaviorTree
* @return NodeStatus used to publish feedback to the Action Client
*/
btcpp_ros2_interfaces::msg::NodeStatus ConvertNodeStatus(BT::NodeStatus& status);
/**
* @brief Function the uses ament_index_cpp to get the package path of the parameter specified by the user
*
* @param parameter_value String containing 'package_name/subfolder' for the directory path to look up
* @return Full path to the directory specified by the parameter_value
*/
std::string GetDirectoryPath(const std::string& parameter_value);
/**
* @brief Function to load BehaviorTree xml files from a specific directory
*
* @param factory BehaviorTreeFactory to register the BehaviorTrees into
* @param directory_path Full path to the directory to search for BehaviorTree definitions
*/
void LoadBehaviorTrees(BT::BehaviorTreeFactory& factory,
const std::string& directory_path);
/**
* @brief Function to load a BehaviorTree ROS plugin (or standard BT.CPP plugins)
*
* @param factory BehaviorTreeFactory to register the plugin into
* @param file_path Full path to the directory to search for BehaviorTree plugin
* @param params parameters passed to the ROS plugin
*/
void LoadPlugin(BT::BehaviorTreeFactory& factory, const std::filesystem::path& file_path,
BT::RosNodeParams params);
/** @brief Function to load all plugins from the specified package
*
* @param params ROS parameters that contain the package name to load plugins from
* @param factory BehaviorTreeFactory to register the plugins into
* @param node node pointer that is shared with the ROS based Behavior plugins
*/
void RegisterPlugins(bt_server::Params& params, BT::BehaviorTreeFactory& factory,
rclcpp::Node::SharedPtr node);
/**
* @brief Function to register all Behaviors and BehaviorTrees from user specified packages
*
* @param params ROS parameters that contain lists of packages to load
* plugins, ros_plugins and BehaviorTrees from
* @param factory BehaviorTreeFactory to register into
* @param node node pointer that is shared with the ROS based Behavior plugins
*/
void RegisterBehaviorTrees(bt_server::Params& params, BT::BehaviorTreeFactory& factory,
rclcpp::Node::SharedPtr node);
} // namespace BT
@@ -0,0 +1,83 @@
// Copyright (c) 2023 Davide Faconti
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <filesystem>
#include "behaviortree_cpp/bt_factory.h"
#include "behaviortree_cpp/utils/shared_library.h"
#include "behaviortree_ros2/ros_node_params.hpp"
namespace BT
{
constexpr const char* ROS_PLUGIN_SYMBOL = "BT_RegisterRosNodeFromPlugin";
}
/* Use this macro to automatically register one or more custom Nodes
* into a factory that require access to the BT::RosNodeParams.
* For instance:
*
* BT_REGISTER_ROS_NODES(factory, params)
* {
* factory.registerNodeType<SpecialNode>("SpecialNode", params);
* }
*
* IMPORTANT: this function MUST be declared in a cpp file, NOT a header file.
* You must add the definition [BT_PLUGIN_EXPORT] in CMakeLists.txt using:
*
* target_compile_definitions(my_plugin_target PRIVATE BT_PLUGIN_EXPORT )
*/
#define BT_REGISTER_ROS_NODES(factory, params) \
BTCPP_EXPORT void BT_RegisterRosNodeFromPlugin(BT::BehaviorTreeFactory& factory, \
const BT::RosNodeParams& params)
// Use this macro to generate a plugin for:
//
// - BT::RosActionNode
// - BT::RosServiceNode
// - BT::RosTopicPubNode
// - BT::RosTopicSubNode
//
// - First argument: type to register (name of the class)
// - Second argument: string with the registration name
//
// Usage example:
// CreateRosNodePlugin(MyClassName, "MyClassName");
#define CreateRosNodePlugin(TYPE, REGISTRATION_NAME) \
BTCPP_EXPORT void BT_RegisterRosNodeFromPlugin(BT::BehaviorTreeFactory& factory, \
const BT::RosNodeParams& params) \
{ \
factory.registerNodeType<TYPE>(REGISTRATION_NAME, params); \
}
/**
* @brief RegisterRosNode function used to load a plugin and register
* the containing Node definition.
*
* @param factory the factory where the node should be registered.
* @param filepath path to the plugin.
* @param params parameters to pass to the instances of the Node.
*/
inline void RegisterRosNode(BT::BehaviorTreeFactory& factory,
const std::filesystem::path& filepath,
const BT::RosNodeParams& params)
{
BT::SharedLibrary loader(filepath.generic_string());
typedef void (*Func)(BT::BehaviorTreeFactory&, const BT::RosNodeParams&);
auto func = (Func)loader.getSymbol(BT::ROS_PLUGIN_SYMBOL);
func(factory, params);
}
@@ -0,0 +1,52 @@
// Copyright (c) 2023 Davide Faconti, Unmanned Life
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <rclcpp/rclcpp.hpp>
#include <string>
#include <chrono>
#include <memory>
namespace BT
{
struct RosNodeParams
{
std::weak_ptr<rclcpp::Node> nh;
// This has different meaning based on the context:
//
// - RosActionNode: name of the action server
// - RosServiceNode: name of the service
// - RosTopicPubNode: name of the topic to publish to
// - RosTopicSubNode: name of the topic to subscribe to
std::string default_port_value;
// parameters used only by service client and action clients
// timeout when sending a request
std::chrono::milliseconds server_timeout = std::chrono::milliseconds(1000);
// timeout used when detecting the server the first time
std::chrono::milliseconds wait_for_server_timeout = std::chrono::milliseconds(500);
RosNodeParams() = default;
RosNodeParams(std::shared_ptr<rclcpp::Node> node) : nh(node)
{}
RosNodeParams(std::shared_ptr<rclcpp::Node> node, const std::string& port_name)
: nh(node), default_port_value(port_name)
{}
};
} // namespace BT
@@ -0,0 +1,199 @@
// Copyright 2024 Marq Rasmussen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#pragma once
#include <memory>
#include <optional>
#include "btcpp_ros2_interfaces/action/execute_tree.hpp"
#include "behaviortree_cpp/bt_factory.h"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
namespace BT
{
/**
* @brief TreeExecutionServer class hosts a ROS Action Server that is able
* to load Behavior plugins, BehaviorTree.xml files and execute them.
*
* These are named in the ROS2 node's parameters, see
* @link bt_executor_parameters.md @endlink
*
* A `BT::Groot2Publisher` is included inside (see BehaviorTree.CPP for more information).
*
* It can be customized by overriding its virtual functions.
*/
class TreeExecutionServer
{
public:
using ExecuteTree = btcpp_ros2_interfaces::action::ExecuteTree;
using GoalHandleExecuteTree = rclcpp_action::ServerGoalHandle<ExecuteTree>;
/**
* @brief Constructor that will create its own instance of rclcpp::Node
*/
explicit TreeExecutionServer(const rclcpp::NodeOptions& options)
: TreeExecutionServer(std::make_unique<rclcpp::Node>("bt_action_server", options))
{}
/**
* @brief Constructor to use when an already existing node should be used.
*/
explicit TreeExecutionServer(const rclcpp::Node::SharedPtr& node);
virtual ~TreeExecutionServer();
/**
* @brief Gets the NodeBaseInterface of node_.
* @details This function exists to allow running TreeExecutionServer as a component in a composable node container.
* The name of this method shall not change to work properly with the component composer.
*/
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr get_node_base_interface();
/// @brief Gets the rclcpp::Node pointer
rclcpp::Node::SharedPtr node();
/// @brief Name of the tree being executed
const std::string& treeName() const;
/// @brief The payload received in the last goal
const std::string& goalPayload() const;
/// @brief Tree being executed.
const BT::Tree& tree() const;
/// @brief Pointer to the global blackboard
BT::Blackboard::Ptr globalBlackboard();
/// @brief The behavior tree factory
BT::BehaviorTreeFactory& factory();
protected:
/**
* @brief Callback invoked when a goal is received and before the tree is created.
* If it returns false, the goal will be rejected.
*/
virtual bool onGoalReceived(const std::string& tree_name, const std::string& payload)
{
return true;
}
/**
* @brief Callback invoked after the tree is created.
* It can be used, for instance, to initialize a logger or the global blackboard.
*
* @param tree The tree that was created
*/
virtual void onTreeCreated(BT::Tree& tree)
{}
/**
* @brief registerNodesIntoFactory is a callback invoked after the
* plugins were registered into the BT::BehaviorTreeFactory.
* It can be used to register additional custom nodes manually.
*
* @param factory The factory to use to register nodes
*/
virtual void registerNodesIntoFactory(BT::BehaviorTreeFactory& factory)
{}
/**
* @brief onLoopAfterTick invoked at each loop, after tree.tickOnce().
* If it returns a valid NodeStatus, the tree will stop and return that status.
* Return std::nullopt to continue the execution.
*
* @param status The status of the tree after the last tick
*/
virtual std::optional<BT::NodeStatus> onLoopAfterTick(BT::NodeStatus status)
{
return std::nullopt;
}
/**
* @brief onTreeExecutionCompleted is a callback invoked after the tree execution is completed,
* i.e. if it returned SUCCESS/FAILURE or if the action was cancelled by the Action Client.
*
* @param status The status of the tree after the last tick
* @param was_cancelled True if the action was cancelled by the Action Client
*
* @return if not std::nullopt, the string will be sent as [return_message] to the Action Client.
*/
virtual std::optional<std::string> onTreeExecutionCompleted(BT::NodeStatus status,
bool was_cancelled)
{
return std::nullopt;
}
/**
* @brief onLoopFeedback is a callback invoked at each loop, after tree.tickOnce().
* If it returns a valid string, it will be sent as feedback to the Action Client.
*
* If you don't want to return any feedback, return std::nullopt.
*/
virtual std::optional<std::string> onLoopFeedback()
{
return std::nullopt;
}
protected:
/**
* @brief Method to register the trees and BT custom nodes.
* It will call registerNodesIntoFactory().
*
* This callback will invoked asynchronously when this rclcpp Node is attached
* to a rclcpp Executor.
* Alternatively, it can be called synchronously in the constructor of a
* __derived__ class of TreeExecutionServer.
*/
void executeRegistration();
private:
struct Pimpl;
std::unique_ptr<Pimpl> p_;
rclcpp::Node::SharedPtr node_;
/**
* @brief handle the goal requested: accept or reject. This implementation always accepts.
* @param uuid Goal ID
* @param goal A shared pointer to the specific goal
* @return GoalResponse response of the goal processed
*/
rclcpp_action::GoalResponse handle_goal(const rclcpp_action::GoalUUID& uuid,
std::shared_ptr<const ExecuteTree::Goal> goal);
/**
* @brief Accepts cancellation requests of action server.
* @param goal A server goal handle to cancel
* @return CancelResponse response of the goal cancelled
*/
rclcpp_action::CancelResponse
handle_cancel(const std::shared_ptr<GoalHandleExecuteTree> goal_handle);
/**
* @brief Handles accepted goals and starts a thread to process them
* @param goal_handle Server goal handle to process feedback and set the response when finished
*/
void handle_accepted(const std::shared_ptr<GoalHandleExecuteTree> goal_handle);
/**
* @brief Background processes to execute the BehaviorTree and handle stop requests
* @param goal_handle Server goal handle to process feedback and set the response when finished
*/
void execute(const std::shared_ptr<GoalHandleExecuteTree> goal_handle);
};
} // namespace BT
@@ -0,0 +1,27 @@
<package format="3">
<name>behaviortree_ros2</name>
<version>0.3.0</version>
<description>
This package provides a ROS2 wrapper, on top of BehaviorTree.CPP.
</description>
<maintainer email="davide.faconti@gmail.com">Davide Faconti</maintainer>
<license>MIT</license>
<author>Davide Faconti</author>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>fmt</depend>
<depend>libboost-dev</depend>
<depend>rclcpp</depend>
<depend>rclcpp_action</depend>
<depend>behaviortree_cpp</depend>
<depend>generate_parameter_library</depend>
<depend>btcpp_ros2_interfaces</depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,66 @@
# ROS Behavior Wrappers
A base class is used to implement each Behavior type for a ROS Action, Service or Topic Publisher / Subscriber.
Users are expected to create a derived class and can implement the following methods.
# ROS Action Behavior Wrapper
### bool setGoal(Goal& goal)
Required callback that allows the user to set the goal message.
Return false if the request should not be sent. In that case, RosActionNode::onFailure(INVALID_GOAL) will be called.
### BT::NodeStatus onResultReceived(const WrappedResult& result)
Required callback invoked when the result is received by the server.
It is up to the user to define if the action returns SUCCESS or FAILURE.
### BT::NodeStatus onFeedback(const std::shared_ptr<const Feedback> feedback)
Optional callback invoked when the feedback is received.
It generally returns RUNNING, but the user can also use this callback to cancel the current action and return SUCCESS or FAILURE.
### BT::NodeStatus onFailure(ActionNodeErrorCode error)
Optional callback invoked when something goes wrong.
It must return either SUCCESS or FAILURE.
### void onHalt()
Optional callback executed when the node is halted.
Note that cancelGoal() is done automatically.
# ROS Service Behavior Wrapper
### setRequest(typename Request::SharedPtr& request)
Required callback that allows the user to set the request message (ServiceT::Request).
### BT::NodeStatus onResponseReceived(const typename Response::SharedPtr& response)
Required callback invoked when the response is received by the server.
It is up to the user to define if this returns SUCCESS or FAILURE.
### BT::NodeStatus onFailure(ServiceNodeErrorCode error)
Optional callback invoked when something goes wrong; you can override it.
It must return either SUCCESS or FAILURE.
# ROS Topic Publisher Wrapper
### bool setMessage(TopicT& msg)
Required callback invoked in tick to allow the user to pass the message to be published.
# ROS Topic Subscriber Wrapper
### NodeStatus onTick(const std::shared_ptr<TopicT>& last_msg)
Required callback invoked in the tick. You must return either SUCCESS of FAILURE.
### bool latchLastMessage()
Optional callback to latch the message that has been processed.
If returns false and no new message is received, before next call there will be no message to process.
If returns true, the next call will process the same message again, if no new message received.
@@ -0,0 +1,49 @@
bt_server:
action_name: {
type: string,
default_value: "bt_execution",
read_only: true,
description: "The name the Action Server takes requests from",
}
tick_frequency: {
type: int,
default_value: 100,
read_only: true,
description: "Frequency in Hz to tick() the Behavior tree at",
validation: {
bounds<>: [1, 1000]
}
}
groot2_port: {
type: int,
default_value: 1667,
read_only: true,
description: "Server port value to publish Groot2 messages on",
validation: {
bounds<>: [1, 49151]
}
}
plugins: {
type: string_array,
default_value: [],
description: "List of 'package_name/subfolder' containing BehaviorTree plugins to load into the factory",
validation: {
unique<>: null,
}
}
ros_plugins_timeout: {
type: int,
default_value: 1000,
description: "Timeout (ms) used in BT::RosNodeParams",
validation: {
bounds<>: [1, 10000]
}
}
behavior_trees: {
type: string_array,
default_value: [],
description: "List of 'package_name/subfolder' containing SubTrees to load into the BehaviorTree factory",
validation: {
unique<>: null,
}
}
@@ -0,0 +1,4 @@
#include "behaviortree_ros2/bt_action_node.hpp"
#include "behaviortree_ros2/bt_service_node.hpp"
#include "behaviortree_ros2/bt_topic_sub_node.hpp"
#include "behaviortree_ros2/bt_topic_pub_node.hpp"
@@ -0,0 +1,37 @@
#include "behaviortree_ros2/bt_ros_logger.hpp"
namespace BT
{
RosLogger::RosLogger(const BT::Tree& tree, std::shared_ptr<rclcpp::Node> node)
: StatusChangeLogger(tree.rootNode()), node_(node)
{}
RosLogger::~RosLogger()
{}
void RosLogger::callback(Duration timestamp, const TreeNode& node, NodeStatus prev_status,
NodeStatus status)
{
using namespace std::chrono;
// get ros node pointer
auto ros_node = node_.lock();
if(ros_node)
{
constexpr const char* whitespaces = " ";
constexpr const size_t ws_count = 25;
double since_epoch = duration<double>(timestamp).count();
RCLCPP_DEBUG(ros_node->get_logger(), "[%.3f]: %s%s %s -> %s", since_epoch,
node.name().c_str(),
&whitespaces[std::min(ws_count, node.name().size())],
toStr(prev_status, true).c_str(), toStr(status, true).c_str());
}
}
void RosLogger::flush()
{}
} // namespace BT
@@ -0,0 +1,175 @@
// Copyright 2024 Marq Rasmussen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "behaviortree_ros2/bt_utils.hpp"
#include "behaviortree_ros2/plugins.hpp"
namespace
{
static const auto kLogger = rclcpp::get_logger("bt_action_server");
}
namespace BT
{
btcpp_ros2_interfaces::msg::NodeStatus ConvertNodeStatus(BT::NodeStatus& status)
{
btcpp_ros2_interfaces::msg::NodeStatus action_status;
switch(status)
{
case BT::NodeStatus::RUNNING:
action_status.status = btcpp_ros2_interfaces::msg::NodeStatus::RUNNING;
break;
case BT::NodeStatus::SUCCESS:
action_status.status = btcpp_ros2_interfaces::msg::NodeStatus::SUCCESS;
break;
case BT::NodeStatus::FAILURE:
action_status.status = btcpp_ros2_interfaces::msg::NodeStatus::FAILURE;
break;
case BT::NodeStatus::IDLE:
action_status.status = btcpp_ros2_interfaces::msg::NodeStatus::IDLE;
break;
case BT::NodeStatus::SKIPPED:
action_status.status = btcpp_ros2_interfaces::msg::NodeStatus::SKIPPED;
break;
}
return action_status;
}
std::string GetDirectoryPath(const std::string& parameter_value)
{
std::string package_name, subfolder;
auto pos = parameter_value.find_first_of("/");
if(pos == parameter_value.size())
{
RCLCPP_ERROR(kLogger, "Invalid Parameter: %s. Missing subfolder delimiter '/'.",
parameter_value.c_str());
return "";
}
package_name = std::string(parameter_value.begin(), parameter_value.begin() + pos);
subfolder = std::string(parameter_value.begin() + pos + 1, parameter_value.end());
try
{
std::string search_directory =
ament_index_cpp::get_package_share_directory(package_name) + "/" + subfolder;
RCLCPP_DEBUG(kLogger, "Searching for Plugins/BehaviorTrees in path: %s",
search_directory.c_str());
return search_directory;
}
catch(const std::exception& e)
{
RCLCPP_ERROR(kLogger, "Failed to find package: %s \n %s", package_name.c_str(),
e.what());
}
return "";
}
void LoadBehaviorTrees(BT::BehaviorTreeFactory& factory,
const std::string& directory_path)
{
using std::filesystem::directory_iterator;
for(const auto& entry : directory_iterator(directory_path))
{
if(entry.path().extension() == ".xml")
{
try
{
factory.registerBehaviorTreeFromFile(entry.path().string());
RCLCPP_INFO(kLogger, "Loaded BehaviorTree: %s", entry.path().filename().c_str());
}
catch(const std::exception& e)
{
RCLCPP_ERROR(kLogger, "Failed to load BehaviorTree: %s \n %s",
entry.path().filename().c_str(), e.what());
}
}
}
}
void LoadPlugin(BT::BehaviorTreeFactory& factory, const std::filesystem::path& file_path,
BT::RosNodeParams params)
{
const auto filename = file_path.filename();
try
{
BT::SharedLibrary loader(file_path.string());
if(loader.hasSymbol(BT::PLUGIN_SYMBOL))
{
typedef void (*Func)(BehaviorTreeFactory&);
auto func = (Func)loader.getSymbol(BT::PLUGIN_SYMBOL);
func(factory);
}
else if(loader.hasSymbol(BT::ROS_PLUGIN_SYMBOL))
{
typedef void (*Func)(BT::BehaviorTreeFactory&, const BT::RosNodeParams&);
auto func = (Func)loader.getSymbol(BT::ROS_PLUGIN_SYMBOL);
func(factory, params);
}
else
{
RCLCPP_ERROR(kLogger, "Failed to load Plugin from file: %s.", filename.c_str());
return;
}
RCLCPP_INFO(kLogger, "Loaded ROS Plugin: %s", filename.c_str());
}
catch(const std::exception& ex)
{
RCLCPP_ERROR(kLogger, "Failed to load ROS Plugin: %s \n %s", filename.c_str(),
ex.what());
}
}
void RegisterPlugins(bt_server::Params& params, BT::BehaviorTreeFactory& factory,
rclcpp::Node::SharedPtr node)
{
BT::RosNodeParams ros_params;
ros_params.nh = node;
ros_params.server_timeout = std::chrono::milliseconds(params.ros_plugins_timeout);
ros_params.wait_for_server_timeout = ros_params.server_timeout;
for(const auto& plugin : params.plugins)
{
const auto plugin_directory = GetDirectoryPath(plugin);
// skip invalid plugins directories
if(plugin_directory.empty())
{
continue;
}
using std::filesystem::directory_iterator;
for(const auto& entry : directory_iterator(plugin_directory))
{
if(entry.path().extension() == ".so")
{
LoadPlugin(factory, entry.path(), ros_params);
}
}
}
}
void RegisterBehaviorTrees(bt_server::Params& params, BT::BehaviorTreeFactory& factory,
rclcpp::Node::SharedPtr node)
{
for(const auto& tree_dir : params.behavior_trees)
{
const auto tree_directory = GetDirectoryPath(tree_dir);
// skip invalid subtree directories
if(tree_directory.empty())
continue;
LoadBehaviorTrees(factory, tree_directory);
}
}
} // namespace BT
@@ -0,0 +1,324 @@
// Copyright 2024 Marq Rasmussen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4244)
#include <thread>
#pragma warning(pop)
#else
#include <thread>
#endif
// auto-generated header, created by generate_parameter_library
#include "behaviortree_ros2/bt_executor_parameters.hpp"
#include "behaviortree_ros2/tree_execution_server.hpp"
#include "behaviortree_ros2/bt_utils.hpp"
#include "behaviortree_cpp/loggers/groot2_publisher.h"
#include "btcpp_ros2_interfaces/srv/get_trees.hpp"
namespace
{
static const auto kLogger = rclcpp::get_logger("bt_action_server");
}
namespace BT
{
using GetTrees = btcpp_ros2_interfaces::srv::GetTrees;
struct TreeExecutionServer::Pimpl
{
rclcpp_action::Server<ExecuteTree>::SharedPtr action_server;
std::thread action_thread;
std::shared_ptr<bt_server::ParamListener> param_listener;
bt_server::Params params;
rclcpp::Service<GetTrees>::SharedPtr get_trees_service;
BT::BehaviorTreeFactory factory;
std::shared_ptr<BT::Groot2Publisher> groot_publisher;
std::string tree_name;
std::string payload;
BT::Tree tree;
BT::Blackboard::Ptr global_blackboard;
bool factory_initialized_ = false;
rclcpp::WallTimer<rclcpp::VoidCallbackType>::SharedPtr single_shot_timer;
};
TreeExecutionServer::TreeExecutionServer(const rclcpp::Node::SharedPtr& node)
: p_(new Pimpl), node_(node)
{
p_->param_listener = std::make_shared<bt_server::ParamListener>(node_);
p_->params = p_->param_listener->get_params();
p_->global_blackboard = BT::Blackboard::create();
// create the action server
const auto action_name = p_->params.action_name;
RCLCPP_INFO(kLogger, "Starting Action Server: %s", action_name.c_str());
p_->action_server = rclcpp_action::create_server<ExecuteTree>(
node_, action_name,
[this](const rclcpp_action::GoalUUID& uuid,
std::shared_ptr<const ExecuteTree::Goal> goal) {
return handle_goal(uuid, std::move(goal));
},
[this](const std::shared_ptr<GoalHandleExecuteTree> goal_handle) {
return handle_cancel(std::move(goal_handle));
},
[this](const std::shared_ptr<GoalHandleExecuteTree> goal_handle) {
handle_accepted(std::move(goal_handle));
});
// we use a wall timer to run asynchronously executeRegistration();
rclcpp::VoidCallbackType callback = [this]() {
if(!p_->factory_initialized_)
{
executeRegistration();
}
// we must cancel the timer after the first execution
p_->single_shot_timer->cancel();
};
p_->get_trees_service = node_->create_service<GetTrees>(
"get_loaded_trees", [this](const std::shared_ptr<GetTrees::Request> _,
std::shared_ptr<GetTrees::Response> response) {
response->tree_ids = p_->factory.registeredBehaviorTrees();
});
p_->single_shot_timer =
node_->create_wall_timer(std::chrono::milliseconds(1), callback);
}
TreeExecutionServer::~TreeExecutionServer()
{}
void TreeExecutionServer::executeRegistration()
{
// Before executing check if we have new Behaviors or Subtrees to reload
p_->factory.clearRegisteredBehaviorTrees();
p_->params = p_->param_listener->get_params();
// user defined method
registerNodesIntoFactory(p_->factory);
// load plugins from multiple directories
RegisterPlugins(p_->params, p_->factory, node_);
// load trees (XML) from multiple directories
RegisterBehaviorTrees(p_->params, p_->factory, node_);
p_->factory_initialized_ = true;
}
rclcpp::node_interfaces::NodeBaseInterface::SharedPtr
TreeExecutionServer::get_node_base_interface()
{
return node_->get_node_base_interface();
}
rclcpp::Node::SharedPtr TreeExecutionServer::node()
{
return node_;
}
rclcpp_action::GoalResponse
TreeExecutionServer::handle_goal(const rclcpp_action::GoalUUID& /* uuid */,
std::shared_ptr<const ExecuteTree::Goal> goal)
{
RCLCPP_INFO(kLogger, "Received goal request to execute Behavior Tree: %s",
goal->target_tree.c_str());
if(!onGoalReceived(goal->target_tree, goal->payload))
{
return rclcpp_action::GoalResponse::REJECT;
}
return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
}
rclcpp_action::CancelResponse TreeExecutionServer::handle_cancel(
const std::shared_ptr<GoalHandleExecuteTree> goal_handle)
{
RCLCPP_INFO(kLogger, "Received request to cancel goal");
if(!goal_handle->is_active())
{
RCLCPP_WARN(kLogger, "Rejecting request to cancel goal because the server is not "
"processing one.");
return rclcpp_action::CancelResponse::REJECT;
}
return rclcpp_action::CancelResponse::ACCEPT;
}
void TreeExecutionServer::handle_accepted(
const std::shared_ptr<GoalHandleExecuteTree> goal_handle)
{
// Join the previous execute thread before replacing it with a new one
if(p_->action_thread.joinable())
{
p_->action_thread.join();
}
// To avoid blocking the executor start a new thread to process the goal
p_->action_thread = std::thread{ [=]() { execute(goal_handle); } };
}
void TreeExecutionServer::execute(
const std::shared_ptr<GoalHandleExecuteTree> goal_handle)
{
const auto goal = goal_handle->get_goal();
BT::NodeStatus status = BT::NodeStatus::RUNNING;
auto action_result = std::make_shared<ExecuteTree::Result>();
// Before executing check if we have new Behaviors or Subtrees to reload
if(p_->param_listener->is_old(p_->params))
{
executeRegistration();
}
// Loop until something happens with ROS or the node completes
try
{
// This blackboard will be owned by "MainTree". It parent is p_->global_blackboard
auto root_blackboard = BT::Blackboard::create(p_->global_blackboard);
p_->tree = p_->factory.createTree(goal->target_tree, root_blackboard);
p_->tree_name = goal->target_tree;
p_->payload = goal->payload;
// call user defined function after the tree has been created
onTreeCreated(p_->tree);
p_->groot_publisher.reset();
p_->groot_publisher =
std::make_shared<BT::Groot2Publisher>(p_->tree, p_->params.groot2_port);
// Loop until the tree is done or a cancel is requested
const auto period =
std::chrono::milliseconds(static_cast<int>(1000.0 / p_->params.tick_frequency));
auto loop_deadline = std::chrono::steady_clock::now() + period;
// operations to be done if the tree execution is aborted, either by
// cancel requested or by onLoopAfterTick()
auto stop_action = [this, &action_result](BT::NodeStatus status,
const std::string& message) {
p_->tree.haltTree();
action_result->node_status = ConvertNodeStatus(status);
// override the message value if the user defined function returns it
if(auto msg = onTreeExecutionCompleted(status, true))
{
action_result->return_message = msg.value();
}
else
{
action_result->return_message = message;
}
RCLCPP_WARN(kLogger, action_result->return_message.c_str());
};
while(rclcpp::ok() && status == BT::NodeStatus::RUNNING)
{
if(goal_handle->is_canceling())
{
stop_action(status, "Action Server canceling and halting Behavior Tree");
goal_handle->canceled(action_result);
return;
}
// tick the tree once and publish the action feedback
status = p_->tree.tickExactlyOnce();
if(const auto res = onLoopAfterTick(status); res.has_value())
{
stop_action(res.value(), "Action Server aborted by onLoopAfterTick()");
goal_handle->abort(action_result);
return;
}
if(const auto res = onLoopFeedback(); res.has_value())
{
auto feedback = std::make_shared<ExecuteTree::Feedback>();
feedback->message = res.value();
goal_handle->publish_feedback(feedback);
}
const auto now = std::chrono::steady_clock::now();
if(now < loop_deadline)
{
p_->tree.sleep(std::chrono::duration_cast<std::chrono::system_clock::duration>(
loop_deadline - now));
}
loop_deadline += period;
}
}
catch(const std::exception& ex)
{
action_result->return_message = std::string("Behavior Tree exception:") + ex.what();
RCLCPP_ERROR(kLogger, action_result->return_message.c_str());
goal_handle->abort(action_result);
return;
}
// Call user defined onTreeExecutionCompleted function.
// Override the message value if the user defined function returns it
if(auto msg = onTreeExecutionCompleted(status, false))
{
action_result->return_message = msg.value();
}
else
{
action_result->return_message =
std::string("Tree finished with status: ") + BT::toStr(status);
}
// set the node_status result to the action
action_result->node_status = ConvertNodeStatus(status);
// return success or aborted for the action result
if(status == BT::NodeStatus::SUCCESS)
{
RCLCPP_INFO(kLogger, action_result->return_message.c_str());
goal_handle->succeed(action_result);
}
else
{
RCLCPP_ERROR(kLogger, action_result->return_message.c_str());
goal_handle->abort(action_result);
}
}
const std::string& TreeExecutionServer::treeName() const
{
return p_->tree_name;
}
const std::string& TreeExecutionServer::goalPayload() const
{
return p_->payload;
}
const BT::Tree& TreeExecutionServer::tree() const
{
return p_->tree;
}
BT::Blackboard::Ptr TreeExecutionServer::globalBlackboard()
{
return p_->global_blackboard;
}
BT::BehaviorTreeFactory& TreeExecutionServer::factory()
{
return p_->factory;
}
} // namespace BT
@@ -0,0 +1,75 @@
# TreeExecutionServer
This base class is used to implement a Behavior Tree executor wrapped inside a `rclcpp_action::Server`.
Users are expected to create a derived class to improve its functionalities, but often it can be used
out of the box directly.
Further, the terms "load" will be equivalent to "register into the `BT::BehaviorTreeFactory`".
The `TreeExecutionServer` offers the following features:
- Configurable using ROS parameters (see below).
- Load Behavior Trees definitions (XML files) from a list of folders.
- Load BT plugins from a list of folders. These plugins may depend or not on ROS.
- Invoke the execution of a Tree from an external ROS Node, using `rclcpp_action::Client`.
Furthermore, the user can customize it to:
- Register custom BT Nodes directly (static linking).
- Attach additional loggers. The **Groot2** publisher will be attached by default.
- Use the "global blackboard", a new idiom/pattern explained in [this tutorial](https://github.com/BehaviorTree/BehaviorTree.CPP/blob/master/examples/t16_global_blackboard.cpp).
- Customize the feedback of the `rclcpp_action::Server`.
## Customization points
These are the virtual method of `TreeExecutionServer` that can be overridden by the user.
### void onTreeCreated(BT::Tree& tree)
Callback invoked when a tree is created; this happens after `rclcpp_action::Server` receive a command from a client.
It can be used, for instance, to initialize a logger or the global blackboard.
### void registerNodesIntoFactory(BT::BehaviorTreeFactory& factory)
Called at the beginning, after all the plugins have been loaded.
It can be used to register programmatically more BT.CPP Nodes.
### std::optional<BT::NodeStatus> onLoopAfterTick(BT::NodeStatus status)
Used to do something after the tree was ticked, in its execution loop.
If this method returns something other than `std::nullopt`, the tree
execution is interrupted an the specified `BT::NodeStatus` is returned to the `rclcpp_action::Client`.
### void onTreeExecutionCompleted(BT::NodeStatus status, bool was_cancelled)
Callback when the tree execution reaches its end.
This happens if:
1. Ticking the tree returns SUCCESS/FAILURE
2. The `rclcpp_action::Client` cancels the action.
3. Callback `onLoopAfterTick`cancels the execution.
Argument `was_cancelled`is true in the 1st case, false otherwise.
### std::optional<std::string> onLoopFeedback()
This callback is invoked after `tree.tickOnce` and `onLoopAfterTick`.
If it returns something other than `std::nullopt`, the provided string will be
sent as feedback to the `rclcpp_action::Client`.
## ROS Parameters
Documentation for the parameters used by the `TreeExecutionServer` can be found [here](bt_executor_parameters.md).
If the parameter documentation needs updating you can regenerate it with:
```bash
generate_parameter_library_markdown --input_yaml src/bt_executor_parameters.yaml --output_markdown_file bt_executor_parameters.md
```
@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.16)
project(btcpp_ros2_interfaces)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(ament_cmake REQUIRED)
find_package(rosidl_default_generators REQUIRED)
rosidl_generate_interfaces(btcpp_ros2_interfaces
"msg/NodeStatus.msg"
"srv/GetTrees.srv"
"action/ExecuteTree.action"
"action/Sleep.action")
ament_export_dependencies(rosidl_default_runtime)
ament_package()
@@ -0,0 +1,18 @@
#### Request ####
# Name of the tree to execute
string target_tree
# Optional, implementation-dependent, payload.
string payload
---
#### Result ####
# Status of the tree
NodeStatus node_status
# result payload or error message
string return_message
---
#### Feedback ####
#This can be customized by the user
string message
@@ -0,0 +1,8 @@
#goal definition
int32 msec_timeout
---
#result definition
bool done
---
#feedback
int32 cycle
@@ -0,0 +1,8 @@
# NodeStatus Enums
uint8 IDLE = 0
uint8 RUNNING = 1
uint8 SUCCESS = 2
uint8 FAILURE = 3
uint8 SKIPPED = 4
uint8 status
@@ -0,0 +1,27 @@
<package format="3">
<name>btcpp_ros2_interfaces</name>
<version>0.3.0</version>
<description>
ROS2 interfaces, mostly used to demonstrate behaviortree_ros2
</description>
<maintainer email="davide.faconti@gmail.com">Davide Faconti</maintainer>
<license>MIT</license>
<author>Davide Faconti</author>
<buildtool_depend>ament_cmake</buildtool_depend>
<buildtool_depend>rosidl_default_generators</buildtool_depend>
<exec_depend>rosidl_default_runtime</exec_depend>
<depend>action_msgs</depend>
<member_of_group>rosidl_interface_packages</member_of_group>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,8 @@
#### Request ####
# Empty
---
#### Result ####
# Ids of the available trees
string[] tree_ids
@@ -0,0 +1,101 @@
cmake_minimum_required(VERSION 3.16)
project(btcpp_ros2_samples)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(ament_cmake REQUIRED)
find_package(behaviortree_ros2 REQUIRED)
find_package(btcpp_ros2_interfaces REQUIRED)
find_package(std_msgs REQUIRED)
find_package(std_srvs REQUIRED)
set(THIS_PACKAGE_DEPS
behaviortree_ros2::behaviortree_ros2
${std_msgs_TARGETS}
${std_srvs_TARGETS}
${btcpp_ros2_interfaces_TARGETS} )
######################################################
# Simple example showing how to use and customize the BtExecutionServer
add_executable(sample_bt_executor src/sample_bt_executor.cpp)
target_link_libraries(sample_bt_executor ${THIS_PACKAGE_DEPS})
######################################################
# Build an Action Client that calls the sleep action (STATIC version)
add_executable(sleep_client
src/sleep_action.cpp
src/sleep_client.cpp)
target_link_libraries(sleep_client ${THIS_PACKAGE_DEPS})
######################################################
# Build a client that call the sleep action (Plugin version)
add_library(sleep_plugin SHARED src/sleep_action.cpp)
target_compile_definitions(sleep_plugin PRIVATE BT_PLUGIN_EXPORT )
target_link_libraries(sleep_plugin ${THIS_PACKAGE_DEPS})
add_executable(sleep_client_dyn src/sleep_client.cpp)
target_compile_definitions(sleep_client_dyn PRIVATE USE_SLEEP_PLUGIN )
target_link_libraries(sleep_client_dyn sleep_plugin )
target_link_libraries(sleep_client_dyn ${THIS_PACKAGE_DEPS})
######################################################
# Build Server
add_executable(sleep_server src/sleep_server.cpp)
target_link_libraries(sleep_server ${THIS_PACKAGE_DEPS})
######################################################
# Build subscriber_test
add_executable(subscriber_test src/subscriber_test.cpp)
target_link_libraries(subscriber_test ${THIS_PACKAGE_DEPS})
######################################################
# the SetBool test
add_executable(bool_client src/bool_client.cpp src/set_bool_node.cpp)
target_link_libraries(bool_client ${THIS_PACKAGE_DEPS})
add_executable(bool_server src/bool_server.cpp )
target_link_libraries(bool_server ${THIS_PACKAGE_DEPS})
######################################################
# INSTALL
install(TARGETS
sleep_client
sleep_client_dyn
sleep_server
sleep_plugin
subscriber_test
sample_bt_executor
bool_client
bool_server
DESTINATION lib/${PROJECT_NAME}
)
######################################################
# INSTALL plugins for other packages to load
install(TARGETS
sleep_plugin
LIBRARY DESTINATION share/${PROJECT_NAME}/bt_plugins
ARCHIVE DESTINATION share/${PROJECT_NAME}/bt_plugins
RUNTIME DESTINATION share/${PROJECT_NAME}/bt_plugins
)
######################################################
# INSTALL Behavior.xml's, ROS config and launch files
install(DIRECTORY
behavior_trees
config
launch
DESTINATION share/${PROJECT_NAME}/
)
ament_export_dependencies(behaviortree_ros2 btcpp_ros2_interfaces)
ament_package()
@@ -0,0 +1,35 @@
# Sample Behaviors
For documentation on sample behaviors included in this package please see the BehaviorTree.CPP [ROS 2 Integration documentation](https://www.behaviortree.dev/docs/ros2_integration). Documentation of the derived class methods can methods for each ROS interface type can be found [here](../behaviortree_ros2/ros_behavior_wrappers.md).
# TreeExecutionServer Sample
Documentation on the TreeExecutionServer used in this example can be found [here](../behaviortree_ros2/tree_execution_server.md).
To start the sample Execution Server that load a list of plugins and BehaviorTrees from `yaml` file:
``` bash
ros2 launch btcpp_ros2_samples sample_bt_executor.launch.xml
```
> *NOTE:* For documentation on the `yaml` parameters please see [bt_executor_parameters.md](../behaviortree_ros2/bt_executor_parameters.md).
As the Server starts up it will print out the name of the ROS Action followed by the plugins and BehaviorTrees it was able to load.
```
[bt_action_server]: Starting Action Server: behavior_server
[bt_action_server]: Loaded Plugin: libdummy_nodes_dyn.so
[bt_action_server]: Loaded Plugin: libmovebase_node_dyn.so
[bt_action_server]: Loaded Plugin: libcrossdoor_nodes_dyn.so
[bt_action_server]: Loaded Plugin: libsleep_plugin.so
[bt_action_server]: Loaded BehaviorTree: door_closed.xml
[bt_action_server]: Loaded BehaviorTree: cross_door.xml
```
To call the Action Server from the command line:
``` bash
ros2 action send_goal /behavior_server btcpp_ros2_interfaces/action/ExecuteTree "{target_tree: CrossDoor}"
```
You can also try a Behavior that is a ROS Action or Service client itself.
```bash
ros2 action send_goal /behavior_server btcpp_ros2_interfaces/action/ExecuteTree "{target_tree: SleepActionSample}"
```
@@ -0,0 +1,13 @@
<root BTCPP_format="4">
<BehaviorTree ID="CrossDoor">
<Sequence>
<Fallback>
<Inverter>
<IsDoorClosed/>
</Inverter>
<SubTree ID="DoorClosed"/>
</Fallback>
<PassThroughDoor/>
</Sequence>
</BehaviorTree>
</root>
@@ -0,0 +1,11 @@
<root BTCPP_format="4">
<BehaviorTree ID="DoorClosed">
<Fallback>
<OpenDoor/>
<RetryUntilSuccessful num_attempts="5">
<PickLock/>
</RetryUntilSuccessful>
<SmashDoor/>
</Fallback>
</BehaviorTree>
</root>
@@ -0,0 +1,15 @@
<root BTCPP_format="4">
<BehaviorTree ID="SleepActionSample">
<Sequence>
<SaySomething message="start"/>
<SleepAction name="sleepA" action_name="sleep_service" msec="2000"/>
<SaySomething message="sleep completed"/>
<Fallback>
<Timeout msec="1500">
<SleepAction name="sleepB" action_name="sleep_service" msec="2000"/>
</Timeout>
<SaySomething message="sleep aborted"/>
</Fallback>
</Sequence>
</BehaviorTree>
</root>
@@ -0,0 +1,13 @@
bt_action_server:
ros__parameters:
action_name: "behavior_server" # Optional (defaults to `bt_action_server`)
tick_frequency: 100 # Optional (defaults to 100 Hz)
groot2_port: 1667 # Optional (defaults to 1667)
ros_plugins_timeout: 1000 # Optional (defaults 1000 ms)
plugins:
- behaviortree_cpp/bt_plugins
- btcpp_ros2_samples/bt_plugins
behavior_trees:
- btcpp_ros2_samples/behavior_trees
@@ -0,0 +1,11 @@
<launch>
<arg name="sleep_server" default="true"/>
<node pkg="btcpp_ros2_samples" exec="sample_bt_executor" output="screen">
<param from="$(find-pkg-share btcpp_ros2_samples)/config/sample_bt_executor.yaml"/>
</node>
<group if="$(var sleep_server)">
<node pkg="btcpp_ros2_samples" exec="sleep_server" output="screen"/>
</group>
</launch>
@@ -0,0 +1,23 @@
<package format="3">
<name>btcpp_ros2_samples</name>
<version>0.3.0</version>
<description>
Examples related to behaviortree_ros2
</description>
<maintainer email="davide.faconti@gmail.com">Davide Faconti</maintainer>
<license>MIT</license>
<author>Davide Faconti</author>
<buildtool_depend>ament_cmake</buildtool_depend>
<depend>behaviortree_ros2</depend>
<depend>std_msgs</depend>
<depend>std_srvs</depend>
<depend>btcpp_ros2_interfaces</depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,45 @@
#include "behaviortree_ros2/bt_action_node.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp/executors.hpp"
#include "set_bool_node.hpp"
using namespace BT;
static const char* xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence>
<SetBoolA value="true"/>
<SetBool service_name="robotB/set_bool" value="true"/>
<SetRobotBool robot="robotA" value="true"/>
<SetRobotBool robot="robotB" value="true"/>
</Sequence>
</BehaviorTree>
</root>
)";
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto nh = std::make_shared<rclcpp::Node>("bool_client");
BehaviorTreeFactory factory;
// version with default port
factory.registerNodeType<SetBoolService>("SetBoolA", BT::RosNodeParams(nh, "robotA/"
"set_bool"));
// version without default port
factory.registerNodeType<SetBoolService>("SetBool", BT::RosNodeParams(nh));
// namespace version
factory.registerNodeType<SetRobotBoolService>("SetRobotBool", nh, "set_bool");
auto tree = factory.createTreeFromText(xml_text);
tree.tickWhileRunning();
return 0;
}
@@ -0,0 +1,37 @@
#include "rclcpp/rclcpp.hpp"
#include "std_srvs/srv/set_bool.hpp"
#include <memory>
void CallbackA(const std::shared_ptr<std_srvs::srv::SetBool::Request> request,
std::shared_ptr<std_srvs::srv::SetBool::Response> response)
{
response->success = request->data;
auto logger = rclcpp::get_logger("rclcpp");
RCLCPP_INFO(logger, "Incoming request A: %s", request->data ? "true" : "false");
}
void CallbackB(const std::shared_ptr<std_srvs::srv::SetBool::Request> request,
std::shared_ptr<std_srvs::srv::SetBool::Response> response)
{
response->success = request->data;
auto logger = rclcpp::get_logger("rclcpp");
RCLCPP_INFO(logger, "Incoming request B: %s", request->data ? "true" : "false");
}
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
std::shared_ptr<rclcpp::Node> node = rclcpp::Node::make_shared("add_two_ints_server");
auto serviceA =
node->create_service<std_srvs::srv::SetBool>("robotA/set_bool", &CallbackA);
auto serviceB =
node->create_service<std_srvs::srv::SetBool>("robotB/set_bool", &CallbackB);
RCLCPP_INFO(rclcpp::get_logger("rclcpp"), "Ready.");
rclcpp::spin(node);
rclcpp::shutdown();
}
@@ -0,0 +1,77 @@
// Copyright 2024 Marq Rasmussen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright
// notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include <behaviortree_ros2/tree_execution_server.hpp>
#include <behaviortree_cpp/loggers/bt_cout_logger.h>
#include <std_msgs/msg/float32.hpp>
// Example that shows how to customize TreeExecutionServer.
//
// Here, we:
// - add an extra logger, BT::StdCoutLogger
// - add a subscriber that will continuously update a variable in the global blackboard
class MyActionServer : public BT::TreeExecutionServer
{
public:
MyActionServer(const rclcpp::NodeOptions& options) : TreeExecutionServer(options)
{
// here we assume that the battery voltage is published as a std_msgs::msg::Float32
sub_ = node()->create_subscription<std_msgs::msg::Float32>(
"battery_level", 10, [this](const std_msgs::msg::Float32::SharedPtr msg) {
// Update the global blackboard
globalBlackboard()->set("battery_level", msg->data);
});
// Note that the callback above and the execution of the tree accessing the
// global blackboard happen in two different threads.
// The former runs in the MultiThreadedExecutor, while the latter in the thread created
// by TreeExecutionServer. But this is OK because the blackboard is thread-safe.
}
void onTreeCreated(BT::Tree& tree) override
{
logger_cout_ = std::make_shared<BT::StdCoutLogger>(tree);
}
std::optional<std::string> onTreeExecutionCompleted(BT::NodeStatus status,
bool was_cancelled) override
{
// NOT really needed, even if logger_cout_ may contain a dangling pointer of the tree
// at this point
logger_cout_.reset();
return std::nullopt;
}
private:
std::shared_ptr<BT::StdCoutLogger> logger_cout_;
rclcpp::Subscription<std_msgs::msg::Float32>::SharedPtr sub_;
};
int main(int argc, char* argv[])
{
rclcpp::init(argc, argv);
rclcpp::NodeOptions options;
auto action_server = std::make_shared<MyActionServer>(options);
// TODO: This workaround is for a bug in MultiThreadedExecutor where it can deadlock when spinning without a timeout.
// Deadlock is caused when Publishers or Subscribers are dynamically removed as the node is spinning.
rclcpp::executors::MultiThreadedExecutor exec(rclcpp::ExecutorOptions(), 0, false,
std::chrono::milliseconds(250));
exec.add_node(action_server->node());
exec.spin();
exec.remove_node(action_server->node());
rclcpp::shutdown();
}
@@ -0,0 +1,41 @@
#include "set_bool_node.hpp"
bool SetBoolService::setRequest(Request::SharedPtr& request)
{
getInput("value", request->data);
std::cout << "setRequest " << std::endl;
return true;
}
BT::NodeStatus SetBoolService::onResponseReceived(const Response::SharedPtr& response)
{
std::cout << "onResponseReceived " << std::endl;
if(response->success)
{
RCLCPP_INFO(logger(), "SetBool service succeeded.");
return BT::NodeStatus::SUCCESS;
}
else
{
RCLCPP_INFO(logger(), "SetBool service failed: %s", response->message.c_str());
return BT::NodeStatus::FAILURE;
}
}
BT::NodeStatus SetBoolService::onFailure(BT::ServiceNodeErrorCode error)
{
RCLCPP_ERROR(logger(), "Error: %d", error);
return BT::NodeStatus::FAILURE;
}
//-----------------------------------------------------------
BT::NodeStatus SetRobotBoolService::tick()
{
std::string robot;
if(getInput("robot", robot) && !robot.empty())
{
setServiceName(robot + "/" + service_suffix_);
}
return SetBoolService::tick();
}
@@ -0,0 +1,51 @@
#pragma once
#include <behaviortree_ros2/bt_service_node.hpp>
#include "std_srvs/srv/set_bool.hpp"
using SetBool = std_srvs::srv::SetBool;
class SetBoolService : public BT::RosServiceNode<SetBool>
{
public:
explicit SetBoolService(const std::string& name, const BT::NodeConfig& conf,
const BT::RosNodeParams& params)
: RosServiceNode<SetBool>(name, conf, params)
{}
static BT::PortsList providedPorts()
{
return providedBasicPorts({ BT::InputPort<bool>("value") });
}
bool setRequest(Request::SharedPtr& request) override;
BT::NodeStatus onResponseReceived(const Response::SharedPtr& response) override;
virtual BT::NodeStatus onFailure(BT::ServiceNodeErrorCode error) override;
private:
std::string service_suffix_;
};
//----------------------------------------------
class SetRobotBoolService : public SetBoolService
{
public:
explicit SetRobotBoolService(const std::string& name, const BT::NodeConfig& conf,
const rclcpp::Node::SharedPtr& node,
const std::string& port_name)
: SetBoolService(name, conf, BT::RosNodeParams(node)), service_suffix_(port_name)
{}
static BT::PortsList providedPorts()
{
return { BT::InputPort<std::string>("robot"), BT::InputPort<bool>("value") };
}
BT::NodeStatus tick() override;
private:
std::string service_suffix_;
};
@@ -0,0 +1,32 @@
#include "sleep_action.hpp"
#include "behaviortree_ros2/plugins.hpp"
bool SleepAction::setGoal(RosActionNode::Goal& goal)
{
auto timeout = getInput<unsigned>("msec");
goal.msec_timeout = timeout.value();
return true;
}
NodeStatus SleepAction::onResultReceived(const RosActionNode::WrappedResult& wr)
{
RCLCPP_INFO(logger(), "%s: onResultReceived. Done = %s", name().c_str(),
wr.result->done ? "true" : "false");
return wr.result->done ? NodeStatus::SUCCESS : NodeStatus::FAILURE;
}
NodeStatus SleepAction::onFailure(ActionNodeErrorCode error)
{
RCLCPP_ERROR(logger(), "%s: onFailure with error: %s", name().c_str(), toStr(error));
return NodeStatus::FAILURE;
}
void SleepAction::onHalt()
{
RCLCPP_INFO(logger(), "%s: onHalt", name().c_str());
}
// Plugin registration.
// The class SleepAction will self register with name "SleepAction".
CreateRosNodePlugin(SleepAction, "SleepAction");
@@ -0,0 +1,26 @@
#include "behaviortree_ros2/bt_action_node.hpp"
#include "btcpp_ros2_interfaces/action/sleep.hpp"
using namespace BT;
class SleepAction : public RosActionNode<btcpp_ros2_interfaces::action::Sleep>
{
public:
SleepAction(const std::string& name, const NodeConfig& conf,
const RosNodeParams& params)
: RosActionNode<btcpp_ros2_interfaces::action::Sleep>(name, conf, params)
{}
static BT::PortsList providedPorts()
{
return providedBasicPorts({ InputPort<unsigned>("msec") });
}
bool setGoal(Goal& goal) override;
void onHalt() override;
BT::NodeStatus onResultReceived(const WrappedResult& wr) override;
virtual BT::NodeStatus onFailure(ActionNodeErrorCode error) override;
};
@@ -0,0 +1,93 @@
#include "behaviortree_ros2/bt_action_node.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp/executors.hpp"
#include "behaviortree_ros2/plugins.hpp"
#ifndef USE_SLEEP_PLUGIN
#include "sleep_action.hpp"
#endif
using namespace BT;
//-------------------------------------------------------------
// Simple Action to print a number
//-------------------------------------------------------------
class PrintValue : public BT::SyncActionNode
{
public:
PrintValue(const std::string& name, const BT::NodeConfig& config)
: BT::SyncActionNode(name, config)
{}
BT::NodeStatus tick() override
{
std::string msg;
if(getInput("message", msg))
{
std::cout << "PrintValue: " << msg << std::endl;
return NodeStatus::SUCCESS;
}
else
{
std::cout << "PrintValue FAILED " << std::endl;
return NodeStatus::FAILURE;
}
}
static BT::PortsList providedPorts()
{
return { BT::InputPort<std::string>("message") };
}
};
//-----------------------------------------------------
// Simple tree, used to execute once each action.
static const char* xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence>
<PrintValue message="start"/>
<SleepAction name="sleepA" msec="2000"/>
<PrintValue message="sleep completed"/>
<Fallback>
<Timeout msec="1500">
<SleepAction name="sleepB" action_name="sleep_service" msec="2000"/>
</Timeout>
<PrintValue message="sleep aborted"/>
</Fallback>
</Sequence>
</BehaviorTree>
</root>
)";
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto nh = std::make_shared<rclcpp::Node>("sleep_client");
BehaviorTreeFactory factory;
factory.registerNodeType<PrintValue>("PrintValue");
RosNodeParams params;
params.nh = nh;
params.default_port_value = "sleep_service";
#ifdef USE_SLEEP_PLUGIN
RegisterRosNode(factory, "../lib/libsleep_action_plugin.so", params);
#else
factory.registerNodeType<SleepAction>("SleepAction", params);
#endif
auto tree = factory.createTreeFromText(xml_text);
for(int i = 0; i < 5; i++)
{
tree.tickWhileRunning();
}
return 0;
}
@@ -0,0 +1,100 @@
#include <functional>
#include <memory>
#include <thread>
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_action/rclcpp_action.hpp"
#include "btcpp_ros2_interfaces/action/sleep.hpp"
#include "behaviortree_ros2/bt_action_node.hpp"
class SleepActionServer : public rclcpp::Node
{
public:
using Sleep = btcpp_ros2_interfaces::action::Sleep;
using GoalHandleSleep = rclcpp_action::ServerGoalHandle<Sleep>;
explicit SleepActionServer(const rclcpp::NodeOptions& options = rclcpp::NodeOptions())
: Node("sleep_action_server", options)
{
using namespace std::placeholders;
this->action_server_ = rclcpp_action::create_server<Sleep>(
this, "sleep_service", std::bind(&SleepActionServer::handle_goal, this, _1, _2),
std::bind(&SleepActionServer::handle_cancel, this, _1),
std::bind(&SleepActionServer::handle_accepted, this, _1));
}
private:
rclcpp_action::Server<Sleep>::SharedPtr action_server_;
rclcpp_action::GoalResponse handle_goal(const rclcpp_action::GoalUUID&,
std::shared_ptr<const Sleep::Goal> goal)
{
RCLCPP_INFO(this->get_logger(), "Received goal request with sleep time %d",
goal->msec_timeout);
return rclcpp_action::GoalResponse::ACCEPT_AND_EXECUTE;
}
rclcpp_action::CancelResponse
handle_cancel(const std::shared_ptr<GoalHandleSleep> goal_handle)
{
RCLCPP_INFO(this->get_logger(), "Received request to cancel goal");
(void)goal_handle;
return rclcpp_action::CancelResponse::ACCEPT;
}
void handle_accepted(const std::shared_ptr<GoalHandleSleep> goal_handle)
{
using namespace std::placeholders;
// this needs to return quickly to avoid blocking the executor, so spin up a new thread
std::thread{ std::bind(&SleepActionServer::execute, this, _1), goal_handle }.detach();
}
void execute(const std::shared_ptr<GoalHandleSleep> goal_handle)
{
RCLCPP_INFO(this->get_logger(), "Executing goal");
rclcpp::Rate loop_rate(5);
const auto goal = goal_handle->get_goal();
auto feedback = std::make_shared<Sleep::Feedback>();
auto result = std::make_shared<Sleep::Result>();
rclcpp::Time deadline = get_clock()->now() + rclcpp::Duration::from_seconds(
double(goal->msec_timeout) / 1000);
int cycle = 0;
while(get_clock()->now() < deadline)
{
if(goal_handle->is_canceling())
{
result->done = false;
goal_handle->canceled(result);
RCLCPP_INFO(this->get_logger(), "Goal canceled");
return;
}
feedback->cycle = cycle++;
goal_handle->publish_feedback(feedback);
RCLCPP_INFO(this->get_logger(), "Publish feedback");
loop_rate.sleep();
}
// Check if goal is done
if(rclcpp::ok())
{
result->done = true;
goal_handle->succeed(result);
RCLCPP_INFO(this->get_logger(), "Goal succeeded");
}
}
}; // class SleepActionServer
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto node = std::make_shared<SleepActionServer>();
rclcpp::spin(node);
return 0;
}
@@ -0,0 +1,63 @@
#include "behaviortree_ros2/bt_topic_sub_node.hpp"
#include <std_msgs/msg/string.hpp>
using namespace BT;
class ReceiveString : public RosTopicSubNode<std_msgs::msg::String>
{
public:
ReceiveString(const std::string& name, const NodeConfig& conf,
const RosNodeParams& params)
: RosTopicSubNode<std_msgs::msg::String>(name, conf, params)
{}
static BT::PortsList providedPorts()
{
return {};
}
NodeStatus onTick(const std::shared_ptr<std_msgs::msg::String>& last_msg) override
{
if(last_msg) // empty if no new message received, since the last tick
{
RCLCPP_INFO(logger(), "[%s] new message: %s", name().c_str(),
last_msg->data.c_str());
}
return NodeStatus::SUCCESS;
}
};
// Simple tree, used to execute once each action.
static const char* xml_text = R"(
<root BTCPP_format="4">
<BehaviorTree>
<Sequence>
<ReceiveString name="A"/>
<ReceiveString name="B"/>
<ReceiveString name="C"/>
</Sequence>
</BehaviorTree>
</root>
)";
int main(int argc, char** argv)
{
rclcpp::init(argc, argv);
auto nh = std::make_shared<rclcpp::Node>("subscriber_test");
BehaviorTreeFactory factory;
RosNodeParams params;
params.nh = nh;
params.default_port_value = "btcpp_string";
factory.registerNodeType<ReceiveString>("ReceiveString", params);
auto tree = factory.createTreeFromText(xml_text);
while(rclcpp::ok())
{
tree.tickWhileRunning();
}
return 0;
}
+68
View File
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1612295671">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1612295671" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1612295671" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.1612295671.1777191576" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.520406189" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.778880296" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder arguments="-f ${YUJIN_WORKSPACE}/build/yujin_ocs/${ProjName}/Makefile -j8" command="make" id="cdt.managedbuild.target.gnu.builder.base.1328555746" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.1304797274" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1243660247" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.991921373" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1000098092" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.7779663" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.176134653" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.370153349" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.494129810" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.1233806798" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1933798163" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="include/yocs_cmd_vel_mux"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="cmd_vel_mux.null.53888827" name="cmd_vel_mux"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1612295671;cdt.managedbuild.toolchain.gnu.base.1612295671.1777191576;cdt.managedbuild.tool.gnu.c.compiler.base.1000098092;cdt.managedbuild.tool.gnu.c.compiler.input.7779663">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1612295671;cdt.managedbuild.toolchain.gnu.base.1612295671.1777191576;cdt.managedbuild.tool.gnu.cpp.compiler.base.1243660247;cdt.managedbuild.tool.gnu.cpp.compiler.input.991921373">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Default">
<resource resourceType="PROJECT" workspacePath="/yocs_cmd_vel_mux"/>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
</cproject>
+4
View File
@@ -0,0 +1,4 @@
/bin
/build
/lib
**/__pycache__
+85
View File
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>yocs_cmd_vel_mux</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>?name?</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.append_environment</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildArguments</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildCommand</key>
<value>make</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
<value>clean</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.contents</key>
<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
<value>false</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableFullBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.stopOnError</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
<value>true</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?>
<pydev_project>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
</pydev_project>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project>
<configuration id="cdt.managedbuild.toolchain.gnu.base.1612295671" name="Default">
<extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuildCommandParser" id="org.eclipse.cdt.managedbuilder.core.GCCBuildCommandParser" keep-relative-paths="false" name="CDT GCC Build Output Parser" parameter="(.*gcc)|(.*[gc]\+\+)|(clang)" prefer-non-shared="true"/>
<provider-reference id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" ref="shared-provider"/>
<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
</extension>
</configuration>
</project>
+83
View File
@@ -0,0 +1,83 @@
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package yocs_cmd_vel_mux
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0.6.3 (2014-12-05)
------------------
0.6.2 (2014-11-30)
------------------
* yocs_cmd_vel_mux: fixes node handle for output pub
to keep backwards compatibility
* adds a little launcher restructing for muxer and smoother
* Contributors: Marcus Liebhardt
0.6.0 (2014-07-08)
------------------
* updating package informations. remove email for authors. updating maintainer
* Contributors: Jihoon Lee
0.5.3 (2014-03-24)
------------------
* Added support for YAML-CPP 0.5+.
The new yaml-cpp API removes the "node >> outputvar;" operator, and
it has a new way of loading documents. There's no version hint in the
library's headers, so I'm getting the version number from pkg-config.
This part of the patch is a port of the ones created by @ktossell for
map_server and other packages.
The new yaml-cpp also does not have FindValue.
* Contributors: Scott K Logan
0.5.2 (2013-11-05)
------------------
0.5.1 (2013-10-14)
------------------
* Unify naming politics for binaries and plugins.
0.5.0 (2013-10-11)
------------------
* Renamed as yocs_cmd_vel_mux.
0.4.1 (2013-10-08)
------------------
0.4.0 (2013-08-29)
------------------
* Add bugtracker and repo info URLs.
* Changelogs at package level.
* License link fixed.
0.3.0 (2013-07-02)
------------------
0.2.3 (2013-04-15)
------------------
0.2.2 (2013-02-10)
------------------
0.2.1 (2013-02-08)
------------------
0.2.0 (2013-02-07)
------------------
* Catkinized.
0.1.3 (2013-01-08)
------------------
* More generous description.
0.1.2 (2013-01-02)
------------------
* Dynamically reconfigurable.
* Upgraded to new groovy plugin formats.
* Add reconfigure launcher and parameter file.
* Add a dynamic reconfigure script to accept a yaml filename.
0.1.1 (2012-12-21)
------------------
0.1.0 (2012-12-05)
------------------
* Initial version.
+68
View File
@@ -0,0 +1,68 @@
cmake_minimum_required(VERSION 3.5)
project(cmd_vel_mux)
# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 14)
endif()
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
find_package(ament_cmake_ros REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(rcl_interfaces REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclcpp_components REQUIRED)
find_package(rcpputils REQUIRED)
find_package(std_msgs REQUIRED)
include_directories(include)
# Nodelet library
add_library(${PROJECT_NAME} SHARED src/cmd_vel_mux.cpp)
ament_target_dependencies(${PROJECT_NAME}
geometry_msgs
rcl_interfaces
rclcpp
rclcpp_components
rcpputils
std_msgs
)
rclcpp_components_register_node(${PROJECT_NAME}
PLUGIN "cmd_vel_mux::CmdVelMux"
EXECUTABLE cmd_vel_mux_node)
install(TARGETS ${PROJECT_NAME}
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
)
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION include/${PROJECT_NAME}
)
install(DIRECTORY config launch
DESTINATION share/${PROJECT_NAME}
)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
ament_lint_auto_find_test_dependencies()
find_package(ros_testing REQUIRED)
add_ros_test(test/test_cmd_vel_mux.py
TARGET test_cmd_vel_mux
TIMEOUT 30
)
add_ros_test(test/test_cmd_vel_mux_updates.py
TARGET test_cmd_vel_mux_updates
TIMEOUT 30
)
endif()
ament_package()
+31
View File
@@ -0,0 +1,31 @@
# Software License Agreement (BSD License)
#
# Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Yujin Robot nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
+47
View File
@@ -0,0 +1,47 @@
# cmd_vel mux
## About
A ROS 2 package for selecting among a number of incoming geometry_msg/msg/Twist messages, choosing the highest
priority one to republish on the output topic. It will automatically dislodge streams that are lower
priority or that stop publishing for any reason. The stream currently in use is published on the
"active" topic.
## Published Topics
* `/active` (`std_msgs/msg/String`) - A latched topic. Publishes the "name" field of the currently active `geometry_msgs/msg/Twist` stream (see Parameters below), or "idle" if nothing is being a published.
* `/cmd_vel` (`geometry_msgs/msg/Twist`) - The current `geometry_msgs/msg/Twist` message. The values from the current highest-priority `geometry_msgs/msg/Twist` are republished here without change.
## Subscribed Topics
* `/any` (`geometry_msgs/msg/Twist`) - For each named input (see Parameters below), a topic of type `geometry_msgs/msg/Twist` is subscribed to based on the `topic` parameter. The data from the highest-priority of these inputs is republished on the output `/cmd_vel`.
## Parameters
The cmd_vel_mux node uses a dictionary to hold the subscribers, with `name` being the key of each element:
* `name` (string) - The "name" of each of the input `geometry_msgs/msg/Twist` topics. This is what will be published on the `active` topic when the currently active publisher changes.
* `topic` (string) - The "topic" corresponding to each of the input `geometry_msgs/msg/Twist` topics. This is what will be subscribed to.
* `timeout` (double) - The "timeout" of each of the input `geometry_msgs/msg/Twist` topics. If no data is received on the input topic for this amount of time, the input will be automatically disabled.
* `priority` (integer) - The "priority" of each of the input `geometry_msgs/msg/Twist` topics. The higher the number, the higher the priority. Higher priority topics will dislodge lower priority topics and start publishing to the output topic automatically.
* `short_desc` (string) - The "short description" of each of the input `geometry_msgs/msg/Twist` topics. This is informational only.
See config/cmd_vel_mux_params.yaml for an example of how to set these up.
## Changing values
The dictionary translates to parameters in the form of `subscribers.` + name + `topic/timeout/priority/short_desc`.
It can be changed on the fly using `ros2 param set` command, followed with the parameter in the form mentioned above and the value.
## Adding subscriber
To add a new subscriber, call the service `/cmd_vel_mux/set_parameters_atomically` with a `rcl_interfaces/srv/SetParametersAtomically` message with a parameters value equal to an array of 4 `rcl_interfaces/msg/Parameter` messages, containing the new subscriber topic, timeout, priority and short_desc. All 4 need to be present for a new subscriber to be added.
**Ex.1** for testing:
```
ros2 service call /cmd_vel_mux/set_parameters_atomically rcl_interfaces/srv/SetParametersAtomically "{parameters: [{name : subscribers.new_input.topic, value: {type: 4, string_value: /input/new_input}}, {name : subscribers.new_input.priority, value: {type: 2, integer_value: 20}}, {name : subscribers.new_input.timeout, value: {type: 3, double_value: 0.2}}, {name : subscribers.new_input.short_desc, value: {type: 4, string_value: 'test input'}}]}"
```
sets *new_input* subscriber listening at topic `/input/new_input`
## Deleting subscriber
To delete a subscriber, call the service `/cmd_vel_mux/set_parameters_atomically` with a `rcl_interfaces/srv/SetParametersAtomically` message with a parameters value equal to an array of 4 `rcl_interfaces/msg/Parameter` messages, containing the new subscriber topic,timeout,priority and short_desc with the `type` key inside the `rcl/parameter/ParameterValue` being set to 0 (PARAMETER_NOT_SET).
**Ex.2** for testing:
```
ros2 service call /cmd_vel_mux/set_parameters_atomically rcl_interfaces/srv/SetParametersAtomically "{parameters: [{name : subscribers.new_input.topic, value: {type: 0}}, {name : subscribers.new_input.priority, value: {type: 0}}, {name : subscribers.new_input.timeout, value: {type: 0}}, {name : subscribers.new_input.short_desc, value: {type: 0}}]}"
```
deletes *new_input* subscriber added at ex.1
@@ -0,0 +1,47 @@
# Created on: Feb 05, 2020
# Author: Jose Tomas Lorente
# Configuration for subscribers to cmd_vel sources. This file is provided just as an example.
# Typically automatic controllers, as ROS navigation stack should have the minimum priority
#
# Used with example.launch
#
# Individual subscriber configuration:
# name: Source name
# topic: The topic that provides cmd_vel messages
# timeout: Time in seconds without incoming messages to consider this topic inactive
# priority: Priority: an UNIQUE unsigned integer from 0 (lowest) to MAX_INT
# short_desc: Short description
cmd_vel_mux:
ros__parameters:
subscribers:
default_input:
topic: "input/default"
timeout: 0.1
priority: 0
short_desc: "The default cmd_vel, controllers unaware that we are multiplexing cmd_vel should come here"
navigation_stack:
topic: "input/navigation"
timeout: 0.5
priority: 1
short_desc: "Navigation stack controller"
navigation_stack_controller:
topic: "input/joystick"
timeout: 0.1
priority: 10
short_desc: "Navigation stack remote control"
remote_control:
topic: "input/remote"
timeout: 0.1
priority: 9
short_desc: "Remote control"
web_application:
topic: "input/webapp"
timeout: 0.3
priority: 8
short_desc: "Web application"
keyboard_operation:
topic: "input/keyop"
timeout: 0.1
priority: 7
short_desc: "Keyboard operation"
@@ -0,0 +1,152 @@
// Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Yujin Robot nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef CMD_VEL_MUX__CMD_VEL_MUX_HPP_
#define CMD_VEL_MUX__CMD_VEL_MUX_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "geometry_msgs/msg/twist.hpp"
#include "rcl_interfaces/msg/set_parameters_result.hpp"
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace cmd_vel_mux
{
/*****************************************************************************
** CmdVelMux
*****************************************************************************/
struct ParameterValues
{
std::string topic; /**< The name of the topic */
double timeout{-1.0}; /**< Timer's timeout, in seconds */
int64_t priority{-1}; /**< UNIQUE integer from 0 (lowest priority) to MAX_INT */
std::string short_desc; /**< Short description */
};
bool operator==(const ParameterValues & parameters1, const ParameterValues & parameters2)
{
if (parameters1.topic != parameters2.topic) {
return false;
} else if (parameters1.timeout != parameters2.timeout) {
return false;
} else if (parameters1.priority != parameters2.priority) {
return false;
} else if (parameters1.short_desc != parameters2.short_desc) {
return false;
}
return true;
}
class CmdVelMux final : public rclcpp::Node
{
public:
explicit CmdVelMux(rclcpp::NodeOptions options);
~CmdVelMux() override = default;
CmdVelMux(CmdVelMux && c) = delete;
CmdVelMux & operator=(CmdVelMux && c) = delete;
CmdVelMux(const CmdVelMux & c) = delete;
CmdVelMux & operator=(const CmdVelMux & c) = delete;
private:
/// ID for "nobody" active input
static const char * const VACANT;
/// Multiplexed command velocity topic
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr output_topic_pub_;
/// Currently allowed cmd_vel subscriber
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr active_subscriber_pub_;
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr param_cb_;
std::string allowed_;
void timerCallback(const std::string & key);
void cmdVelCallback(
const std::shared_ptr<geometry_msgs::msg::Twist> msg,
const std::string & key);
rcl_interfaces::msg::SetParametersResult parameterUpdate(
const std::vector<rclcpp::Parameter> & update_parameters);
/*********************
** Private Classes
**********************/
/**
* Inner class describing an individual subscriber to a cmd_vel topic
*/
struct CmdVelSub final
{
/// Descriptive name; must be unique to this subscriber
std::string name_;
ParameterValues values_;
/// The subscriber itself
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr sub_;
/// No incoming messages timeout
rclcpp::TimerBase::SharedPtr timer_;
};
bool addInputToParameterMap(
std::map<std::string, ParameterValues> & parsed_parameters,
const std::string & input_name, const std::string & parameter_name,
const rclcpp::Parameter & parameter_value);
bool parametersAreValid(
const std::map<std::string, ParameterValues> & parameters) const;
void configureFromParameters(
const std::map<std::string, ParameterValues> & parameters);
std::map<std::string, ParameterValues> parseFromParametersMap(
const std::map<std::string,
rclcpp::Parameter> & parameters);
std::map<std::string, std::shared_ptr<CmdVelSub>> map_;
};
} // namespace cmd_vel_mux
#endif // CMD_VEL_MUX__CMD_VEL_MUX_HPP_
@@ -0,0 +1,71 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of {copyright_holder} nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Launch the cmd_vel_mux node composed with default configuration."""
import os
import ament_index_python.packages
from launch import LaunchDescription
from launch_ros.actions import ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
import yaml
def generate_launch_description():
share_dir = ament_index_python.packages.get_package_share_directory('cmd_vel_mux')
# Passing parameters to a composed node must be done via a dictionary of
# key -> value pairs. Here we read in the data from the configuration file
# and create a dictionary of it that the ComposableNode will accept.
params_file = os.path.join(share_dir, 'config', 'cmd_vel_mux_params.yaml')
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['cmd_vel_mux']['ros__parameters']
container = ComposableNodeContainer(
name='cmd_vel_mux_container',
namespace='',
package='rclcpp_components',
executable='component_container',
composable_node_descriptions=[
ComposableNode(
package='cmd_vel_mux',
plugin='cmd_vel_mux::CmdVelMux',
name='cmd_vel_mux',
parameters=[params]
),
],
output='both',
)
return LaunchDescription([container])
@@ -0,0 +1,63 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of {copyright_holder} nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
"""Launch the cmd_vel_mux node with default configuration."""
import os
import ament_index_python.packages
import launch
import launch_ros.actions
import yaml
def generate_launch_description():
share_dir = ament_index_python.packages.get_package_share_directory('cmd_vel_mux')
# There are two different ways to pass parameters to a non-composed node;
# either by specifying the path to the file containing the parameters, or by
# passing a dictionary containing the key -> value pairs of the parameters.
# When starting a *composed* node on the other hand, only the dictionary
# style is supported. To keep the code between the non-composed and
# composed launch file similar, we use that style here as well.
params_file = os.path.join(share_dir, 'config', 'cmd_vel_mux_params.yaml')
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['cmd_vel_mux']['ros__parameters']
cmd_vel_mux_node = launch_ros.actions.Node(
package='cmd_vel_mux',
executable='cmd_vel_mux_node',
output='both',
parameters=[params]
)
return launch.LaunchDescription([cmd_vel_mux_node])
+50
View File
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="2">
<name>cmd_vel_mux</name>
<version>0.12.1</version>
<description>
A multiplexer for command velocity inputs. Arbitrates incoming cmd_vel messages from several topics,
allowing one topic at a time to command the robot, based on priorities. It also deallocates current
allowed topic if no messages are received after a configured timeout. All topics, together with their
priority and timeout are configured through a YAML file, that can be reload at runtime.
</description>
<maintainer email="clalancette@openrobotics.org">Chris Lalancette</maintainer>
<license>BSD</license>
<url type="website">https://github.com/kobuki-base/cmd_vel_mux</url>
<url type="repository">https://github.com/kobuki-base/cmd_vel_mux</url>
<url type="bugtracker">https://github.com/kobuki-base/cmd_vel_mux/issues</url>
<author>Jorge Santos Simon</author>
<author email="jihoonl@yujinrobot.com">Jihoon Lee</author>
<buildtool_depend>ament_cmake_ros</buildtool_depend>
<build_depend>geometry_msgs</build_depend>
<build_depend>rcl_interfaces</build_depend>
<build_depend>rclcpp</build_depend>
<build_depend>rclcpp_components</build_depend>
<build_depend>rcpputils</build_depend>
<build_depend>std_msgs</build_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>rcl_interfaces</exec_depend>
<exec_depend>rclcpp</exec_depend>
<exec_depend>rclcpp_components</exec_depend>
<exec_depend>rcpputils</exec_depend>
<exec_depend>std_msgs</exec_depend>
<!-- <test_depend>ament_cmake_copyright</test_depend> -->
<test_depend>ament_cmake_cppcheck</test_depend>
<test_depend>ament_cmake_cpplint</test_depend>
<test_depend>ament_cmake_flake8</test_depend>
<test_depend>ament_cmake_lint_cmake</test_depend>
<test_depend>ament_cmake_pep257</test_depend>
<test_depend>ament_cmake_uncrustify</test_depend>
<test_depend>ament_cmake_xmllint</test_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ros_testing</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+429
View File
@@ -0,0 +1,429 @@
// Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Yujin Robot nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
/*****************************************************************************
** Includes
*****************************************************************************/
#include <chrono>
#include <cinttypes>
#include <fstream>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "cmd_vel_mux/cmd_vel_mux.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "rcl_interfaces/msg/set_parameters_result.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "rcpputils/split.hpp"
#include "std_msgs/msg/string.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace cmd_vel_mux
{
/*****************************************************************************
** Implementation
*****************************************************************************/
const char * const CmdVelMux::VACANT = "empty";
CmdVelMux::CmdVelMux(rclcpp::NodeOptions options)
: rclcpp::Node("cmd_vel_mux", options.allow_undeclared_parameters(
true).automatically_declare_parameters_from_overrides(true)), allowed_(VACANT)
{
std::map<std::string, rclcpp::Parameter> parameters;
// Check if there are loaded parameters from config file besides sim_time_used
if (!get_parameters("subscribers", parameters) || parameters.size() < 1) {
RCLCPP_WARN(get_logger(), "No subscribers configured!");
} else {
std::map<std::string, ParameterValues> parsed_parameters = parseFromParametersMap(parameters);
if (parsed_parameters.empty()) {
// We ran into some kind of error while configuring, quit
throw std::runtime_error("Invalid parameters");
}
if (!parametersAreValid(parsed_parameters)) {
throw std::runtime_error("Incomplete parameters");
}
configureFromParameters(parsed_parameters);
}
param_cb_ =
add_on_set_parameters_callback(
std::bind(&CmdVelMux::parameterUpdate, this, std::placeholders::_1));
output_topic_pub_ = this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 10);
RCLCPP_DEBUG(get_logger(), "CmdVelMux : subscribe to output topic 'cmd_vel'");
active_subscriber_pub_ = this->create_publisher<std_msgs::msg::String>(
"active", rclcpp::QoS(1).transient_local()); // latched topic
// Notify the world that right now nobody is publishing on cmd_vel yet
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = "idle";
active_subscriber_pub_->publish(std::move(active_msg));
RCLCPP_DEBUG(get_logger(), "CmdVelMux : successfully initialized");
}
bool CmdVelMux::parametersAreValid(const std::map<std::string, ParameterValues> & parameters) const
{
std::set<int64_t> used_priorities;
for (const std::pair<const std::string, ParameterValues> & parameter : parameters) {
if (parameter.second.topic.empty()) {
RCLCPP_WARN(get_logger(), "Empty topic for '%s'", parameter.first.c_str());
return false;
}
if (parameter.second.timeout < 0.0) {
RCLCPP_WARN(get_logger(), "Missing timeout for '%s', ignoring", parameter.first.c_str());
return false;
}
if (parameter.second.priority < 0) {
RCLCPP_WARN(get_logger(), "Missing priority for '%s', ignoring", parameter.first.c_str());
return false;
}
if (parameter.second.short_desc.empty()) {
RCLCPP_WARN(get_logger(), "Empty short_desc for '%s', ignoring", parameter.first.c_str());
return false;
}
if (used_priorities.count(parameter.second.priority) != 0) {
RCLCPP_WARN(get_logger(), "Cannot have duplicate priorities, ignoring");
return false;
}
used_priorities.insert(parameter.second.priority);
}
return true;
}
void CmdVelMux::configureFromParameters(const std::map<std::string, ParameterValues> & parameters)
{
std::map<std::string, std::shared_ptr<CmdVelSub>> new_map;
for (const std::pair<const std::string, ParameterValues> & parameter : parameters) {
const std::string & key = parameter.first;
const ParameterValues & parameter_values = parameter.second;
// Check if parameter subscriber has all its necessary values
if (map_.count(key) != 0) {
// For names already in the subscribers map, retain current
// object so we don't re-subscribe to the topic
new_map[key] = map_[key];
} else {
new_map[key] = std::make_shared<CmdVelSub>();
}
// update existing or new object with the new configuration
new_map[key]->name_ = key;
new_map[key]->values_.priority = parameter_values.priority;
new_map[key]->values_.short_desc = parameter_values.short_desc;
if (parameter_values.topic != new_map[key]->values_.topic) {
// Shutdown the topic if the name has changed so it gets recreated
// on configuration reload. In the case of new subscribers, topic
// is empty and shutdown has just no effect
new_map[key]->values_.topic = parameter_values.topic;
new_map[key]->sub_ = nullptr;
}
if (parameter_values.timeout != new_map[key]->values_.timeout) {
// Change timer period if the timeout changed
new_map[key]->values_.timeout = parameter_values.timeout;
new_map[key]->timer_ = nullptr;
}
}
// Take down the deleted subscriber if it was the one being used as source
if (allowed_ != VACANT && new_map.count(allowed_) == 0) {
allowed_ = VACANT;
// ...notify the world that nobody is publishing on cmd_vel; its vacant
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = "idle";
active_subscriber_pub_->publish(std::move(active_msg));
}
map_ = new_map;
// (Re)create subscribers whose topic is invalid: new ones and those with changed names
for (std::pair<const std::string, std::shared_ptr<CmdVelSub>> & m : map_) {
const std::string & key = m.first;
const std::shared_ptr<CmdVelSub> & values = m.second;
if (!values->sub_) {
values->sub_ = this->create_subscription<geometry_msgs::msg::Twist>(
values->values_.topic, 10,
[this, key](const geometry_msgs::msg::Twist::SharedPtr msg) {cmdVelCallback(msg, key);});
RCLCPP_DEBUG(
get_logger(), "CmdVelMux : subscribed to '%s' on topic '%s'. pr: %" PRId64 ", to: %.2f",
values->name_.c_str(), values->values_.topic.c_str(),
values->values_.priority, values->values_.timeout);
} else {
RCLCPP_DEBUG(
get_logger(), "CmdVelMux : no need to re-subscribe to input topic '%s'",
values->values_.topic.c_str());
}
if (!values->timer_) {
// Create (stopped by now) a one-shot timer for every subscriber, if it doesn't exist yet
values->timer_ = this->create_wall_timer(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::duration<double>(
values->values_.timeout)), [this, key]() {timerCallback(key);});
}
}
RCLCPP_INFO(get_logger(), "CmdVelMux : (re)configured");
}
bool CmdVelMux::addInputToParameterMap(
std::map<std::string, ParameterValues> & parsed_parameters,
const std::string & input_name,
const std::string & parameter_name,
const rclcpp::Parameter & parameter_value)
{
if (parameter_name == "topic") {
std::string topic;
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
topic.clear();
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_STRING) {
topic = parameter_value.as_string();
} else {
RCLCPP_WARN(get_logger(), "topic must be a string; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].topic = topic;
} else if (parameter_name == "timeout") {
double timeout{-1.0};
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
timeout = -1.0;
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_DOUBLE) {
timeout = parameter_value.as_double();
} else {
RCLCPP_WARN(get_logger(), "timeout must be a double; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].timeout = timeout;
} else if (parameter_name == "priority") {
int64_t priority{-1};
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
priority = -1;
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_INTEGER) {
priority = parameter_value.as_int();
if (priority < 0 || priority > std::numeric_limits<uint32_t>::max()) {
RCLCPP_WARN(get_logger(), "Priority out of range, must be between 0 and MAX_UINT32");
return false;
}
} else {
RCLCPP_WARN(get_logger(), "priority must be an integer; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].priority = priority;
} else if (parameter_name == "short_desc") {
std::string short_desc;
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
short_desc.clear();
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_STRING) {
short_desc = parameter_value.as_string();
} else {
RCLCPP_WARN(get_logger(), "short_desc must be a string; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].short_desc = short_desc;
} else {
RCLCPP_WARN(get_logger(), "Invalid input variable '%s'; ignored", parameter_name.c_str());
return false;
}
return true;
}
std::map<std::string, ParameterValues> CmdVelMux::parseFromParametersMap(
const std::map<std::string,
rclcpp::Parameter> & parameters)
{
std::map<std::string, ParameterValues> parsed_parameters;
// Iterate over all parameters and parse their content
for (const std::pair<const std::string, rclcpp::Parameter> & parameter : parameters) {
std::vector<std::string> splits = rcpputils::split(parameter.first, '.');
if (splits.size() != 2) {
RCLCPP_WARN(
get_logger(), "Invalid or unknown parameter '%s', ignoring", parameter.first.c_str());
continue;
}
const std::string & input_name = splits[0];
const std::string & parameter_name = splits[1];
const rclcpp::Parameter & parameter_value = parameter.second;
if (!addInputToParameterMap(parsed_parameters, input_name, parameter_name, parameter_value)) {
parsed_parameters.clear();
break;
}
}
return parsed_parameters;
}
void CmdVelMux::cmdVelCallback(
const std::shared_ptr<geometry_msgs::msg::Twist> msg,
const std::string & key)
{
// if subscriber was deleted or the one being called right now just ignore
if (map_.count(key) == 0) {
return;
}
// Reset timer for this source
map_[key]->timer_->reset();
// Give permit to publish to this source if it's the only active or is
// already allowed or has higher priority that the currently allowed
if ((allowed_ == VACANT) ||
(allowed_ == key) ||
(map_[key]->values_.priority > map_[allowed_]->values_.priority))
{
if (allowed_ != key) {
allowed_ = key;
// Notify the world that a new cmd_vel source took the control
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = map_[key]->name_;
active_subscriber_pub_->publish(std::move(active_msg));
}
output_topic_pub_->publish(*msg);
}
}
// The per-topic timerCallback is continually reset as cmd_vel messages are
// received. Thus, if it ever expires, then the topic hasn't published within
// the specified timeout period and it should be removed.
void CmdVelMux::timerCallback(const std::string & key)
{
if (allowed_ == key) {
// No cmd_vel messages timeout happened to currently active source, so...
allowed_ = VACANT;
// ...notify the world that nobody is publishing on cmd_vel; its vacant
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = "idle";
active_subscriber_pub_->publish(std::move(active_msg));
}
}
rcl_interfaces::msg::SetParametersResult CmdVelMux::parameterUpdate(
const std::vector<rclcpp::Parameter> & update_parameters)
{
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
std::map<std::string, rclcpp::Parameter> old_parameters;
if (!get_parameters("subscribers", old_parameters) || old_parameters.size() <= 1) {
result.successful = false;
result.reason = "no parameters loaded";
return result;
}
std::map<std::string, ParameterValues> parameters = parseFromParametersMap(old_parameters);
// And then merge them
for (const rclcpp::Parameter & parameter : update_parameters) {
std::vector<std::string> splits = rcpputils::split(parameter.get_name(), '.');
if (splits.size() != 3) {
RCLCPP_WARN(
get_logger(), "Invalid or unknown parameter '%s', ignoring", parameter.get_name().c_str());
result.successful = false;
result.reason = "Invalid or unknown parameter";
break;
}
if (splits[0] != "subscribers") {
RCLCPP_WARN(
get_logger(), "Unknown parameter prefix '%s', ignoring", parameter.get_name().c_str());
result.successful = false;
result.reason = "Unknown parameter prefix";
break;
}
const std::string & input_name = splits[1];
const std::string & parameter_name = splits[2];
if (!addInputToParameterMap(parameters, input_name, parameter_name, parameter)) {
result.successful = false;
result.reason = "Invalid parameter";
break;
}
}
if (result.successful) {
if (parametersAreValid(parameters)) {
configureFromParameters(parameters);
} else {
result.successful = false;
result.reason = "Incomplete parameters";
}
}
return result;
}
} // namespace cmd_vel_mux
RCLCPP_COMPONENTS_REGISTER_NODE(cmd_vel_mux::CmdVelMux)
+217
View File
@@ -0,0 +1,217 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of {copyright_holder} nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import collections.abc
import contextlib
import unittest
import geometry_msgs.msg
import launch
import launch.actions
import launch.substitutions
import launch_ros.actions
import launch_ros.substitutions
import launch_testing.actions
import launch_testing.tools
import rclpy
import rclpy.qos
import std_msgs.msg
def generate_test_description():
path_to_cmd_vel_mux_params = launch.substitutions.PathJoinSubstitution([
launch_ros.substitutions.FindPackageShare(package='cmd_vel_mux'),
'config',
'cmd_vel_mux_params.yaml'
])
return launch.LaunchDescription([
launch_ros.actions.Node(
package='cmd_vel_mux',
executable='cmd_vel_mux_node',
parameters=[path_to_cmd_vel_mux_params],
output='screen'
),
launch_testing.actions.ReadyToTest()
])
latching_qos_profile = rclpy.qos.QoSProfile(depth=1)
latching_qos_profile.reliability = rclpy.qos.QoSReliabilityPolicy.RELIABLE
latching_qos_profile.durability = rclpy.qos.QoSDurabilityPolicy.TRANSIENT_LOCAL
class TestCmdVelMux(unittest.TestCase):
@classmethod
def setUpClass(
cls,
launch_service,
proc_info,
proc_output
):
rclpy.init()
cls._node = rclpy.create_node(
'cmd_vel_mux_testing_node', start_parameter_services=False
)
@classmethod
def tearDownClass(cls):
cls._node.destroy_node()
rclpy.shutdown()
@contextlib.contextmanager
def pub(
self,
message,
*,
topic,
rate,
qos_profile=None
):
if qos_profile is None:
qos_profile = rclpy.qos.qos_profile_system_default
publisher = self._node.create_publisher(type(message), topic, qos_profile=qos_profile)
timer = self._node.create_timer(1.0 / rate, lambda *args: publisher.publish(message))
try:
yield
finally:
self._node.destroy_timer(timer)
self._node.destroy_publisher(publisher)
def expect(
self,
expected_sequence,
*,
topic,
message_type=None,
timeout=None,
qos_profile=None
):
future = rclpy.task.Future()
if not isinstance(expected_sequence, collections.abc.Sequence):
if expected_sequence is not None:
expected_sequence = [expected_sequence]
if expected_sequence is not None and len(expected_sequence) > 0:
if message_type is None:
message_type = type(expected_sequence[0])
sequence_types = tuple(type(message) for message in expected_sequence)
if not all(type_ == message_type for type_ in sequence_types):
raise ValueError(
f'inconsistent message types: found {sequence_types}'
f' but expected {message_type} only'
)
def _callback(message):
nonlocal expected_sequence
if expected_sequence[0] == message:
expected_sequence = expected_sequence[1:]
if len(expected_sequence) == 0:
future.set_result(None)
else:
if message_type is None:
raise ValueError('cannot infer message type')
def _callback(message):
future.set_result(None)
if qos_profile is None:
qos_profile = rclpy.qos.qos_profile_system_default
subscription = self._node.create_subscription(
message_type, topic, _callback, qos_profile=qos_profile
)
try:
rclpy.spin_until_future_complete(self._node, future, timeout_sec=timeout)
return ((expected_sequence is None) ^ future.done())
finally:
self._node.destroy_subscription(subscription)
def test_idle_mux(self):
expected_active_input = std_msgs.msg.String()
expected_active_input.data = 'idle'
self.assertTrue(self.expect(
expected_active_input,
topic='active', timeout=2,
qos_profile=latching_qos_profile
))
self.assertTrue(self.expect(
None, topic='cmd_vel', message_type=geometry_msgs.msg.Twist, timeout=2
))
def test_mux_with_single_input(self):
default_twist = geometry_msgs.msg.Twist()
default_twist.linear.x = 1.0
with self.pub(default_twist, topic='input/default', rate=20):
expected_active_input = std_msgs.msg.String()
expected_active_input.data = 'default_input'
self.assertTrue(self.expect(
expected_active_input,
topic='active', timeout=2,
qos_profile=latching_qos_profile
))
self.assertTrue(self.expect(default_twist, topic='cmd_vel', timeout=2))
def test_mux_priority_override(self):
default_twist = geometry_msgs.msg.Twist()
default_twist.linear.x = 1.0
joystick_twist = geometry_msgs.msg.Twist()
joystick_twist.angular.z = 1.0
with self.pub(
default_twist, topic='input/default', rate=20
), self.pub(
joystick_twist, topic='input/joystick', rate=20
):
expected_active_input = std_msgs.msg.String()
expected_active_input.data = 'navigation_stack_controller'
self.assertTrue(self.expect(
expected_active_input,
topic='active', timeout=2,
qos_profile=latching_qos_profile
))
self.assertTrue(self.expect(joystick_twist, topic='cmd_vel', timeout=2))
def test_mux_timeout(self):
no_twist = geometry_msgs.msg.Twist()
with self.pub(no_twist, topic='input/default', rate=8):
idle_input = std_msgs.msg.String()
idle_input.data = 'idle'
default_input = std_msgs.msg.String()
default_input.data = 'default_input'
self.assertTrue(self.expect(
[idle_input, default_input, idle_input],
topic='active', timeout=5,
qos_profile=latching_qos_profile
))
@@ -0,0 +1,249 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of {copyright_holder} nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import collections
import contextlib
import functools
import re
import unittest
import launch
import launch.actions
import launch.substitutions
import launch_ros.actions
import launch_ros.substitutions
import launch_testing.actions
import launch_testing.markers
import launch_testing.tools
import rcl_interfaces.srv
import rclpy
def flatten(d, prefix=None):
assert isinstance(d, collections.abc.Mapping)
flat_d = {}
for k, v in d.items():
if prefix is not None:
k = prefix + '.' + k
if isinstance(v, collections.abc.Mapping):
flat_d.update(flatten(v, prefix=k))
else:
flat_d[k] = v
return flat_d
@launch_testing.markers.keep_alive
def generate_test_description():
return launch.LaunchDescription([
launch_testing.actions.ReadyToTest()
])
class TestCmdVelMux(unittest.TestCase):
@classmethod
def setUpClass(
cls,
launch_service,
proc_info,
proc_output
):
@contextlib.contextmanager
def launch_cmd_vel_mux_node(self, *, parameters):
cmd_vel_mux_node_action = launch_ros.actions.Node(
package='cmd_vel_mux',
executable='cmd_vel_mux_node',
name='cmd_vel_mux',
parameters=[parameters],
output='screen'
)
with launch_testing.tools.launch_process(
launch_service, cmd_vel_mux_node_action, proc_info, proc_output
) as node_process:
yield node_process
cls.launch_cmd_vel_mux_node = launch_cmd_vel_mux_node
rclpy.init()
cls._node = rclpy.create_node(
'cmd_vel_mux_testing_node', start_parameter_services=False
)
cls._cmd_vel_mux_set_parameters_client = cls._node.create_client(
rcl_interfaces.srv.SetParametersAtomically,
'/cmd_vel_mux/set_parameters_atomically'
)
def update_cmd_vel_mux_params(self, *, parameters):
self.assertTrue(self._cmd_vel_mux_set_parameters_client.wait_for_service(timeout_sec=5))
request = rcl_interfaces.srv.SetParametersAtomically.Request()
print(flatten(parameters))
request.parameters = [
rclpy.Parameter(name=name, value=value).to_parameter_msg()
for name, value in flatten(parameters).items()
]
future = self._cmd_vel_mux_set_parameters_client.call_async(request)
rclpy.spin_until_future_complete(self._node, future, timeout_sec=5.0)
self.assertTrue(future.done())
response = future.result()
return response.result.successful, response.result.reason
@classmethod
def tearDownClass(cls):
cls._node.destroy_client(cls._cmd_vel_mux_set_parameters_client)
cls._node.destroy_node()
rclpy.shutdown()
def test_no_params(self):
with self.launch_cmd_vel_mux_node(parameters={}) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*WARN.*No subscribers configured!')
], strict=False
), timeout=2))
def test_invalid_subscriber(self):
with self.launch_cmd_vel_mux_node(
parameters={
'subscribers': {
'some_invalid_subscriber': ''
}
}
) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*std::runtime_error.*'),
re.compile(r'.*Invalid parameters.*')
], strict=False
), timeout=2))
self.assertTrue(node_process.wait_for_shutdown(timeout=2))
self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK)
def test_invalid_subscriber_params(self):
with self.launch_cmd_vel_mux_node(
parameters={
'subscribers': {
'some_subscriber': {
'topic': 0
}
}
}
) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*std::runtime_error.*'),
re.compile(r'.*Invalid parameters.*')
], strict=False
), timeout=2))
self.assertTrue(node_process.wait_for_shutdown(timeout=2))
self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK)
def test_incomplete_params(self):
with self.launch_cmd_vel_mux_node(
parameters={
'subscribers': {
'some_subscriber': {
'topic': 'some_topic',
'priority': 0,
'short_desc': ''
}
}
}
) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*std::runtime_error.*'),
re.compile(r'.*Incomplete parameters.*'),
], strict=False
), timeout=2))
self.assertTrue(node_process.wait_for_shutdown(timeout=2))
self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK)
def test_params_update(self):
with self.launch_cmd_vel_mux_node(parameters={
'subscribers': {
'some_subscriber': {
'topic': 'some_topic',
'priority': 0,
'timeout': 1.0,
'short_desc': 'A dummy description'
}
}
}) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*CmdVelMux : \(re\)configured.*'),
], strict=False
), timeout=2))
ok, reason = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'some_invalid_subscriber': ''
}
})
self.assertFalse(ok)
self.assertEqual(reason, 'Invalid or unknown parameter')
ok, reason = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'another_subscriber': {
'topic': 'another_topic',
'priority': 0,
'timeout': 0.1,
}
}
})
self.assertFalse(ok)
self.assertEqual(reason, 'Incomplete parameters')
ok, reason = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'another_subscriber': {
'topic': 0,
}
}
})
self.assertFalse(ok)
self.assertEqual(reason, 'Invalid parameter')
ok, _ = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'another_subscriber': {
'topic': 'another_topic',
'priority': 1,
'timeout': 0.1,
'short_desc': 'Another dummy description'
}
}
})
self.assertTrue(ok)
+16
View File
@@ -0,0 +1,16 @@
# Compiled Object files
*.slo
*.lo
*.o
# Eclipse
.settings
# Compiled Dynamic libraries
*.so
*.dylib
# Compiled Static libraries
*.lai
*.la
*.a
+32
View File
@@ -0,0 +1,32 @@
# Software License Agreement (BSD License)
#
# Copyright (c) 2022 Daniel Stonier
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
+5
View File
@@ -0,0 +1,5 @@
ecl_core
========
A set of tools and interfaces extending the capabilities of c++ to provide a lightweight,
consistent interface with a focus for control programming.
+338
View File
@@ -0,0 +1,338 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1069310076">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1069310076" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="command_line" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1069310076" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.1069310076.97404362" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.711160990" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.506759735" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder buildPath="${workspace_loc:${ProjName}}/../../../build/${ProjName}" id="cdt.managedbuild.target.gnu.builder.base.1386481711" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.1422431335" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.143374507" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1927254483" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1076063647" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1749256354" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1518170669" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.2122196183" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1000782804" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.977298002" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.954666529" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="include/ecl"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="command_line.null.646541467" name="command_line"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1069310076;cdt.managedbuild.toolchain.gnu.base.1069310076.97404362;cdt.managedbuild.tool.gnu.c.compiler.base.1076063647;cdt.managedbuild.tool.gnu.c.compiler.input.1749256354">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1069310076;cdt.managedbuild.toolchain.gnu.base.1069310076.97404362;cdt.managedbuild.tool.gnu.cpp.compiler.base.143374507;cdt.managedbuild.tool.gnu.cpp.compiler.input.1927254483">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Default">
<resource resourceType="PROJECT" workspacePath="/ecl_command_line"/>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets">
<buildTargets>
<target name="clean" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>clean</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="all" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>all</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="test" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>test</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
</buildTargets>
</storageModule>
</cproject>
+78
View File
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ecl_command_line</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>?name?</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.append_environment</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildArguments</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildCommand</key>
<value>make</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
<value>clean</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.contents</key>
<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
<value>false</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableFullBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.stopOnError</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
<value>true</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,12 @@
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package ecl_command_line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0.60.8 (2014-02-10)
-------------------
0.60.7 (2014-02-03)
-------------------
0.60.6 (2014-01-29)
-------------------
@@ -0,0 +1,57 @@
##############################################################################
# Cmake
##############################################################################
cmake_minimum_required(VERSION 3.5)
project(ecl_command_line)
##############################################################################
# Ament
##############################################################################
find_package(ament_cmake_ros REQUIRED)
find_package(ecl_build REQUIRED)
##############################################################################
# Project Configuration
##############################################################################
ament_package_xml()
ecl_enable_cxx14_compiler()
ecl_enable_cxx_warnings()
##############################################################################
# Header Library Targets
##############################################################################
add_library(${PROJECT_NAME} INTERFACE)
target_include_directories(
${PROJECT_NAME}
INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
)
##############################################################################
# Sources
##############################################################################
add_subdirectory(include)
add_subdirectory(src)
##############################################################################
# Exports
##############################################################################
# Downstream CMake3 compatibility
ament_export_targets(${PROJECT_NAME})
# Downstream CMake2 compatibility
ament_export_include_directories(include)
ament_package()
@@ -0,0 +1,111 @@
/**
\mainpage
\htmlinclude manifest.html
\section packageSummary Package Summary
Provides a templatised c++ parser for handling command line arguments.
The templates provide a very flexible manner for handling any type
of input argument.
The code for the command line parser is a simple wrapper around another
template header library called <a href="http://tclap.sourceforge.net/">TCLAP</a>.
Since it is relatively small, its
bundled here in the command_line subdirectory and namespaced
in a convenient manner. Licensing terms (MIT) are included in the
command_line subdirectory (also included as an install target).
@subsection Alternatives
A more complicated, but more flexible alternative
(it allows argument parsing from both command line and configuration
file simultaneously) is the boost::program_options library.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit which
requires this library:
@code
#include <ecl/command_line.hpp>
// Interface classes
using ecl::CmdLine;
using ecl::ArgException
// Argument classes
using ecl::SwitchArg;
using ecl::ValueArg;
using ecl::MultiArg;
using ecl::UnlabeledValueArg;
using ecl::UnlabeledMultiArg; // there are more - see tclap docs
@endcode
Since it is a template header library, no linking is required if you are
only using these classes.
\section usage Usage
@subsection Initialisation
A single object is used to parse the command line. Initialise it with
a few default properties. These will be used to automatically
generate a --help argument.
@code
// Supply a program description, argument separator (optional) and version number (optional).
CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.");
// CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01");
@endcode
@subsection ArgumentsSection Adding Arguments
@code
// Add a boolean (flag, name, description, default)
SwitchArg debug("d","debug","Enable debugging.", false);
cmd.add(debug);
// Add an int (flag,name,description,compulsory flag,default value,help description of the type")
ValueArg<int> intArg("i","integer","An integer argument for testing.",false,5,"integer");
// Not a regular option (name,description,compulsory flag,default value,help description of the type")
UnlabeledValueArg<std::string> outputDirArg("output_dir","Output directory for rectified images.",true,"./rectified","string");
cmd.add(intArg);
@endcode
Valid argument types include
- @ref ecl::SwitchArg "SwitchArg" : simple boolean.
- @ref ecl::ValueArg "ValueArg" : expect some value on the command line.
- @ref ecl::MultiArg "MultiArg" : permit multiple values for an argument which get stored in a vector.
- @ref ecl::MultiSwitchArg "MultiSwitchArg" : as above, but for booleans, not often used so see TCLAP for more instructions.
- @ref ecl::UnlabeledValueArg "UnlabeledValueArg" : does not use a flag (like the arguments for copy), order is important!
- @ref ecl::UnlabeledMultiArg "UnlabeledMultiArg" : reads in all remaining unlabelled args (like rm file1.txt file2.txt etc.)
@subsection customArgumentsSection Custom Arguments
Custom ValueArg types can be used so long as they implement the >> operator.
@section extraHelp Further Help (TCLAP)
Most of tclap's doxygen is generated automatically inside the ecl. For more detailed
documentation, read the <a href="http://tclap.sourceforge.net/manual.html">manual</a> at
tclap's home page.
\section unitTests Unit Tests
- src/test/command_line.cpp
\section examples Examples
- src/examples/command_line.cpp
\section ChangeLog
- <b>May 09</b> : wrapper for the tclap headers written.
- <b>May 09</b> : initial import of the tclap headers.
@section Errata
Now it's in the ros, at some point in the future I will unwind this back to the original package since it no longer needs
to be embedded in the ecl.
*/
@@ -0,0 +1,22 @@
/**
* @namespace ecl::command_line
*
* @brief Command line parsing classes.
*
* Cross-platform collection of tools for command line parsing. It has been
* built as a wrapper around the TCLAP template library.
**/
/*
* @namespace ecl::command_line::MultiArgHelper
*
* @brief Collection of utilities and tools for multiple argument handling in tclap.
*
* Collection of utilities and tools for multiple argument handling in tclap.
*/
/*
* @namespace ecl::command_line::ValueArgHelper
*
* @brief Collection of utilities and tools for value argument handling in tclap.
*
* Collection of utilities and tools for value argument handling in tclap.
*/
@@ -0,0 +1,5 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(ecl)
@@ -0,0 +1,14 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(command_line)
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl)
@@ -0,0 +1,25 @@
/**
* @file /include/ecl/command_line.hpp
*
* @brief Parsing command line arguments.
*
* Uses a c++ library called TCLAP (MIT license) to provide command
* line parsing for the ECL.
*
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CMD_LINE_HPP_
#define ECL_CMD_LINE_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "command_line/cmd_line.hpp"
#endif /*ECL_CMD_LINE_HPP_*/
@@ -0,0 +1,7 @@
###############################################################################
# FILES
###############################################################################
FILE(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
INSTALL(FILES ${HEADERS} DESTINATION include/ecl/command_line)
@@ -0,0 +1,580 @@
/**
* @file /include/ecl/command_line/arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_ARGUMENT_H
#define TCLAP_ARGUMENT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include "arg_exception.hpp"
#include "visitor.hpp"
#include "cmd_line_interface.hpp"
namespace ecl {
/**
* @brief Virtual parent for all the different argument classes.
*
* A virtual base class that defines the essential data for all arguments.
* This class, or one of its existing children, must be subclassed to do
* anything.
*/
class Arg
{
private:
/**
* Indicates whether the rest of the arguments should be ignored.
*/
static bool& ignoreRestRef() { static bool ign = false; return ign; }
/**
* The delimiter that separates an argument flag/name from the
* value.
*/
static char& delimiterRef() { static char delim = ' '; return delim; }
protected:
/**
* The single char flag used to identify the argument.
* This value (preceded by a dash {-}), can be used to identify
* an argument on the command line. The _flag can be blank,
* in fact this is how unlabeled args work. Unlabeled args must
* override appropriate functions to get correct handling. Note
* that the _flag does NOT include the dash as part of the flag.
*/
std::string _flag;
/**
* A single work namd indentifying the argument.
* This value (preceded by two dashed {--}) can also be used
* to identify an argument on the command line. Note that the
* _name does NOT include the two dashes as part of the _name. The
* _name cannot be blank.
*/
std::string _name;
/**
* Description of the argument.
*/
std::string _description;
/**
* Indicating whether the argument is required.
*/
bool _required;
/**
* Label to be used in usage description. Normally set to
* "required", but can be changed when necessary.
*/
std::string _requireLabel;
/**
* Indicates whether a value is required for the argument.
* Note that the value may be required but the argument/value
* combination may not be, as specified by _required.
*/
bool _valueRequired;
/**
* Indicates whether the argument has been set.
* Indicates that a value on the command line has matched the
* name/flag of this argument and the values have been set accordingly.
*/
bool _alreadySet;
/**
* A pointer to a vistitor object.
* The visitor allows special handling to occur as soon as the
* argument is matched. This defaults to NULL and should not
* be used unless absolutely necessary.
*/
Visitor* _visitor;
/**
* Whether this argument can be ignored, if desired.
*/
bool _ignoreable;
/**
* Indicates that the arg was set as part of an XOR and not on the
* command line.
*/
bool _xorSet;
bool _acceptsMultipleValues;
/**
* Performs the special handling described by the Vistitor.
*/
void _checkWithVisitor() const;
/**
* Primary constructor. YOU (yes you) should NEVER construct an Arg
* directly, this is a base class that is extended by various children
* that are meant to be used. Use SwitchArg, ValueArg, MultiArg,
* UnlabeledValueArg, or UnlabeledMultiArg instead.
*
* \param flag - The flag identifying the argument.
* \param name - The name identifying the argument.
* \param desc - The description of the argument, used in the usage.
* \param req - Whether the argument is required.
* \param valreq - Whether the a value is required for the argument.
* \param v - The visitor checked by the argument. Defaults to NULL.
*/
Arg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
bool valreq,
Visitor* v = NULL );
public:
/**
* Destructor.
*/
virtual ~Arg();
/**
* Adds this to the specified list of Args.
* \param argList - The list to add this to.
*/
virtual void addToList( std::list<Arg*>& argList ) const;
/**
* Begin ignoring arguments since the "--" argument was specified.
*/
static void beginIgnoring() { ignoreRestRef() = true; }
/**
* Whether to ignore the rest.
*/
static bool ignoreRest() { return ignoreRestRef(); }
/**
* The delimiter that separates an argument flag/name from the
* value.
*/
static char delimiter() { return delimiterRef(); }
/**
* The char used as a place holder when SwitchArgs are combined.
* Currently set to '*', which shouldn't cause many problems since
* *'s are expanded by most shells on the command line.
*/
static char blankChar() { return '*'; }
/**
* The char that indicates the beginning of a flag. Currently '-'.
*/
static char flagStartChar() { return '-'; }
/**
* The sting that indicates the beginning of a flag. Currently "-".
* Should be identical to flagStartChar.
*/
static std::string flagStartString() { return "-"; }
/**
* The sting that indicates the beginning of a name. Currently "--".
* Should be flagStartChar twice.
*/
static std::string nameStartString() { return "--"; }
/**
* The name used to identify the ignore rest argument.
*/
static std::string ignoreNameString() { return "ignore_rest"; }
/**
* Sets the delimiter for all arguments.
* \param c - The character that delimits flags/names from values.
*/
static void setDelimiter( char c ) { delimiterRef() = c; }
/**
* Pure virtual method meant to handle the parsing and value assignment
* of the string on the command line.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. What is
* passed in from main.
*/
virtual bool processArg(int *i, std::vector<std::string>& args) = 0;
/**
* Operator ==.
* Equality operator. Must be virtual to handle unlabeled args.
* \param a - The Arg to be compared to this.
*/
virtual bool operator==(const Arg& a) const;
/**
* Returns the argument flag.
*/
const std::string& getFlag() const;
/**
* Returns the argument name.
*/
const std::string& getName() const;
/**
* Returns the argument description.
*/
std::string getDescription() const;
/**
* Indicates whether the argument is required.
*/
virtual bool isRequired() const;
/**
* Sets _required to true. This is used by the XorHandler.
* You really have no reason to ever use it.
*/
void forceRequired();
/**
* Sets the _alreadySet value to true. This is used by the XorHandler.
* You really have no reason to ever use it.
*/
void xorSet();
/**
* Indicates whether a value must be specified for argument.
*/
bool isValueRequired() const;
/**
* Indicates whether the argument has already been set. Only true
* if the arg has been matched on the command line.
*/
bool isSet() const;
/**
* Indicates whether the argument can be ignored, if desired.
*/
bool isIgnoreable() const;
/**
* A method that tests whether a string matches this argument.
* This is generally called by the processArg() method. This
* method could be re-implemented by a child to change how
* arguments are specified on the command line.
* \param s - The string to be compared to the flag/name to determine
* whether the arg matches.
*/
virtual bool argMatches( const std::string& s ) const;
/**
* Returns a simple string representation of the argument.
* Primarily for debugging.
*/
virtual std::string toString() const;
/**
* Returns a short ID for the usage.
* \param valueId - The value used in the id.
*/
virtual std::string shortID( const std::string& valueId = "val" ) const;
/**
* Returns a long ID for the usage.
* \param valueId - The value used in the id.
*/
virtual std::string longID( const std::string& valueId = "val" ) const;
/**
* Trims a value off of the flag.
* \param flag - The string from which the flag and value will be
* trimmed. Contains the flag once the value has been trimmed.
* \param value - Where the value trimmed from the string will
* be stored.
*/
virtual void trimFlag( std::string& flag, std::string& value ) const;
/**
* Checks whether a given string has blank chars, indicating that
* it is a combined SwitchArg. If so, return true, otherwise return
* false.
* \param s - string to be checked.
*/
bool _hasBlanks( const std::string& s ) const;
/**
* Sets the requireLabel. Used by XorHandler. You shouldn't ever
* use this.
* \param s - Set the requireLabel to this value.
*/
void setRequireLabel( const std::string& s );
virtual bool allowMore();
virtual bool acceptsMultipleValues();
};
/**
* Typedef of an Arg list iterator.
*/
typedef std::list<Arg*>::iterator ArgListIterator;
/**
* Typedef of an Arg vector iterator.
*/
typedef std::vector<Arg*>::iterator ArgVectorIterator;
/**
* Typedef of a Visitor list iterator.
*/
typedef std::list<Visitor*>::iterator VisitorListIterator;
//////////////////////////////////////////////////////////////////////
//BEGIN Arg.cpp
//////////////////////////////////////////////////////////////////////
inline Arg::Arg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
bool valreq,
Visitor* v) :
_flag(flag),
_name(name),
_description(desc),
_required(req),
_requireLabel("required"),
_valueRequired(valreq),
_alreadySet(false),
_visitor( v ),
_ignoreable(true),
_xorSet(false),
_acceptsMultipleValues(false)
{
if ( _flag.length() > 1 )
throw(SpecificationException(
"Argument flag can only be one character long", toString() ) );
if ( _name != ignoreNameString() &&
( _flag == Arg::flagStartString() ||
_flag == Arg::nameStartString() ||
_flag == " " ) )
throw(SpecificationException("Argument flag cannot be either '" +
Arg::flagStartString() + "' or '" +
Arg::nameStartString() + "' or a space.",
toString() ) );
if ( ( _name.find( Arg::flagStartString(), 0 ) != std::string::npos ) ||
( _name.find( Arg::nameStartString(), 0 ) != std::string::npos ) ||
( _name.find( " ", 0 ) != std::string::npos ) )
throw(SpecificationException("Argument name cannot contain either '" +
Arg::flagStartString() + "' or '" +
Arg::nameStartString() + "' or space.",
toString() ) );
}
inline Arg::~Arg() { }
inline std::string Arg::shortID( const std::string& valueId ) const
{
std::string id = "";
if ( _flag != "" )
id = Arg::flagStartString() + _flag;
else
id = Arg::nameStartString() + _name;
std::string delim = " ";
delim[0] = Arg::delimiter(); // ugly!!!
if ( _valueRequired )
id += delim + "<" + valueId + ">";
if ( !_required )
id = "[" + id + "]";
return id;
}
inline std::string Arg::longID( const std::string& valueId ) const
{
std::string id = "";
if ( _flag != "" )
{
id += Arg::flagStartString() + _flag;
if ( _valueRequired )
id += " <" + valueId + ">";
id += ", ";
}
id += Arg::nameStartString() + _name;
if ( _valueRequired )
id += " <" + valueId + ">";
return id;
}
inline bool Arg::operator==(const Arg& a) const
{
if ( ( _flag != "" && _flag == a._flag ) || _name == a._name)
return true;
else
return false;
}
inline std::string Arg::getDescription() const
{
std::string desc = "";
if ( _required )
desc = "(" + _requireLabel + ") ";
// if ( _valueRequired )
// desc += "(value required) ";
desc += _description;
return desc;
}
inline const std::string& Arg::getFlag() const { return _flag; }
inline const std::string& Arg::getName() const { return _name; }
inline bool Arg::isRequired() const { return _required; }
inline bool Arg::isValueRequired() const { return _valueRequired; }
inline bool Arg::isSet() const
{
if ( _alreadySet && !_xorSet )
return true;
else
return false;
}
inline bool Arg::isIgnoreable() const { return _ignoreable; }
inline void Arg::setRequireLabel( const std::string& s)
{
_requireLabel = s;
}
inline bool Arg::argMatches( const std::string& argFlag ) const
{
if ( ( argFlag == Arg::flagStartString() + _flag && _flag != "" ) ||
argFlag == Arg::nameStartString() + _name )
return true;
else
return false;
}
inline std::string Arg::toString() const
{
std::string s = "";
if ( _flag != "" )
s += Arg::flagStartString() + _flag + " ";
s += "(" + Arg::nameStartString() + _name + ")";
return s;
}
inline void Arg::_checkWithVisitor() const
{
if ( _visitor != NULL )
_visitor->visit();
}
/**
* Implementation of trimFlag.
*/
inline void Arg::trimFlag(std::string& flag, std::string& value) const
{
int stop = 0;
for ( int i = 0; static_cast<unsigned int>(i) < flag.length(); i++ )
if ( flag[i] == Arg::delimiter() )
{
stop = i;
break;
}
if ( stop > 1 )
{
value = flag.substr(stop+1);
flag = flag.substr(0,stop);
}
}
/**
* Implementation of _hasBlanks.
*/
inline bool Arg::_hasBlanks( const std::string& s ) const
{
for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ )
if ( s[i] == Arg::blankChar() )
return true;
return false;
}
inline void Arg::forceRequired()
{
_required = true;
}
inline void Arg::xorSet()
{
_alreadySet = true;
_xorSet = true;
}
/**
* Overridden by Args that need to added to the end of the list.
*/
inline void Arg::addToList( std::list<Arg*>& argList ) const
{
argList.push_front( const_cast<Arg*>(this) );
}
inline bool Arg::allowMore()
{
return false;
}
inline bool Arg::acceptsMultipleValues()
{
return _acceptsMultipleValues;
}
//////////////////////////////////////////////////////////////////////
//END Arg.cpp
//////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,191 @@
/**
* @file /include/ecl/command_line/arg_exception.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_ARG_EXCEPTION_H
#define TCLAP_ARG_EXCEPTION_H
#include <string>
#include <exception>
namespace ecl {
/**
* @brief Defines the exception that is thrown whenever a command line is created and parsed.
*
* A simple class that defines an argument exception. Should be caught
* whenever a CmdLine is created and parsed.
*/
class ArgException : public std::exception
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source.
* \param td - Text describing the type of ArgException it is.
* of the exception.
*/
ArgException( const std::string& text = "undefined exception",
const std::string& id = "undefined",
const std::string& td = "Generic ArgException")
: std::exception(),
_errorText(text),
_argId( id ),
_typeDescription(td)
{ }
/**
* Destructor.
*/
virtual ~ArgException() throw() { }
/**
* Returns the error text.
*/
std::string error() const { return ( _errorText ); }
/**
* Returns the argument id.
*/
std::string argId() const
{
if ( _argId == "undefined" )
return " ";
else
return ( "Argument: " + _argId );
}
/**
* Returns the arg id and error text.
*/
const char* what() const throw()
{
static std::string ex;
ex = _argId + " -- " + _errorText;
return ex.c_str();
}
/**
* Returns the type of the exception. Used to explain and distinguish
* between different child exceptions.
*/
std::string typeDescription() const
{
return _typeDescription;
}
private:
/**
* The text of the exception message.
*/
std::string _errorText;
/**
* The argument related to this exception.
*/
std::string _argId;
/**
* Describes the type of the exception. Used to distinguish
* between different child exceptions.
*/
std::string _typeDescription;
};
/**
* @brief Defines the exception that is thrown when an argument is improperly parsed.
*
* Thrown from within the child Arg classes when it fails to properly
* parse the argument it has been passed.
*/
class ArgParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
ArgParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string( "Exception found while parsing " ) +
std::string( "the value the Arg has been passed." ))
{ }
};
/**
* @brief Defines the exception when an argument is improperly specified.
*
* Thrown from CmdLine when the arguments on the command line are not
* properly specified, e.g. too many arguments, required argument missing, etc.
*/
class CmdLineParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
CmdLineParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string( "Exception found when the values ") +
std::string( "on the command line do not meet ") +
std::string( "the requirements of the defined ") +
std::string( "Args." ))
{ }
};
/**
* @brief Defines the exception that is thrown whenever a conflict in arguments occurs.
*
* Thrown from Arg and CmdLine when an Arg is improperly specified, e.g.
* same flag as another Arg, same name, etc.
*/
class SpecificationException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
SpecificationException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string("Exception found when an Arg object ")+
std::string("is improperly defined by the ") +
std::string("developer." ))
{ }
};
} // namespace ecl
#endif
@@ -0,0 +1,489 @@
/**
* @file /include/ecl/command_line/cmd_line.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_CMDLINE_H
#define TCLAP_CMDLINE_H
#include "switch_arg.hpp"
#include "multi_switch_arg.hpp"
#include "unlabeled_value_arg.hpp"
#include "unlabeled_multi_arg.hpp"
#include "xor_handler.hpp"
#include "help_visitor.hpp"
#include "version_visitor.hpp"
#include "ignore_rest_visitor.hpp"
#include "cmd_line_output.hpp"
#include "std_output.hpp"
#include "constraint.hpp"
#include "values_constraint.hpp"
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace ecl {
/**
* @brief Manages the command line parsing object.
*
* The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes.
*/
class CmdLine : public CmdLineInterface
{
protected:
/**
* The list of arguments that will be tested against the
* command line.
*/
std::list<Arg*> _argList;
/**
* The name of the program. Set to argv[0].
*/
std::string _progName;
/**
* A message used to describe the program. Used in the usage output.
*/
std::string _message;
/**
* The version to be displayed with the --version switch.
*/
std::string _version;
/**
* The number of arguments that are required to be present on
* the command line. This is set dynamically, based on the
* Args added to the CmdLine object.
*/
int _numRequired;
/**
* The character that is used to separate the argument flag/name
* from the value. Defaults to ' ' (space).
*/
char _delimiter;
/**
* The handler that manages xoring lists of args.
*/
XorHandler _xorHandler;
/**
* A list of Args to be explicitly deleted when the destructor
* is called. At the moment, this only includes the three default
* Args.
*/
std::list<Arg*> _argDeleteOnExitList;
/**
* A list of Visitors to be explicitly deleted when the destructor
* is called. At the moment, these are the Vistors created for the
* default Args.
*/
std::list<Visitor*> _visitorDeleteOnExitList;
/**
* Object that handles all output for the CmdLine.
*/
CmdLineOutput* _output;
/**
* Checks whether a name/flag string matches entirely matches
* the Arg::blankChar. Used when multiple switches are combined
* into a single argument.
* \param s - The message to be used in the usage.
*/
bool _emptyCombined(const std::string& s);
/**
* Perform a delete ptr; operation on ptr when this object is deleted.
*/
void deleteOnExit(Arg* ptr);
/**
* Perform a delete ptr; operation on ptr when this object is deleted.
*/
void deleteOnExit(Visitor* ptr);
private:
/**
* Encapsulates the code common to the constructors (which is all
* of it).
*/
void _constructor();
/**
* Is set to true when a user sets the output object. We use this so
* that we don't delete objects that are created outside of this lib.
*/
bool _userSetOutput;
/**
* Whether or not to automatically create help and version switches.
*/
bool _helpAndVersion;
public:
/**
* Command line constructor. Defines how the arguments will be
* parsed.
* \param message - The message to be used in the usage
* output.
* \param delimiter - The character that is used to separate
* the argument flag/name from the value. Defaults to ' ' (space).
* \param version - The version number to be used in the
* --version switch.
* \param helpAndVersion - Whether or not to create the Help and
* Version switches. Defaults to true.
*/
CmdLine(const std::string& message,
const char delimiter = ' ',
const std::string& version = "none",
bool helpAndVersion = true);
/**
* Deletes any resources allocated by a CmdLine object.
*/
virtual ~CmdLine();
/**
* Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added.
*/
void add( Arg& a );
/**
* An alternative add. Functionally identical.
* \param a - Argument to be added.
*/
void add( Arg* a );
/**
* Add two Args that will be xor'd. If this method is used, add does
* not need to be called.
* \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd.
*/
void xorAdd( Arg& a, Arg& b );
/**
* Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called.
* \param xors - List of Args to be added and xor'd.
*/
void xorAdd( std::vector<Arg*>& xors );
/**
* Parses the command line.
* \param argc - Number of arguments.
* \param argv - Array of arguments.
*/
void parse(int argc, char** argv);
/**
*
*/
CmdLineOutput* getOutput();
/**
*
*/
void setOutput(CmdLineOutput* co);
/**
*
*/
std::string& getVersion();
/**
*
*/
std::string& getProgramName();
/**
*
*/
std::list<Arg*>& getArgList();
/**
*
*/
XorHandler& getXorHandler();
/**
*
*/
char getDelimiter();
/**
*
*/
std::string& getMessage();
/**
*
*/
bool hasHelpAndVersion();
};
///////////////////////////////////////////////////////////////////////////////
//Begin CmdLine.cpp
///////////////////////////////////////////////////////////////////////////////
inline CmdLine::CmdLine(const std::string& m,
char delim,
const std::string& v,
bool help )
: _progName("not_set_yet"),
_message(m),
_version(v),
_numRequired(0),
_delimiter(delim),
_userSetOutput(false),
_helpAndVersion(help)
{
_constructor();
}
inline CmdLine::~CmdLine()
{
ArgListIterator argIter;
VisitorListIterator visIter;
for( argIter = _argDeleteOnExitList.begin();
argIter != _argDeleteOnExitList.end();
++argIter)
delete *argIter;
for( visIter = _visitorDeleteOnExitList.begin();
visIter != _visitorDeleteOnExitList.end();
++visIter)
delete *visIter;
if ( !_userSetOutput )
delete _output;
}
inline void CmdLine::_constructor()
{
_output = new StdOutput;
Arg::setDelimiter( _delimiter );
Visitor* v;
if ( _helpAndVersion )
{
v = new HelpVisitor( this, &_output );
SwitchArg* help = new SwitchArg("h","help",
"Displays usage information and exits.",
false, v);
add( help );
deleteOnExit(help);
deleteOnExit(v);
v = new VersionVisitor( this, &_output );
SwitchArg* vers = new SwitchArg("","version",
"Displays version information and exits.",
false, v);
add( vers );
deleteOnExit(vers);
deleteOnExit(v);
}
v = new IgnoreRestVisitor();
SwitchArg* ignore = new SwitchArg(Arg::flagStartString(),
Arg::ignoreNameString(),
"Ignores the rest of the labeled arguments following this flag.",
false, v);
add( ignore );
deleteOnExit(ignore);
deleteOnExit(v);
}
inline void CmdLine::xorAdd( std::vector<Arg*>& ors )
{
_xorHandler.add( ors );
for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++)
{
(*it)->forceRequired();
(*it)->setRequireLabel( "OR required" );
add( *it );
}
}
inline void CmdLine::xorAdd( Arg& a, Arg& b )
{
std::vector<Arg*> ors;
ors.push_back( &a );
ors.push_back( &b );
xorAdd( ors );
}
inline void CmdLine::add( Arg& a )
{
add( &a );
}
inline void CmdLine::add( Arg* a )
{
for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ )
if ( *a == *(*it) )
throw( SpecificationException(
"Argument with same flag/name already exists!",
a->longID() ) );
a->addToList( _argList );
if ( a->isRequired() )
_numRequired++;
}
inline void CmdLine::parse(int argc, char** argv)
{
try {
_progName = argv[0];
// this step is necessary so that we have easy access to mutable strings.
std::vector<std::string> args;
for (int i = 1; i < argc; i++)
args.push_back(argv[i]);
int requiredCount = 0;
for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++)
{
bool matched = false;
for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++)
{
if ( (*it)->processArg( &i, args ) )
{
requiredCount += _xorHandler.check( *it );
matched = true;
break;
}
}
// checks to see if the argument is an empty combined switch ...
// and if so, then we've actually matched it
if ( !matched && _emptyCombined( args[i] ) )
matched = true;
if ( !matched && !Arg::ignoreRest() )
throw(CmdLineParseException("Couldn't find match for argument",
args[i]));
}
if ( requiredCount < _numRequired )
throw(CmdLineParseException("One or more required arguments missing!"));
if ( requiredCount > _numRequired )
throw(CmdLineParseException("Too many arguments!"));
} catch ( ArgException &e ) {
_output->failure(*this, e); exit(1);
}
}
inline bool CmdLine::_emptyCombined(const std::string& s)
{
if ( s[0] != Arg::flagStartChar() )
return false;
for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ )
if ( s[i] != Arg::blankChar() )
return false;
return true;
}
inline void CmdLine::deleteOnExit(Arg* ptr)
{
_argDeleteOnExitList.push_back(ptr);
}
inline void CmdLine::deleteOnExit(Visitor* ptr)
{
_visitorDeleteOnExitList.push_back(ptr);
}
inline CmdLineOutput* CmdLine::getOutput()
{
return _output;
}
inline void CmdLine::setOutput(CmdLineOutput* co)
{
_userSetOutput = true;
_output = co;
}
inline std::string& CmdLine::getVersion()
{
return _version;
}
inline std::string& CmdLine::getProgramName()
{
return _progName;
}
inline std::list<Arg*>& CmdLine::getArgList()
{
return _argList;
}
inline XorHandler& CmdLine::getXorHandler()
{
return _xorHandler;
}
inline char CmdLine::getDelimiter()
{
return _delimiter;
}
inline std::string& CmdLine::getMessage()
{
return _message;
}
inline bool CmdLine::hasHelpAndVersion()
{
return _helpAndVersion;
}
///////////////////////////////////////////////////////////////////////////////
//End CmdLine.cpp
///////////////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,130 @@
/**
* @file /include/ecl/command_line/cmd_line_interface.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_COMMANDLINE_INTERFACE_H
#define TCLAP_COMMANDLINE_INTERFACE_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
namespace ecl {
class Arg;
class CmdLineOutput;
class XorHandler;
/**
* @brief Managing interface for
* The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes.
*/
class CmdLineInterface
{
public:
/**
* Destructor
*/
virtual ~CmdLineInterface() {}
/**
* Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added.
*/
virtual void add( Arg& a )=0;
/**
* An alternative add. Functionally identical.
* \param a - Argument to be added.
*/
virtual void add( Arg* a )=0;
/**
* Add two Args that will be xor'd.
* If this method is used, add does
* not need to be called.
* \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd.
*/
virtual void xorAdd( Arg& a, Arg& b )=0;
/**
* Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called.
* \param xors - List of Args to be added and xor'd.
*/
virtual void xorAdd( std::vector<Arg*>& xors )=0;
/**
* Parses the command line.
* \param argc - Number of arguments.
* \param argv - Array of arguments.
*/
virtual void parse(int argc, char** argv)=0;
/**
* Returns the CmdLineOutput object.
*/
virtual CmdLineOutput* getOutput()=0;
/**
* \param co - CmdLineOutput object that we want to use instead.
*/
virtual void setOutput(CmdLineOutput* co)=0;
/**
* Returns the version string.
*/
virtual std::string& getVersion()=0;
/**
* Returns the program name string.
*/
virtual std::string& getProgramName()=0;
/**
* Returns the argList.
*/
virtual std::list<Arg*>& getArgList()=0;
/**
* Returns the XorHandler.
*/
virtual XorHandler& getXorHandler()=0;
/**
* Returns the delimiter string.
*/
virtual char getDelimiter()=0;
/**
* Returns the message string.
*/
virtual std::string& getMessage()=0;
/**
* Indicates whether or not the help and version switches were created
* automatically.
*/
virtual bool hasHelpAndVersion()=0;
};
} // namespace ecl
#endif
@@ -0,0 +1,69 @@
/**
* @file /include/ecl/command_line/cmd_line_output.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_CMDLINEOUTPUT_H
#define TCLAP_CMDLINEOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace ecl {
class CmdLineInterface;
class ArgException;
/**
* @brief Tclap class indirectly used by children for standardising outputs.
*
* The interface that any output object must implement.
*/
class CmdLineOutput
{
public:
/**
* Virtual destructor.
*/
virtual ~CmdLineOutput() {}
/**
* Generates some sort of output for the USAGE.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c)=0;
/**
* Generates some sort of output for the version.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c)=0;
/**
* Generates some sort of output for a failure.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure( CmdLineInterface& c,
ArgException& e )=0;
};
} // namespace ecl
#endif
@@ -0,0 +1,65 @@
/**
* @file /include/ecl/command_line/constraint.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_CONSTRAINT_H
#define TCLAP_CONSTRAINT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace ecl {
/**
* @brief Defines the interaction between an argument and a constraint.
*
* The interface that defines the interaction between the Arg and Constraint.
*/
template<class T>
class Constraint
{
public:
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const =0;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const =0;
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T& value) const =0;
/**
* Destructor.
* Silences warnings about Constraint being a base class with virtual
* functions but without a virtual destructor.
*/
virtual ~Constraint() { ; }
};
} // namespace ecl
#endif
@@ -0,0 +1,270 @@
/**
* @file /include/ecl/command_line/docbook_output.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_DOCBOOKOUTPUT_H
#define TCLAP_DOCBOOKOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "xor_handler.hpp"
#include "arg.hpp"
namespace ecl {
/**
* @brief TClap class used for generating docbook output.
*
* A class that generates DocBook output for usage() method for the
* given CmdLine and its Args.
*/
class DocBookOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
/**
* Substitutes the char r for string x in string s.
* \param s - The string to operate on.
* \param r - The char to replace.
* \param x - What to replace r with.
*/
void substituteSpecialChars( std::string& s, char r, std::string& x );
void removeChar( std::string& s, char r);
void printShortArg(Arg* it);
void printLongArg(Arg* it);
};
inline void DocBookOutput::version(CmdLineInterface& _cmd)
{
std::cout << _cmd.getVersion() << std::endl;
}
inline void DocBookOutput::usage(CmdLineInterface& _cmd )
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
std::cout << "<?xml version='1.0'?>" << std::endl;
std::cout << "<!DOCTYPE book PUBLIC \"-//Norman Walsh//DTD DocBk XML V4.2//EN\"" << std::endl;
std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl << std::endl;
std::cout << "<book>" << std::endl;
std::cout << "<refentry>" << std::endl;
std::cout << "<refmeta>" << std::endl;
std::cout << "<refentrytitle>" << std::endl;
std::cout << progName << std::endl;
std::cout << "</refentrytitle>" << std::endl;
std::cout << "<manvolnum>1</manvolnum>" << std::endl;
std::cout << "</refmeta>" << std::endl;
std::cout << "<refnamediv>" << std::endl;
std::cout << "<refname>" << std::endl;
std::cout << progName << std::endl;
std::cout << "</refname>" << std::endl;
std::cout << "</refnamediv>" << std::endl;
std::cout << "<cmdsynopsis>" << std::endl;
std::cout << "<command>" << progName << "</command>" << std::endl;
// xor
for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
{
std::cout << "<group choice='req'>" << std::endl;
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++ )
printShortArg((*it));
std::cout << "</group>" << std::endl;
}
// rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
printShortArg((*it));
std::cout << "</cmdsynopsis>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Description</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << _cmd.getMessage() << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Options</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << "<itemizedlist>" << std::endl;
// xor
for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
{
std::cout << "<itemizedlist>" << std::endl;
size_t xlen = xorList.size() - 1;
size_t xcount = 0;
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++, xcount++ )
{
printLongArg((*it));
if ( xcount < xlen )
std::cout << "<listitem>OR</listitem>" << std::endl;
}
std::cout << "</itemizedlist>" << std::endl;
}
// rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
printLongArg((*it));
std::cout << "</itemizedlist>" << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Version</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << version << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "</refentry>" << std::endl;
std::cout << "</book>" << std::endl;
}
inline void DocBookOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
std::cout << e.what() << std::endl;
}
inline void DocBookOutput::substituteSpecialChars( std::string& s,
char r,
std::string& x )
{
size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos )
{
s.erase(p,1);
s.insert(p,x);
}
}
inline void DocBookOutput::removeChar( std::string& s, char r)
{
size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos )
{
s.erase(p,1);
}
}
inline void DocBookOutput::printShortArg(Arg* a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string id = a->shortID();
substituteSpecialChars(id,'<',lt);
substituteSpecialChars(id,'>',gt);
removeChar(id,'[');
removeChar(id,']');
std::string choice = "opt";
if ( a->isRequired() )
choice = "req";
std::string repeat = "norepeat";
if ( a->acceptsMultipleValues() )
repeat = "repeat";
std::cout << "<arg choice='" << choice
<< "' repeat='" << repeat << "'>"
<< id << "</arg>" << std::endl;
}
inline void DocBookOutput::printLongArg(Arg* a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string id = a->longID();
substituteSpecialChars(id,'<',lt);
substituteSpecialChars(id,'>',gt);
removeChar(id,'[');
removeChar(id,']');
std::string desc = a->getDescription();
substituteSpecialChars(desc,'<',lt);
substituteSpecialChars(desc,'>',gt);
std::cout << "<simplelist>" << std::endl;
std::cout << "<member>" << std::endl;
std::cout << id << std::endl;
std::cout << "</member>" << std::endl;
std::cout << "<member>" << std::endl;
std::cout << desc << std::endl;
std::cout << "</member>" << std::endl;
std::cout << "</simplelist>" << std::endl;
}
} // namespace ecl
#endif
@@ -0,0 +1,65 @@
/**
* @file /include/ecl/command_line/help_visitor.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_HELP_VISITOR_H
#define TCLAP_HELP_VISITOR_H
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "visitor.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to define the interface for visitors.
*
* A Visitor object that calls the usage method of the given CmdLineOutput
* object for the specified CmdLine object.
*/
class HelpVisitor: public Visitor
{
protected:
/**
* The CmdLine the output will be generated for.
*/
CmdLineInterface* _cmd;
/**
* The output object.
*/
CmdLineOutput** _out;
public:
/**
* Constructor.
* \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output.
*/
HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out)
: Visitor(), _cmd( cmd ), _out( out ) { }
/**
* Calls the usage method of the CmdLineOutput for the
* specified CmdLine.
*/
void visit() { (*_out)->usage(*_cmd); exit(0); }
};
} // namespace ecl
#endif
@@ -0,0 +1,48 @@
/**
* @file /include/ecl/command_line/ignore_rest_visitor.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_IGNORE_REST_VISITOR_H
#define TCLAP_IGNORE_REST_VISITOR_H
#include "visitor.hpp"
#include "arg.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to define the interface for visitors.
*
* A Vistor that tells the CmdLine to begin ignoring arguments after
* this one is parsed.
*/
class IgnoreRestVisitor: public Visitor
{
public:
/**
* Constructor.
*/
IgnoreRestVisitor() : Visitor() {}
/**
* Sets Arg::_ignoreRest.
*/
void visit() { Arg::beginIgnoring(); }
};
} // namespace ecl
#endif
@@ -0,0 +1,520 @@
/**
* @file /include/ecl/command_line/multi_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_MULTIPLE_ARGUMENT_H
#define TCLAP_MULTIPLE_ARGUMENT_H
#include <string>
#include <vector>
#include <cstdio>
#include "arg.hpp"
#include "constraint.hpp"
#define HAVE_SSTREAM
#if defined(HAVE_SSTREAM)
#include <sstream>
#elif defined(HAVE_STRSTREAM)
#include <strstream>
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
namespace ecl {
template<class T> class MultiArg;
namespace MultiArgHelper {
enum Error_e { EXTRACT_FAILURE = 1000, EXTRACT_TOO_MANY };
/**
* @brief TClap class internally used for extracting value args.
*
* This class is used to extract a value from an argument.
* It is used because we need a special implementation to
* deal with std::string and making a specialiced function
* puts it in the T segment, thus generating link errors.
* Having a specialiced class makes the symbols weak.
* This is not pretty but I don't know how to make it
* work any other way.
*/
template<class T>
class ValueExtractor
{
friend class MultiArg<T>;
private:
/**
* Reference to the vector of values where the result of the
* extraction will be put.
*/
std::vector<T> &_values;
/**
* Constructor.
* \param values - Where the values extracted will be put.
*/
ValueExtractor(std::vector<T> &values) : _values(values) {}
/**
* Method that will attempt to parse the input stream for values
* of type T.
* \param val - Where the values parsed will be put.
*/
int extractValue( const std::string& val )
{
T temp;
#if defined(HAVE_SSTREAM)
std::istringstream is(val);
#elif defined(HAVE_STRSTREAM)
std::istrstream is(val.c_str());
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
int valuesRead = 0;
while ( is.good() )
{
if ( is.peek() != EOF )
is >> temp;
else
break;
valuesRead++;
}
if ( is.fail() )
return EXTRACT_FAILURE;
if ( valuesRead > 1 )
return EXTRACT_TOO_MANY;
_values.push_back(temp);
return 0;
}
};
/**
* @brief TClap class internally used for string handling.
*
* Specialization for string. This is necessary because istringstream
* operator>> is not able to ignore spaces... meaning -x "X Y" will only
* read 'X'... and thus the specialization.
*/
template<>
class ValueExtractor<std::string>
{
friend class MultiArg<std::string>;
private:
/**
* Reference to the vector of strings where the result of the
* extraction will be put.
*/
std::vector<std::string> &_values;
/**
* Constructor.
* \param values - Where the strings extracted will be put.
*/
ValueExtractor(std::vector<std::string> &values) : _values(values) {}
/**
* Method that will attempt to parse the input stream for values
* of type std::string.
* \param val - Where the values parsed will be put.
*/
int extractValue( const std::string& val )
{
_values.push_back( val );
return 0;
}
};
} //namespace MultiArgHelper
/**
* An argument that allows multiple values of type T to be specified. Very
* similar to a ValueArg, except a vector of values will be returned
* instead of just one.
*/
template<class T>
class MultiArg : public Arg
{
protected:
/**
* The list of values parsed from the CmdLine.
*/
std::vector<T> _values;
/**
* The description of type T to be used in the usage.
*/
std::string _typeDesc;
/**
* A list of constraint on this Arg.
*/
Constraint<T>* _constraint;
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - The string to be read.
*/
void _extractValue( const std::string& val );
bool _allowMore;
public:
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v = NULL);
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v = NULL );
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns a vector of type T containing the values parsed from
* the command line.
*/
const std::vector<T>& getValue();
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string& val="val") const;
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string& val="val") const;
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
virtual bool isRequired() const;
virtual bool allowMore();
};
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{
_acceptsMultipleValues = true;
}
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{
parser.add( this );
_acceptsMultipleValues = true;
}
/**
*
*/
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{
_acceptsMultipleValues = true;
}
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{
parser.add( this );
_acceptsMultipleValues = true;
}
template<class T>
const std::vector<T>& MultiArg<T>::getValue() { return _values; }
template<class T>
bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
std::string flag = args[*i];
std::string value = "";
trimFlag( flag, value );
if ( argMatches( flag ) )
{
if ( Arg::delimiter() != ' ' && value == "" )
throw( ArgParseException(
"Couldn't find delimiter for this argument!",
toString() ) );
// always take the first one, regardless of start string
if ( value == "" )
{
(*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
_extractValue( args[*i] );
else
throw( ArgParseException("Missing a value for this argument!",
toString() ) );
}
else
_extractValue( value );
/*
// continuing taking the args until we hit one with a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
return false;
}
/**
*
*/
template<class T>
std::string MultiArg<T>::shortID(const std::string& /*val*/) const
{
std::string id = Arg::shortID(_typeDesc) + " ... ";
return id;
}
/**
*
*/
template<class T>
std::string MultiArg<T>::longID(const std::string& /*val*/) const
{
std::string id = Arg::longID(_typeDesc) + " (accepted multiple times)";
return id;
}
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
template<class T>
bool MultiArg<T>::isRequired() const
{
if ( _required )
{
if ( _values.size() > 1 )
return false;
else
return true;
}
else
return false;
}
template<class T>
void MultiArg<T>::_extractValue( const std::string& val )
{
MultiArgHelper::ValueExtractor<T> ve(_values);
int err = ve.extractValue(val);
if ( err == MultiArgHelper::EXTRACT_FAILURE )
throw( ArgParseException("Couldn't read argument value "
"from string '" + val + "'", toString() ) );
if(err == MultiArgHelper::EXTRACT_TOO_MANY)
throw( ArgParseException("More than one valid value "
"parsed from string '" + val + "'",
toString() ) );
if ( _constraint != NULL )
if ( ! _constraint->check( _values.back() ) )
throw( CmdLineParseException( "Value '" + val +
"' does not meet constraint: " +
_constraint->description(),
toString() ) );
}
template<class T>
bool MultiArg<T>::allowMore()
{
bool am = _allowMore;
_allowMore = true;
return am;
}
} // namespace ecl
#endif
@@ -0,0 +1,192 @@
/**
* @file /include/ecl/command_line/multi_switch_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_MULTI_SWITCH_ARG_H
#define TCLAP_MULTI_SWITCH_ARG_H
#include <string>
#include <vector>
#include "switch_arg.hpp"
namespace ecl {
/**
* A multiple switch argument. If the switch is set on the command line, then
* the getValue method will return the number of times the switch appears.
*/
class MultiSwitchArg : public SwitchArg
{
protected:
/**
* The value of the switch.
*/
int _value;
public:
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
int init = 0,
Visitor* v = NULL);
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
int init = 0,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the SwitchArg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns int, the number of times the switch has been set.
*/
int getValue();
/**
* Returns the shortID for this Arg.
*/
std::string shortID(const std::string& val) const;
/**
* Returns the longID for this Arg.
*/
std::string longID(const std::string& val) const;
};
//////////////////////////////////////////////////////////////////////
//BEGIN MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
int init,
Visitor* v )
: SwitchArg(flag, name, desc, false, v),
_value( init )
{ }
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
int init,
Visitor* v )
: SwitchArg(flag, name, desc, false, v),
_value( init )
{
parser.add( this );
}
inline int MultiSwitchArg::getValue() { return _value; }
inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( argMatches( args[*i] ))
{
// so the isSet() method will work
_alreadySet = true;
// Matched argument: increment value.
++_value;
_checkWithVisitor();
return true;
}
else if ( combinedSwitchesMatch( args[*i] ) )
{
// so the isSet() method will work
_alreadySet = true;
// Matched argument: increment value.
++_value;
// Check for more in argument and increment value.
while ( combinedSwitchesMatch( args[*i] ) )
++_value;
_checkWithVisitor();
return false;
}
else
return false;
}
inline std::string MultiSwitchArg::shortID(const std::string& val) const
{
std::string id = Arg::shortID() + " ... " + val;
return id;
}
inline std::string MultiSwitchArg::longID(const std::string& val) const
{
std::string id = Arg::longID() + " (accepted multiple times) " + val;
return id;
}
//////////////////////////////////////////////////////////////////////
//END MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,53 @@
/**
* @file /include/ecl/command_line/optional_unlabeled_tracker.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H
#define TCLAP_OPTIONAL_UNLABELED_TRACKER_H
#include <string>
namespace ecl {
class OptionalUnlabeledTracker
{
public:
static void check( bool req, const std::string& argName );
static void gotOptional() { alreadyOptionalRef() = true; }
static bool& alreadyOptional() { return alreadyOptionalRef(); }
private:
static bool& alreadyOptionalRef() { static bool ct = false; return ct; }
};
inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName )
{
if ( OptionalUnlabeledTracker::alreadyOptional() )
throw( SpecificationException(
"You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg",
argName ) );
if ( !req )
OptionalUnlabeledTracker::gotOptional();
}
} // namespace ecl
#endif
@@ -0,0 +1,288 @@
/**
* @file /include/ecl/command_line/std_output.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_STDCMDLINEOUTPUT_H
#define TCLAP_STDCMDLINEOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <cmath>
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "xor_handler.hpp"
#include "arg.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to handle CmdLine arguments.
*
* A class that isolates any output from the CmdLine object so that it
* may be easily modified.
*/
class StdOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
/**
* Writes a brief usage message with short args.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _shortUsage( CmdLineInterface& c, std::ostream& os ) const;
/**
* Writes a longer usage message with long and short args,
* provides descriptions and prints message.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _longUsage( CmdLineInterface& c, std::ostream& os ) const;
/**
* This function inserts line breaks and indents long strings
* according the params input. It will only break lines at spaces,
* commas and pipes.
* \param os - The stream to be printed to.
* \param s - The string to be printed.
* \param maxWidth - The maxWidth allowed for the output line.
* \param indentSpaces - The number of spaces to indent the first line.
* \param secondLineOffset - The number of spaces to indent the second
* and all subsequent lines in addition to indentSpaces.
*/
void spacePrint( std::ostream& os,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset ) const;
};
inline void StdOutput::version(CmdLineInterface& _cmd)
{
std::string progName = _cmd.getProgramName();
std::string interface_version = _cmd.getVersion();
std::cout << std::endl << progName << " version: "
<< interface_version << std::endl << std::endl;
}
inline void StdOutput::usage(CmdLineInterface& _cmd )
{
std::cout << std::endl << "USAGE: " << std::endl << std::endl;
_shortUsage( _cmd, std::cout );
std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl;
_longUsage( _cmd, std::cout );
std::cout << std::endl;
}
inline void StdOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
std::string progName = _cmd.getProgramName();
std::cerr << "PARSE ERROR: " << e.argId() << std::endl
<< " " << e.error() << std::endl << std::endl;
if ( _cmd.hasHelpAndVersion() )
{
std::cerr << "Brief USAGE: " << std::endl;
_shortUsage( _cmd, std::cerr );
std::cerr << std::endl << "For complete USAGE and HELP type: "
<< std::endl << " " << progName << " --help"
<< std::endl << std::endl;
}
else
usage(_cmd);
}
inline void StdOutput::_shortUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
std::string s = progName + " ";
// first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
{
s += " {";
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++ )
s += (*it)->shortID() + "|";
s[s.length()-1] = '}';
}
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
s += " " + (*it)->shortID();
// if the program name is too long, then adjust the second line offset
int secondLineOffset = static_cast<int>(progName.length()) + 2;
if ( secondLineOffset > 75/2 )
secondLineOffset = static_cast<int>(75/2);
spacePrint( os, s, 75, 3, secondLineOffset );
//spacePrint( std::cout, s, 75, 3, secondLineOffset );
}
inline void StdOutput::_longUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string message = _cmd.getMessage();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
// first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
{
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end();
it++ )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
if ( it+1 != xorList[i].end() )
spacePrint(os, "-- OR --", 75, 9, 0);
}
os << std::endl << std::endl;
}
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
os << std::endl;
}
os << std::endl;
spacePrint( os, message, 75, 3, 0 );
}
inline void StdOutput::spacePrint( std::ostream& os,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset ) const
{
int len = static_cast<int>(s.length());
if ( (len + indentSpaces > maxWidth) && maxWidth > 0 )
{
int allowedLen = maxWidth - indentSpaces;
int start = 0;
while ( start < len )
{
// find the substring length
int stringLen = std::min<int>( len - start, allowedLen );
// trim the length so it doesn't end in middle of a word
if ( stringLen == allowedLen )
while ( s[stringLen+start] != ' ' &&
s[stringLen+start] != ',' &&
s[stringLen+start] != '|' &&
stringLen >= 0 )
stringLen--;
// ok, the word is longer than the line, so just split
// wherever the line ends
if ( stringLen <= 0 )
stringLen = allowedLen;
// check for newlines
for ( int i = 0; i < stringLen; i++ )
if ( s[start+i] == '\n' )
stringLen = i+1;
// print the indent
for ( int i = 0; i < indentSpaces; i++ )
os << " ";
if ( start == 0 )
{
// handle second line offsets
indentSpaces += secondLineOffset;
// adjust allowed len
allowedLen -= secondLineOffset;
}
os << s.substr(start,stringLen) << std::endl;
// so we don't start a line with a space
while ( s[stringLen+start] == ' ' && start < len )
start++;
start += stringLen;
}
}
else
{
for ( int i = 0; i < indentSpaces; i++ )
os << " ";
os << s << std::endl;
}
}
} // namespace ecl
#endif

Some files were not shown because too many files have changed in this diff Show More